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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With