I have a class under test which contains a method which has an inner anonymous class. One of the methods in the anonymous class calls a method from the class under test, but Mockito doesn't seem to realize this.
public class ClassUnderTest {
Dependency dependency;
public ClassUnderTest(Dependency d) {
dependency = d;
}
public void method() {
dependency.returnsObservable().observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io()).subscribe(new Observer<SupportClass> {
/* Other methods omitted */
public void onComplete() {
outerMethod();
})
}
public void outerMethod() {
blah;
}
}
My test code:
public class TestClass {
ClassUnderTest underTest;
Dependency dependency;
@Before
public void setUp() throws Exception {
dependency = Mockito.mock(Dependency.class);
underTest = Mockito.spy(new ClassUnderTest(dependency));
}
@Test
public void method() throws
Mockito.when(dependency.returnObservable()).thenReturn(Observable.just(new SupportClass());
Mockito.doNothing().when(underTest).outerMethod();
underTest.method();
Mockito.verify(underTest).outerMethod();
}
}
For some reason that I can't seem to figure out, Mockito can't detect that outerMethod() is being called, even though I have manually verified by stepping through line by line in the debugger. I have also verified that the call to the dependency object returns the proper observable with the correct content, and the onComplete() and outerMethod() methods do get called. I'm just confused why Mockito doesn't detect it as such.
This is the error that it spits out:
Wanted but not invoked:
classUnderTest.outerMethod();
-> at (file and line number)
However, there was exactly 1 interaction with this mock:
classUnderTest.method();
-> at (file and line number)
Is there anything obvious I'm missing?
Dependency
class. I'm not seeing whereinnerMethod
is being called. Would be best to post a MCVE – Doyledoyleydependency.returnsObservable().subscribe(...)
. That would cause NPE in your test because dependency.returnsObservable() would return null. Make your example work. – BackstageObservable
sonComplete
method is called. – AmericanaObservable
s work yet, butonComplete()
does get called at some point (I think there's a lot of behind the scenes stuff going on with theObservable
object that causes it to get called, it's almost like anonClick()
method, it's triggered by something and not necessarily called explicitly). – Coates