0

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.

Mandroid
  • 6,200
  • 12
  • 64
  • 134
  • Is partial mock sth you are looking for? – Lesiak Apr 16 '19 at 05:58
  • I think so, but not sure. I think I am partially mocking A already. And need to do same for X. – Mandroid Apr 16 '19 at 05:59
  • https://stackoverflow.com/questions/14970516/use-mockito-to-mock-some-methods-but-not-others – Lesiak Apr 16 '19 at 05:59
  • Well, you've mocked the X.getVariable method. SO it only returns what you tell it to return. And you only told to return something when it's called with "var1", not with "var2. So it returns null.You should probably not mock X in the first place. A complete, minimal example would help. – JB Nizet Apr 16 '19 at 06:06

1 Answers1

1

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:

  1. If possible, just use real X, instead of a mock
  2. Alternatively, you can partial mock X as well
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

Lesiak
  • 22,088
  • 2
  • 41
  • 65