2017年不容错过的10+个开源 Java库

LinkedList mockedList = mock(LinkedList.class);//stubbingwhen(mockedList.get(0)).thenReturn("first");when(mockedList.get(1)).thenThrow(new RuntimeException());//following prints "first"System.out.println(mockedList.get(0));//following throws runtime exceptionSystem.out.println(mockedList.get(1));//following prints "null" because get(999) was not stubbedSystem.out.println(mockedList.get(999));//Although it is possible to verify a stubbed invocation, usually it's just redundant//If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).//If your code doesn't care what get(0) returns, then it should not be stubbed. Not convinced? See here.verify(mockedList).get(0);

网站,GitHub,文档

Jukito

结合了 JUnit、Guice 和 Mockito 的力量,听起来很有技术含量。

  • 大大降低了自动 mock 的古板,使阅读测试变得容易

  • 在测试对象的 API 变化时更有弹性

  • 通过 @Inject 注解的字段可以自动注入

  • 更容易将对象绑在一起,因此可以将单元测试扩展到部分集成测试

@RunWith(JukitoRunner.class)public class EmailSystemTest @Inject EmailSystemImpl emailSystem;  Email dummyEmail;  @Before  public void setupMocks(      IncomingEmails incomingEmails,      EmailFactory factory) {    dummyEmail = factory.createDummy();    when(incomingEmails.count()).thenReturn(1);    when(incomingEmails.get(0)).thenReturn(dummyEmail);  }  @Test  public void shouldFetchEmailWhenStarting(      EmailView emailView) {    // WHEN    emailSystem.start();    // THEN    verify(emailView).addEmail(dummyEmail);  }}

GitHub,网站

边城 边城翻译于 1天前0人顶  翻译得不错哦! 

Awaitility

Awaitility 是一个小型的 DSL(领域专用语言),用于将异步操作同步化。

测试异步系统是件难事,不仅需要处理线程、超时和并发问题,测试代码的意图还可能被这些细节所掩盖。Awaitility 是一个 DSL,它能以一个简洁易读的方式表达异步系统要做的事情。

@Testpublic void updatesCustomerStatus() throws Exception {    // Publish an asynchronous event:    publishEvent(updateCustomerStatusEvent);    // Awaitility lets you wait until the asynchronous operation completes: