正在测试的类是测试classedclass,该级具有一个名为" Inner"的字段,来自类型InnerClass。
Class TestedClass{
InnerClass inner;
public void methodToTest() {
inner.getSomething().AddSomething(new Something());
}
}
在我的测试中,我为"内部"创建了一个模拟,无法弄清楚如何测试方法托端,我尝试过的所有选项都不编译并从Mockito那里获得例外。嘲笑和测试这种情况的正确方法是什么?
谢谢。
您应该在TestedClass
初始化期间注入InnerClass
模拟。例如,您应该有一个构造函数:
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
}