有一个界面:
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/