【发布时间】:2022-02-03 07:37:16
【问题描述】:
我的项目是一个简单的 Spring Boot 应用程序,它没有 main/@SpringBootApplication 类。它用作其他模块的依赖库。我正在尝试为该项目中存在的类编写单元测试,如下所示,并得到以下粘贴错误。非常感谢任何快速帮助。
pom 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<!-- exclude junit 4 -->
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- junit 5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
由于本项目没有主类,所以使用下面的配置类来获取spring应用上下文。
@Configuration
public class TestServiceConfig {
@Bean
public TestService productService() {
return Mockito.mock(TestService.class);
}
@Bean
public MongoDriverService productMongo() {
return Mockito.mock(MongoDriverService.class);
}
}
下面是我抛出异常的测试类。实际的 java 类有一个名为 getPlanCode 的方法(它需要 6 个参数)并返回 void。在此方法中,mongo 对象用于连接数据库,因此我在服务对象上使用了@InjectMocks。
public class ValidationServiceTest {
@Mock
MongoDriverService mongo;
@InjectMocks
TestService service;
@Test
@DisplayName("Test Get Plan Code positive")
public void getPlanCodeTest() {
doNothing().when(service).getPlanCode(anyString(), anyString(), any(Batch.class), any(BatchFile.class), any(Document.class), anyString());
service.getPlanCode(anyString(), anyString(), any(Batch.class), any(BatchFile.class), any(Document.class), anyString());
verify(service, times(1)).getPlanCode(anyString(), anyString(), any(Batch.class), any(BatchFile.class), any(Document.class), anyString());
}
}
以下是例外情况
12:51:33.829 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@45b4c3a9 testClass = DefaultMedicareBFTAccumsValidationServiceTest, testInstance = com.anthem.rxsmart.service.standalone.batchvalidation.DefaultMedicareBFTAccumsValidationServiceTest@14dda234, testMethod = getPlanCodeTest@DValidationServiceTest, testException = org.mockito.exceptions.misusing.NotAMockException:
Argument passed to when() is not a mock!
Example of correct stubbing:
【问题讨论】:
标签: spring-boot mockito junit5 spring-boot-test