我正在尝试模拟具有void
返回类型的私有字段的方法。在我的测试中,我试图模拟aClass.doSomething()
投掷IllegalStateException
,我需要验证recover()
被调用。这是一个示例:
public class ClassToTest implements Runnable {
private ClassToMock aClass;
@Override
public void run() {
try{
aClass.doSomething("some parameter");
} catch(IllegalStateException e) {
logger.error("Something bad happened", e);
recover();
}
}
public void recover(){
logger.info("I am recovering");
}
}
我分别完成了每一部分:
- 模拟私人字段的方法调用
- 模拟具有
void
返回类型的方法 - 投掷异常
- 验证私人方法调用
,但我无法将所有内容放在一起。任何帮助都将受到赞赏
我以为我会详细说明GhostCat的评论:
与Mockito一起
Mockito不仅仅是一个模拟框架 - 这是一门学科。如果您仔细阅读Mockito的文档,并限制自己求助于PowerMock et al ,您将学习良好的OOP练习。
阅读如何使用构造函数进行依赖注入
primum non nocere - 首先重构您的代码:
public class ClassToTest implements Runnable {
private final ClassToMock aClass;
private final Logger logger;
//injection of collaborators through the constructor
public ClassToTest(ClassToMock aClass, Logger logger) {
this.aClass = aClass;
this.logger = logger;
}
@Override
public void run() {
try{
aClass.doSomething("some parameter");
} catch(IllegalStateException e) {
logger.error("Something bad happened", e);
recover();
}
}
public void recover() { //there is no need for this method to be public - see Effective Java item 13
logger.info("I am recovering");
}
}
现在,您的代码可以使用Mockito 测试,而无需求助于更复杂的模拟框架:
//mocks
@Mock ClassToMock classToMock;
@Mock Logger mockLogger;
//system under test
ClassToTest classToTest;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks();
classToTest = new ClassToTest(classToMock, mockLogger);
}
@Test
public void whenRun_thenDoesSomethingWithSomeParameter() {
//act
classToTest.run();
//assert
verify(classToMock).doSomething(eq("some parameter"));
}
@Test
public void givenAnIllegalStateForAClass_whenRun_thenLogsError() {
//arrange
IllegalStateException e = new IllegalStateException();
when(classToMock.doSomething(anyString()).thenThrow(e);
//act
classToTest.run();
//assert
verify(mockLogger).error(eq("Something bad happened"), same(e));
}
@Test
public void givenAnIllegalStateForAClass_whenRun_thenLogsRecovery() {
//arrange
when(classToMock.doSomething(anyString()).thenThrow(new IllegalStateException());
//act
classToTest.run();
//assert
verify(mockLogger).info(eq("I am recovering"));
}