使用Mockito的Spring Boot测试:在单元测试期间,@ Validated批注将被忽略

时间:2018-12-12 22:17:57

标签: spring-boot junit mockito springmockito

我正在使用Spring Boot 2.1.1,JUnit 5,Mockito 2.23.4。

        <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>

这是我的控制器:

@RestController
@Validated
public class AramaController {

    @ResponseStatus(value = HttpStatus.OK)
    @GetMapping("/arama")
    public List<Arama> arama(@RequestParam @NotEmpty @Size(min = 4, max = 20) String query) {
        return aramaService.arama(query);
    }
}

此控制器正常工作。

没有“ query”参数的卷曲返回错误请求400:

~$ curl http://localhost:8080/arama -v
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /arama HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.58.0
> Accept: */*
> 
< HTTP/1.1 400 
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Length: 0
< Date: Wed, 12 Dec 2018 21:47:11 GMT
< Connection: close
< 
* Closing connection 0

以“ query = a”为参数的卷曲也返回错误请求400:

~$ curl http://localhost:8080/arama?query=a -v
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /arama?query=a HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.58.0
> Accept: */*
> 
< HTTP/1.1 400 
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Wed, 12 Dec 2018 21:47:33 GMT
< Connection: close
< 
* Closing connection 0
{"message":"Input error","details":["size must be between 4 and 20"]}

在服务器上运行时,此控制器和验证可以完美地工作。

在单元测试期间,@ Validated注释似乎没有任何作用。

这是我的测试代码:

@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

由于@Valid批注通过了我的其他测试用例,并且它们在不加载Spring上下文的情况下工作,因此有没有办法使@Validated批注在Mockito中也可以正常工作(再次,在不加载Spring上下文的情况下)?

2 个答案:

答案 0 :(得分:0)

也许您可以尝试使用@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);
    }
}

答案 1 :(得分:0)

我在其他地方得到了答案,想分享一下:

  

如果不启动上下文,则不会有@Validator   经过测试,因为验证程序实例是Spring Bean。但是,@ Valid   将按照JSR-303标准运行。

     

到目前为止,我的建议是。

@SpringBootTest
@ExtendWith(SpringExtension.class)