Reputation: 121
The class under test is TestedClass which holds a field called "inner" from type InnerClass.
Class TestedClass{
InnerClass inner;
public void methodToTest() {
inner.getSomething().AddSomething(new Something());
}
}
In my test i create a mock for "inner" and could not figure out how to test methodToTest, all option i've tried either do not compile and gets an exception from Mockito. What would be the proper way of mocking and testing this scenario?
Thanks.
Upvotes: 0
Views: 327
Reputation: 887
You should inject InnerClass
mock during TestedClass
initialization. For example you should have a constructor:
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());
}
}
And the test verifying the call would be:
@Test
public void shouldInvokeInnerClassMethod() {
InnerClass innerMock = Mockito.mock(InnerClass.class);
TestClass testSubject = new TestClass(innerMock);
testSubject.methodToTest();
verify(innerMock).getSomething();
}
If you would like to test the value passed to addSometing
method:
@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
}
Upvotes: 2