【发布时间】:2015-03-19 02:28:42
【问题描述】:
我正在用 Spring MVC + axon 为我的控制器编写集成测试。
我的控制器是一个简单的 RestController,有一个方法:
@RequestMapping(value = "/", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void createEventProposal(@RequestBody CreateEventProposalForm form) {
CreateEventProposalCommand command = new CreateEventProposalCommand(
new EventProposalId(),
form.getName(),
EventDescription.of(form.getDescription()),
form.getMinimalInterestThreshold());
commandGateway.send(command);
}
CreateEventProposalForm 只是一个值类,用于从传入的 json 中收集所有参数。
EventProposalId
是另一个值对象,代表一个标识符。它可以在字符串或不带任何参数的情况下构造 - 在后一种情况下会生成 UUID。
现在,我想编写一个测试用例,给定一个适当的 json,我的控制器应该使用适当的命令对象在我的命令网关模拟上调用 send 方法。
这就是 mockito 表现得有点不可预测的时候:
@Test
public void givenPostRequestShouldSendAppropriateCommandViaCommandHandler() throws Exception {
final String jsonString = asJsonString(
new CreateEventProposalForm(eventProposalName, eventDescription, minimalInterestThreshold)
);
mockMvc.perform(
post(URL_PATH)
.contentType(MediaType.APPLICATION_JSON)
.content(jsonString)
);
verify(commandGatewayMock, times(1))
.send(
new CreateEventProposalCommand(
any(EventProposalId.class),
eventProposalName,
EventDescription.of(eventDescription),
minimalInterestThreshold
)
);
}
如果我将 EventProposalId 的新实例传递给 EventProposalCommand 构造函数,请说:
new CreateEventProposalCommand(
EventProposalId.of("anId"),
eventProposalName,
EventDescription.of(eventDescription),
minimalInterestThreshold
)
如你所料,它失败了。
但是考虑到any(EventProposalId.class),我可以传递完全虚拟的值,例如
new CreateEventProposalCommand(
any(EventProposalId.class),
"dummy name",
EventDescription.of("dummy description"),
666
)
作为其他参数,测试总是通过。
如何在不拦截方法参数的情况下做出这样的断言? 这是 mockito 的错误还是应该这样?
【问题讨论】:
标签: java testing mocking mockito spring-test