我有类 TestME,它有静态 main 方法。我需要避免调用 b.cool 方法。
public class TestME {
public static int testme(String ...strings){
System.out.println(strings.length);
B b = new B();
b.cool();
return strings.length;
}
}
我的B级在下面
public class B {
public void cool(){
System.out.println("I am cool");
}
}
上面 TestMe 类的我的 Junit 类如下
@RunWith(MockitoJUnitRunner.class)
public class JunitTest {
@Spy
B b;
@InjectMocks
TestME test;
@Before
public void setUp(){
test = new TestME();
MockitoAnnotations.initMocks(this);
}
@Test
public void testMe(){
doNothing().when(b).cool();
Assert.assertEquals(2, test.testme("xyz", "omg"));
}
}
最佳答案
您可以更改代码:
public class TestME {
public static int testme(String ...strings){
System.out.println(strings.length);
B b = new B();
b.cool();
return strings.length;
}
}
至以下内容:
public class TestME {
public static int testme(String ...strings){
System.out.println(strings.length);
B b = getInstanceOfB();
b.cool();
return strings.length;
}
static B getInstanceOfB(){
return new B();
}
}
然后在您的测试代码中,您可以监视类、 stub getInstanceOfB()
方法以返回模拟对象。拥有这个真正的 b.cool
永远不会在测试中被调用。
@RunWith(PowerMockRunner.class)
@PrepareForTest(TestME.class)
public class JunitTest {
@Before
public void setUp(){
B b = PowerMockito.mock(B.class);
PowerMockito.spy(TestME.class);
PowerMockito.when(TestME.getInstanceOfB()).thenReturn(b);
}
@Test
public void testMe(){
Assert.assertEquals(2, TestME.testme("xyz", "omg"));
}
}
您需要 PowerMockito 来完成此任务。
关于java - 如何使用 Mockito 和 Junit 模拟静态方法中存在的 void 方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52180541/