Mock method in junit test

10,034

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.

Share:
10,034
Radu Gabriel
Author by

Radu Gabriel

Updated on July 12, 2022

Comments

  • Radu Gabriel
    Radu Gabriel almost 2 years

    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()         
        }
    }