Note that there are some explanatory texts on larger screens.

plurals
  1. POUnit-testing with mockito (partial mocking)
    text
    copied!<p>I have a problem with Mockito.</p> <p>Is it possible to do such a thing:</p> <pre><code>ClassX x = mock(ClassX.class) when(x.methodB()).thenReturn("toto"); String result = x.methodA(); </code></pre> <p>I'm working with Mockito 1.7.</p> <p>I saw there was a "spy" system but they say it's not recommended to use it (why?) on the item we test...</p> <p>I tried that spy function anyway but i get a strange behaviour.</p> <p>Check what i want to do:</p> <p>Real code:</p> <pre><code>String methodA(String arg) { return this.methodB(arg); } String methodB(String arg) { return "toto"; } </code></pre> <p>Test code:</p> <pre><code>@Test public void testTest() { final ClassX x = spy( new ClassX() ); final String argument = "arg"; doReturn("good").when(helper).methodB(argument); assertTrue( x.methodB(argument).equals("good") ); assertTrue( x.methodA(argument).equals("good") ); } </code></pre> <p>As they said i avoided the when thenReturn syntax that could be a problem with a spy (but it doesn't work either anyway)</p> <p>The strange thing is that: assertTrue( x.methodB(argument).equals("good") ); is OK</p> <p>Only the second assertTrue( x.methodA(argument).equals("good") ); is not OK</p> <p>Actually helper.methodA(argument) returns "toto" -> the real result and not the mock result</p> <p>It isn't possible to tell mockito to return "good" in this case??? It seems when the test class call methodB it's ok, but if a method of the spy calls the methodB it doesn't work anymore...</p> <p>I don't know what to do... is it such a strange thing to unit-test 2 methods of the same class and make the tests independent from each others so that a famous mock-test framework doesn't implement this basic function? Isn't it what we just call real unit-testing? Don't understand why they say to avoid using spy method on the tested object...</p> <p>Thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload