现在测试我的模拟服务方法调用参数我使用以下技术,有没有更好或最新的方法来做到这一点?
@Test
public void testSendOutBidNotificationWhenCurrentBidderIsNotNullAndDifferentThenUserWithBidDifferenceNonZero(){
Event event = new Event();
event.setCurrency(Currency.USD);
Item item = new Item();
item.setCode("TST");
User user = new User("current@current.com", 8888888888L);
User currentHighBidder = new User("high@high.com", 9999999999L);
item.setCurrentHighBidder(currentHighBidder);
doReturn(10).when(itemService).getBidIncrement(any(), any());
ArgumentCaptor<TextMessage> textMessageCaptor = ArgumentCaptor.forClass(TextMessage.class);
textMessagePrepareService.sendOutBidNotification(event, item, user, 20, currentHighBidder);
verify(textMessageService).sendText(textMessageCaptor.capture());
assertEquals("You have been outbid for item TST. The new bid is $20, so you need to bid $10 more than that to win the item. For example: TST$30",
textMessageCaptor.getValue().getMessage());
}
这里我正在捕获TextMessage,它将在sendText方法中用作参数并测试将在之前构建的值。
测试方法如下
public void sendOutBidNotification(Event event, Item item, User user, int bidAmount, User currentHighBidder){
if (currentHighBidder != null && !currentHighBidder.equals(user)) {
log.info("Outbid person different: " + currentHighBidder);
try {
int bidIncrement = itemService.getBidIncrement(item, eventService.getAuction(event));
Map<String, String> params = new HashMap<String, String>();
params.put("increment", String.valueOf(bidIncrement));
params.put("required", String.valueOf(bidAmount + bidIncrement));
params.put("amount", String.valueOf(bidAmount));
params.put("item_code", item.getCode());
params.put("currency_symbol", event.getCurrency().getSymbol());
String loserMessage = this.getLooserOutBidNotificationMessage(bidIncrement, params);
TextMessage textMessage = new TextMessage(loserMessage, event.getAePhoneNumber(), currentHighBidder, loserMessage);
textMessageService.sendText(textMessage);
} catch (Exception e) {
log.error("Exception Occurred : " + e);
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
有一种更好的方法:不要使用new
来创建TextMessage。相反,有一个工厂为您创建消息;并使用依赖注入将该工厂放入您正在测试的类中。
因为那时你获得控制而不是在调用该方法时使用的TextMessage对象!含义:您可以模拟该工厂,并让它返回“已知”TextMessage对象。现在,您只需要验证是否使用那个对象调用了您的服务。这允许你只做一个简单的参数匹配;你可以完全摆脱那个ArgumentCaptor和断言!
这将是非常好的; as:对消息的 text 执行assertEquals()是不好的做法。这些消息一直在变化;当人们发现改变包含消息文本的某些资源包的内容会破坏单元测试时,人们会很快烦恼。