java - jUnit change behavior of a method -


i have make junit tests methods , can't change source code. there possibility change behavior of function without change source code? straight-forward example: class , b source code (can't change them). want change behavior of run() method when call in b through testing() in junit test. ideas?

public class {     public string run(){         return "test";     }  }  public class b {     public void testing() {         string froma = new a().run(); //i want mocked result here         system.out.println(froma);     } }  public class c {     @test     public void junittest() {         new b().testing();         // , here want call testing method b "mock return" run()              } } 

you can use mockito , powermock:

import org.junit.before; import org.junit.test; import org.junit.runner.runwith; import org.powermock.api.mockito.powermockito; import org.powermock.core.classloader.annotations.preparefortest; import org.powermock.modules.junit4.powermockrunner;  import static org.mockito.mockito.spy; import static org.mockito.mockito.when;  @runwith(powermockrunner.class) @preparefortest(b.class) public class c {     @before     public void setup() throws exception {         a = spy(new a());         when(a.run()).thenreturn("mock return");         powermockito.whennew(a.class).withnoarguments().thenreturn(a);     }      @test     public void junittest() {         new b().testing();     } } 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -