java - 仅验证少数元素的单元测试

标签 java unit-testing junit mockito

有一个界面:

interface IEventListener
{
  void onEvent(List <IEvent> events);
}

有一个事件类:

class EventB
{
  private final int id;
  private final A a;
  private final String somethingElse;
...
// constructors, getters
...
}

还有一个类要测试:

class Doer
{
 IEventListener eventListener;
 void doSomething(Aaa a)
 {
   eventListener.onEvent(Arrays.asList(new EventA(1), new EventC(2)));
...
   eventListener.onEvent(Arrays.asList(new EventB(42, a.getA(), "foo"), new EventA(3), new EventB(0, a.getA(), "bar")));
...
   eventListener.onEvent(Arrays.asList(new EventC(4)));
 }
}

Doer是我需要测试的代码,方法 doSomething产生事件包,我需要测试它是否在某些特定条件下产生特定事件。

更准确地说,我想要一个调用方法 doSomething 的单元测试并检查 EventB 是否以“42”和 A 发送从方法参数 a 开始。所有其他事件都应被忽略。

为了进行这样的测试,我只提出了涉及相当冗长的代码的解决方案,其中包含 ArgumentCaptor、for block 和魔术 boolean 标志......

对其进行单元测试的最佳方法是什么?也许代码设计不好?

最佳答案

设计是正确的,这是使用 Mockito 测试它的方法:

import org.hamcrest.Matchers;
import org.mockito.Mockito;
public void firesEventsOnDoSomething() {
  Listener listener = Mockito.mock(Listener.class);
  Doer doer = new Doer(listener);
  doer.doSomething(aaa);
  Mockito.verify(listener).onEvent(
    Mockito.argThat(
      Matchers.hasItem(
        Matchers.allOf(
          Matchers.instanceOf(EventB.class),
          Matchers.hasProperty("a", Matchers.equalTo(aaa.getA())),
          // whatever you want
        )
      )
    )
  );
}

这是 Mockito 1.9.0 和 Hamcrest-library 1.2.1。

要将 JUnit 4.10 与 Hamcrest-library 1.2.1 一起使用,您应该使用 junit:junit-dep:4.10 工件,并排除 org.hamcrest:hamcrest-core来自它:

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit-dep</artifactId>
  <version>4.10</version>
  <scope>test</scope>
  <exclusions>
    <exclusion>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-core</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-core</artifactId>
  <version>1.2.1</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-library</artifactId>
  <version>1.2.1</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-core</artifactId>
  <version>1.9.0</version>
  <scope>test</scope>
  <exclusions>
    <exclusion>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-core</artifactId>
    </exclusion>
  </exclusions>
</dependency>

关于java - 仅验证少数元素的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10586374/

相关文章:

java - 本地主机上的 Apache Tomcat websockets 实现

java - 用整数对二维字符串数组进行排序

java - Spring Boot - Mongodb - 基于另一个字段自动递增字段

unit-testing - 如何在 ink 中设置来电者!契约(Contract)单元测试功能?

结果相等时 Python 单元测试失败

java - 在 Eclipse 中显示命名查询建议/警告

Android - ActivityUnitTestCase 测试类中 startActivity 方法上的 AssertionFailedError

java - 如果测试运行正常,为什么我会收到反射异常 NoSuchMethodException

java - 可以使用多少并发线程来对 Web 应用程序进行负载测试?

java - Singleton HSQLDB数据库通过测试