[英]jUnit change behavior of a method
我必须对某些方法进行一些jUnit测试,并且无法更改源代码。 是否有可能在不更改源代码的情况下更改功能的行为? 看一个简单的例子:类A和B是源代码(不能更改它们)。 当我通过Junit测试中的testing()在B中调用run()方法时,我想从A更改run()方法的行为。 有任何想法吗?
public class A {
public String run(){
return "test";
}
}
public class B {
public void testing() {
String fromA = new A().run(); //I want a mocked result here
System.out.println(fromA);
}
}
public class C {
@Test
public void jUnitTest() {
new B().testing();
// And here i want to call testing method from B but with a "mock return" from run()
}
}
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 a = spy(new A());
when(a.run()).thenReturn("mock return");
PowerMockito.whenNew(A.class).withNoArguments().thenReturn(a);
}
@Test
public void jUnitTest() {
new B().testing();
}
}
您无法测试所需的方式,也无法更改源代码。 您不能模拟局部变量。 你添加新的方法,我会建议B.class
将返回new A()
和spy
使用它的Mockito 。
@Test
public void test(){
final B spy = Mockito.spy(new B());
Mockito.doReturn(new C()).when(spy).getA();
}
class C extends A {
@Override
public String run(){return "new String";}
}
在测试中使用字节码库不是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.