回答想測試這樣的結構:的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