回答想测试这样的结构:的Mockito - 如何与自定义对象
@RequestMapping(value = "/test", method = POST)
public ResponseEntity test(@RequestBody TestRequest request, Errors errors) {
testValidator.validate(request, errors); // Spring Validator interface impl
if (errors.hasErrors())
return new ResponseEntity(HttpStatus.BAD_REQUEST);
return new ResponseEntity(HttpStatus.OK);
}
的Errors
对象由框架,而不是从我身边经过,所以没有更好的办法来改变它的行为测试但是使用了类似的Mockito的Answer
的:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ExampleTest {
@Autowired
private TestRestTemplate testRestTemplate;
@MockBean
private TestValidator testValidator;
@Test
public void test() {
doAnswer(new Answer<Errors>() {
@Override
public Errors answer(InvocationOnMock invocation) throws Throwable {
Errors errors = spy((Errors) invocation.getArguments()[1]);
//errors.rejectValue("id", "id", "id rejected");
doReturn(true).when(errors).hasErrors();
return errors;
}
}).when(testValidator).validate(any(), any());
ResponseEntity re = testRestTemplate
.postForEntity("/test", new TestRequest(213L), String.class);
assertEquals(HttpStatus.BAD_REQUEST, re.getStatusCode());
}
...但问题是errors.hasErrors()
尽管仍然在doAnswer
试块返回false
和断言失败,因为HTTP STA tus OK
。我预计Errors
对象将成为调用.validate()
后指定行为的间谍,但似乎我做错了什么。
那么,如何使用Mockito的doAnswer
返回一个自定义对象?
你这样做,你如何“注入”你的testValidator到测试的实例? – 2016-09-18 10:58:14
(我还建议你使用spring-mvc-test) – 2016-09-18 10:59:11
@RC,使用新的Spring测试特性'@ MockBean'注释,其行为与Mockito的'@ Mock'完全一样 – WildDev