Unit testing with mockito (partial mockery)

I have a problem with Mockito.

Is it possible to do such a thing:

ClassX x = mock(ClassX.class)
when(x.methodB()).thenReturn("toto");
String result = x.methodA();

I am working with Mockito 1.7.

I saw that there was a "spyware" system, but they say that it is not recommended to use it (why?) On the element being tested ...

I tried this spy feature anyway, but I get weird behavior.

Check what I want to do:

Real code:

String methodA(String arg) {
    return this.methodB(arg);
}

String methodB(String arg) {
    return "toto";
}

Test 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") );
}  

As they said, I avoided whenReturn syntax, which may be a spy problem (but it doesn’t work either way)

What is strange is that: assertTrue (x.methodB (argument) .equals ("good")); OK

Only the second assertTrue (x.methodA (argument) .equals ("good")); does not work

helper.methodA() "toto" → , mock

mockito, "" ??? , B, , B, ...

, ... , ? , ? , , ...

+3
2

- spied. . , spied B A, , .

+2

UPDATE: , .thenCallRealMethod(), . Mockito ; . .

ORIGINAL: Mockito, , EasyMock. , Mockito. - B . - EasyMock:

import org.junit.Test;
import static org.junit.Assert.*;
import static org.easymock.EasyMock.*;

public class PartialMockTest {

    class ClassX {
        String methodA(String arg) {return methodB(arg);}
        String methodB(String arg) {return "toto";}
    }

    @Test
    public void MockitoOnClassX(){
        ClassX classx = mock(ClassX.class);
        when(classx.methodB("hiyas")).thenReturn("tomtom");
        when(classx.methodA(anyString())).thenCallRealMethod();
        String response = classx.methodA("hiyas");
        assertEquals("tomtom",response);
    }


    @Test
    public void OverrideOnClassX() {
        ClassX classx = new ClassX(){@Override String methodB(String arg){return "tomtom";}};
        String response = classx.methodA("hiyas");
        assertEquals("tomtom",response);
    }

    @Test
    public void PartialMockOnClassX() throws NoSuchMethodException {
        ClassX classx = createMockBuilder(ClassX.class).addMockedMethod("methodB").createMock();
        expect(classx.methodA("hiyas")).andReturn("tomtom");
        replay(classx);
        String response = classx.methodA("hiyas");
        assertEquals("tomtom",response);
    }

}
+4

Source: https://habr.com/ru/post/1776229/


All Articles