Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock method in junit test

I have to make some jUnit tests (with mocks) for some methods and I can't change the source code. Is there any possibility to change the behavior of a function (with mocks maybe) without change source code?

Look a straight-forward example: Class A and B are source code (can't change them). I want to change behavior of run() method from A when I call it in B. Any ideas?

public class A {
    public String run(){
        return "test";
    }
}

public class B extends A {
    public void testing() {
        String fromA = run(); //I want a mocked result here
        System.out.println(fromA);
    }
}

public class C {
    B mockB = null;

    @Test
    public void jUnitTest() {
        mockB = Mockito.mock(B.class);

        // And here i want to call testing method from B but with a "mock return" from run()         
    }
}
like image 930
Radu Gabriel Avatar asked May 02 '26 19:05

Radu Gabriel


1 Answers

You can create partial mocks with mockito's spy() method. So your test class would look something like

public class C {

   @Test
   public void jUnitTest(){
       B mockB = spy(new MockB());

       when( mockB.run() ).thenReturn("foo");

       mockB.testing();
   }
}

This assumes the methods you want to mock aren't declared as final.

like image 192
Don Bottstein Avatar answered May 05 '26 09:05

Don Bottstein