[英]Testing SpringBoot RestController using @WebMvcTest and Mockito BDDMockito
I am quite new to testing and recently i encounter something weird, or maybe not weird, for the initiated.我对测试很陌生,最近我遇到了一些奇怪的事情,或者对于初学者来说可能并不奇怪。
SpringBoot version: 2.2.4.RELEASE SpringBoot版本:2.2.4.RELEASE
Mockito core: 3.1.0 Mockito 核心:3.1.0
Use Case: RestController test using @WebMvcTest slice, MockBean, MockMvc & BDDMockito:用例:使用@WebMvcTest 切片、MockBean、MockMvc 和 BDDMockito 进行 RestController 测试:
@WebMvcTest(Controller.class)
@AutoConfigureMockMvc(addFilters = false)
public class ControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private Service service;
@Test
@DisplayName("Some meaningful name")
public void getXXXShouldBeSuccessful() throws Exception {
...
//NOTE: I know creating objectDto here is useless, but i would like to understand
//why it doesn't work when it is passed in the method
//ObjectDto objectDto = new ObjectDto();
//objectDto.someSetter(id);
...
given(service.methodName((ObjectDto) any(Object.class))).willReturn(true); // This works
//given(service.methodName(objectDto)).willReturn(true); //This doesn't work
this.mockMvc.perform(post(some endpoint)...
And my controller:还有我的 controller:
@PostMapping(value = "/{id}")
public ResponseEntity<JsonResponse> someMethod(
@PathVariable String id,
@Valid @RequestBody ObjectDto objectDto) {
objectDto.someSetter(id);
if(service.methodName(objectDto)) // <============ Returns false
//Expected true, but if(service.methodName(objectDto)) is false when testing,
//although both objectDto(in my test, and here in the
//controller, has the same exact property values)
I found the solution by using (ObjectDto) any(Object.class)
, but it would be great to understand why //given(service.methodName(objectDto)).willReturn(true);我通过使用(ObjectDto) any(Object.class)
找到了解决方案,但最好理解为什么//given(service.methodName(objectDto)).willReturn(true); doesn't work.不起作用。
Is it because since i am mocking the service method, Mockito doesn't care about what object is being passed in the method?是不是因为我是mocking服务方法,Mockito不关心object在方法中传递了什么?
NOTE 1: objectDTO is just a POJO.注 1:objectDTO 只是一个 POJO。
NOTE 2: if objectDTO is replaced by a Map
, it works!!!注意 2:如果将 objectDTO 替换为Map
,它就可以工作!!!
Try this:试试这个:
when(service.methodName(any(ObjectDto.class)).thenReturn(true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.