Junit 测试未自动连接我的服务 class。但它在控制器中工作

The Junit Test not autowired my service class. But it works in the controller

我不知道为什么会这样,服务的自动装配在控制器中工作但在 Junit 测试中不工作class

这是我的 JUnit 测试:

package com.crmbackend.user;
import static org.assertj.core.api.Assertions.assertThat; 
import org.junit.jupiter.api.Test;
import com.crmbackend.entity.Role;
import com.crmbackend.entity.User;
import com.crmbackend.userService.UserService;
@DataJpaTest(showSql = true)
@AutoConfigureTestDatabase(replace = Replace.NONE)
@Rollback(false)

public class UserServiceTests {

    @Autowired
    private TestEntityManager entityManager;
    @Autowired
    private UserService service;

    @Test
    public void testCreateNewUserWithSingleRolePasswordEncode() {
        Role roleUser = entityManager.find(Role.class, 3);
        User userLucas = new User("lucas9324", "Lucas", "Tom", "qqq542417349", "Lucas9324@outlook.com", "7364832234");
        userLucas.addRole(roleUser);

        User savedUser = service.save(userLucas);
        assertThat(savedUser.getId()).isGreaterThan(0);
    }

}

这是我的服务class:

package com.crmbackend.userService;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.crmbackend.entity.User;

@Service
@Transactional
public class UserService {

    @Autowired
    private UserRepository userRepo;

    @Autowired
    private RoleRepository roleRepo;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public User getByUsername(String username) {
        return userRepo.getUserByUsername(username);
    }

    private void encodePassword(User user) {
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);
    }


    public User save(User user) {
        boolean isUpdatingUser = (user.getId() != null);
        if (isUpdatingUser) {
            User existingUser = userRepo.findById(user.getId()).get();

            if (user.getPassword().isEmpty()) {
                user.setPassword(existingUser.getPassword());
            } else {
                encodePassword(user);
            }

        } else {
            encodePassword(user);
        }
        return userRepo.save(user);

    }

    
}

的@Autowired
 @Autowired
    private UserService service;

在控制器中工作正常但在 JUnit 测试中不工作.... 总是遇到没有找到符合条件的 bean 的问题。

有什么建议吗?

DataJpaTest 是切片测试,它不会加载整个 Spring 应用程序上下文,即它不会加载您的服务,而只会加载测试 JPA 功能所需的内容。

如果您想将 UserService 作为 bean 加载,则需要导入。

然而,鉴于所有依赖项也在您的 UserService 中自动装配,您最好只使用 SpringBootTest 加载整个上下文。

如果加载整个上下文花费的时间太长,您可以排除 autoconfigurations/configurations,如果您在配置上使用组件扫描,则过滤组件扫描。

有关DataJpaTest

的信息

https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing.spring-boot-applications.autoconfigured-spring-data-jpa

You can use the @DataJpaTest annotation to test JPA applications. By default, it scans for @Entity classes and configures Spring Data JPA repositories. If an embedded database is available on the classpath, it configures one as well. SQL queries are logged by default by setting the spring.jpa.show-sql property to true. This can be disabled using the showSql() attribute of the annotation.

Regular @Component and @ConfigurationProperties beans are not scanned when the @DataJpaTest annotation is used. @EnableConfigurationProperties can be used to include @ConfigurationProperties beans.