我想在当前的应用程序中使用TDD并尝试创建一些测试。在这种情况下,我需要向支持人员发送消息,如果可以,则返回true
.但是当我开始测试时,我失败了,因为实际结果和预期结果并不相同。
当我调试这个测试时,我看到,那个 mockito 根据需要放置 Mocks,但sender.sendSupportMessage()
钢铁返回 false。谁能解释一下出了什么问题?
public class SupportTests {
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Mock
SupportContract.ISupportMessageSender sender;
@Mock
CurrentUserOperations currentUserOperations;
private SupportMessage stubSupportMessage;
private String message;
@Before
public void init(){
message = "message";
stubSupportMessage = new SupportMessage(1, message, null);
}
@Test
public void testSendMessageToSupportShouldBeDone (){
Support support = new Support(sender, currentUserOperations);
when(currentUserOperations.getCurrentUserSystemId())
.thenReturn(Long.valueOf(1));
when(sender.sendSupportMessage(stubSupportMessage))
.thenReturn(true);
boolean actualResult = support.sendMessageToSupport(message);
assertEquals("Sending message to support are failed.", true, actualResult);
}
}
public class Support implements SupportContract.ISupport {
private SupportContract.ISupportMessageSender sender;
private CurrentUserOperations currentUserOperations;
public Support(SupportContract.ISupportMessageSender sender, CurrentUserOperations currentUserOperations) {
this.sender = sender;
this.currentUserOperations = currentUserOperations;
}
@Override
public boolean sendMessageToSupport(String message) {
long userSystemId = currentUserOperations.getCurrentUserSystemId();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
SupportMessage supportMessage = new SupportMessage(userSystemId, message,
dateFormat.format(Calendar.getInstance().getTime()));
return sender.sendSupportMessage(supportMessage);
}
}
好的。我找到了解决方案。
如我们所见,在测试方法中我们使用stubSupportMessage
,它以@Before init
方法实例化。
另外,在Support
类中,我们看到SupportMessage supportMessage = new SupportMessage(...)
,并且这些支持消息不是相同的stubSupportMessage != supportMessage
。
因此,我们需要摆脱不同的对象。问题已通过以下代码解决:
when(sender.sendSupportMessage(any(SupportMessage.class))).thenReturn(true);
我们说any
可以使用SupportMessage
类的对象。
现在测试类:
public class SupportTests {
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Mock
SupportContract.ISupportMessageSender sender;
@Mock
CurrentUserOperations currentUserOperations;
private String message;
@Before
public void init(){
message = "message";
}
@Test
public void testSendMessageToSupportShouldBeDone (){
Support support = new Support(sender, currentUserOperations);
when(currentUserOperations.getCurrentUserSystemId()).thenReturn(Long.valueOf(1));
when(sender.sendSupportMessage(any(SupportMessage.class))).thenReturn(true);
boolean actualResult = support.sendMessageToSupport(message);
assertEquals("Sending message to support are failed.", true, actualResult);
}
}