我有一个定义为
的方法@Startup
@Singleton
public class PRCConnectionRunner {
@Inject
private ServiceStatus status;
private Timer connectorTimer = null;
public void destroy() {
connectorTimer.cancel();
status.stopped();
}
}
我想测试它调用停止和取消的destroy的行为。我可以通过注入一个状态如下的模拟对象来轻松测试停止
@Mock
ServiceStatus status;
@InjectMocks
PRCConnectionRunner prcConnection;
@Test
public void destroyShouldCallStatusStop() {
prcConnection.destroy();
Mockito.verify(status).stopped();
}
然而,由于我无法注入connectorTimer,因为它是在PRCConnectionRunner类中构造的,我怎样才能测试destroy调用在connectorTimer上的cancel()?
答案 0 :(得分:1)
您可以使用PowerMockito。它的MemberModifier允许设置私人成员,你可以"注入"计时器模拟并验证它。要使用PowerMockito,您应该通过@RunWith(PowerMockRunner.class)注释测试类。它应该是这样的:
@RunWith(PowerMockRunner.class)
public class TestConnectionRunner
@Mock
ServiceStatus status;
@InjectMocks
PRCConnectionRunner prcConnection;
@Mock
Timer timerMock;
@Test
public void destroyShouldCallStatusStop() {
MemberModifier.field(PRCConnectionRunner.class, "connectorTimer").set(prcConnection, timerMock);
prcConnection.destroy();
Mockito.verify(status).stopped();
Mockito.verify(timerMock).cancel();
}
}
您可以在此link
中找到更多Mockito / PowerMock示例