测试中的类是TestedClass,它包含一个名为" inner"的字段。来自类型InnerClass。
Class TestedClass{
InnerClass inner;
public void methodToTest() {
inner.getSomething().AddSomething(new Something());
}
}
在我的测试中,我为"内部"创建了一个模拟器。并且无法弄清楚如何测试methodToTest,我试过的所有选项要么不编译,要么从Mockito获得例外。模拟和测试这种情况的正确方法是什么?
感谢。
答案 0 :(得分:2)
您应该在InnerClass
初始化期间注入TestedClass
模拟。例如,你应该有一个构造函数:
class Something {
void addSomething(Something sth) {
}
}
class InnerClass {
Something getSomething() {
return new Something();
}
}
class TestClass {
private final InnerClass inner;
TestClass(InnerClass inner) {
this.inner = inner;
}
public void methodToTest() {
inner.getSomething().addSomething(new Something());
}
}
验证通话的测试将是:
@Test
public void shouldInvokeInnerClassMethod() {
InnerClass innerMock = Mockito.mock(InnerClass.class);
TestClass testSubject = new TestClass(innerMock);
testSubject.methodToTest();
verify(innerMock).getSomething();
}
如果您想测试传递给addSometing
方法的值:
@Test
public void shouldAddSomething() {
ArgumentCaptor<Something> somethingCaptor = ArgumentCaptor.forClass(Something.class);
Something somethingMock = Mockito.mock(Something.class);
InnerClass innerMock = Mockito.mock(InnerClass.class);
when(innerMock.getSomething()).thenReturn(somethingMock);
TestClass testSubject = new TestClass(innerMock);
testSubject.methodToTest();
verify(somethingMock).addSomething(somethingCaptor.capture());
Something addedSomething = somethingCaptor.getValue();
//assertions on addedSomething content
}