public void send(Message msg) {
 messages.add(msg);
 }public int numberSent() {
 return messages.size();
 }
 }

实现Stub的状态验证,

class OrderStateTester…

public void testOrderSendsMailIfUnfilled() {
 Order order = new Order(TALISKER, 51);
 MailServiceStub mailer = new MailServiceStub();
 order.setMailer(mailer);
 order.fill(warehouse);
 assertEquals(1, mailer.numberSent());
 }

只做了简单的测试,断言发出了1封邮件。没有测试是否发送给了对的收件人,或者邮件正文是否正确。不过不影响跟Mock比较。

如果用Mock,会怎么写呢?

class OrderInteractionTester…

public void testOrderSendsMailIfUnfilled() {
 Order order = new Order(TALISKER, 51);
 Mock warehouse = mock(Warehouse.class);
 Mock mailer = mock(MailService.class);
 order.setMailer((MailService) mailer.proxy());mailer.expects(once()).method(“send”);
 warehouse.expects(once()).method(“hasInventory”)
 .withAnyArguments()
 .will(returnValue(false));order.fill((Warehouse) warehouse.proxy());
 }

结合一张图,就一下全明白了,

java Mock单元测试统计接口 java单元测试mock框架_IT

怎么喝Mockito?

添加Maven dependency,

org.mockito mockito-core 3.3.3 test

现在可以开始Mock了,先Mock一个List Interface试试,(示例只是玩语法,实际应使用instance)

//Let’s import Mockito statically so that the code looks clearer
 import static org.mockito.Mockito.*;// mock creation
 List mockedList = mock(List.class);// using mock object
 mockedList.add(“one”);
 mockedList.clear();// verification
 verify(mockedList).add(“one”);
 verify(mockedList).clear();

接着用Mockito来做Stub:

// You can mock concrete classes, not just interfaces
 LinkedList mockedList = mock(LinkedList.class);

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。