在SpringBoot中编写单元测试而不启动应用程序

use*_*249 6 junit spring-boot

正在 springBoot 中开发微服务。正在为 Service 和 DAO 层编写单元测试。当我使用@SpringBootTest时,它会在构建时启动应用程序。但是当我运行单元测试时它不应该启动应用程序。我使用了@RunWith(SpringRunner.class),但无法在 junit 类中使用@Autowired类实例。如何配置不应启动应用程序的 junit 测试类以及如何在 junit 类中@Autowired类实例。

小智 2

如果您不想启动完整的应用程序,请使用 MockitoJUnitRunner 进行 JUnit5 测试。

任何服务、存储库和接口都可以通过 @Mock 注解进行模拟。

@InjectMocks 用于需要测试的 Class 对象。

这是一个例子。

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
public class AServiceTest {
    
    @InjectMocks
    AService aService;
    
    @Mock
    ARepository aRepository;
    
    @Mock
    UserService userService;
    
    
    @Before
    public void setUp() {
        // MockitoAnnotations.initMocks(this);
        // anything needs to be done before each test.
    }
    
    @Test
    public void loginTest() {
        Mockito.when(aRepository.findByUsername(ArgumentMatchers.anyString())).thenReturn(Optional.empty());
        String result = aService.login("test");
        assertEquals("false", result);
    }
Run Code Online (Sandbox Code Playgroud)