gpt4 book ai didi

java - jUnit 改变方法的行为

转载 作者:行者123 更新时间:2023-11-30 08:09:55 25 4
gpt4 key购买 nike

我必须对某些方法进行一些 jUnit 测试,并且无法更改源代码。是否有可能在不更改源代码的情况下更改函数的行为?看一个简单的例子:A类和B类是源代码(不能更改它们)。当我通过 Junit 测试中的 test() 在 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()
}
}

最佳答案

您可以使用MockitoPowerMock :

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

关于java - jUnit 改变方法的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30527950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com