Spring boot 使用Mockito进行的Spring启动测试:@在单元测试期间,已验证的注释被忽略
我使用的是SpringBoot2.1.1、JUnit5和Mockito2.23.4Spring boot 使用Mockito进行的Spring启动测试:@在单元测试期间,已验证的注释被忽略,spring-boot,junit,mockito,springmockito,Spring Boot,Junit,Mockito,Springmockito,我使用的是SpringBoot2.1.1、JUnit5和Mockito2.23.4 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.23.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>2.23.4</version>
<scope>test</scope>
</dependency>
此测试导致以下故障:
java.lang.AssertionError: Status expected:<400> but was:<200>
Expected :400
Actual :200
java.lang.AssertionError:应为状态:但为:
预计:400
实际:200
既然@Valid注释通过了我的其他测试用例,并且它们在不加载Spring上下文的情况下工作,那么有没有办法让@Validated注释在Mockito(同样,在不加载Spring上下文的情况下)也能工作呢?也许您可以尝试使用
@WebMvcTest
并添加SpringExtension
@ExtendWith({SpringExtension.class, MockitoExtension.class})
@WebMvcTest(AramaController.class)
class AramaControllerTest {
@Mock
private AramaService aramaService;
@InjectMocks
private AramaController aramaController;
@Autowired
private MockMvc mockMvc;
@Test
void aramaValidationError() throws Exception {
mockMvc
.perform(
get("/arama").param("query", "a")
)
.andExpect(status().isBadRequest());
verifyNoMoreInteractions(aramaService);
}
}
我在别处得到了答案,并想与大家分享: 如果不启动上下文,您将无法获得@Validator 测试,因为验证器实例是Springbean。但是,@有效 将按照JSR-303标准工作 到目前为止,我能建议的是
@SpringBootTest
@ExtendWith(SpringExtension.class)
既然可以在不加载Spring上下文的情况下测试“@Valid”注释,那么有没有办法使“@Validated”注释也能工作呢?当您有
@springbootest
注释时,@ExtendWith
注释是多余的。
@ExtendWith(MockitoExtension.class)
class AramaControllerTest {
@Mock
private AramaService aramaService;
@InjectMocks
private AramaController aramaController;
private MockMvc mockMvc;
@BeforeEach
private void setUp() {
mockMvc = MockMvcBuilders
.standaloneSetup(aramaCcontroller)
.setControllerAdvice(new RestResponseEntityExceptionHandler())
.build();
}
@Test
void aramaValidationError() throws Exception {
mockMvc
.perform(
get("/arama").param("query", "a")
)
.andExpect(status().isBadRequest());
verifyNoMoreInteractions(aramaService);
}
}
java.lang.AssertionError: Status expected:<400> but was:<200>
Expected :400
Actual :200
@ExtendWith({SpringExtension.class, MockitoExtension.class})
@WebMvcTest(AramaController.class)
class AramaControllerTest {
@Mock
private AramaService aramaService;
@InjectMocks
private AramaController aramaController;
@Autowired
private MockMvc mockMvc;
@Test
void aramaValidationError() throws Exception {
mockMvc
.perform(
get("/arama").param("query", "a")
)
.andExpect(status().isBadRequest());
verifyNoMoreInteractions(aramaService);
}
}
@SpringBootTest
@ExtendWith(SpringExtension.class)