Reputation: 7468
I am facing an issue while mocking things for junit test.
Scenario is as:
Class A implements an interface from a third party jar, and needs to implement method1. In addition to method1, A also contains method2, which is called from method1. method2 itself calls some external service.
I want to unit test method1.
method1 takes input, say X. X has an input variable wrapped inside it, say var1. var1 is used by logic in method1, and method1 sets another variable,say var2, in X.
So I first mock class A, so as to mock method2.
A a= Mockito.spy(new A());
doReturn("some dummy value").when(a).method2();
Then I also have to mock X for setting var1.
X x= mock(X.class);
when(x.getVariable("var1")).thenReturn("some dummy value for var1");
Finally:
a.method1(x);
Inside, method1 I do:
x.setVariable("var2","some value for var2").
Now in unit test, when I try to fetch var2 from x, I get null.
x.getVariable("var2");
I expect "some value for var2" but instead I get null.
Upvotes: 0
Views: 60
Reputation: 25936
You are correctly partial mocking class A, but using a mock for class X.
You have no expectations set on x.getVariable("var2")
, and therefore it always returns null.
Calling x.setVariable("var2","some value for var2").
on the mock has no impact on this call
What I suggest:
X x = mock(X.class);
when(x.getVariable("var2")).thenCallRealMethod();
doCallRealMethod().when(x).setVariable(anyString(), anyString());
when(x.getVariable("var1")).thenReturn("some dummy value for var1");
Addtionally, if method under test method1
does not call method2
in its body, use a real instance of A
instead of a partial mock
Upvotes: 1