简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM