如何使用 PowerMock 在循环中模拟来自其他 class 的方法?
How to mock method from other class in a loop using PowerMock?
我有一个要测试的 public void 方法 "a",在 "a" 我有一个以字符串作为迭代器的循环,在这个循环中我调用了 B 的 public void 方法以字符串迭代器作为我想模拟的参数,我想编写一个单元测试来测试 "a" 使用 PowerMock,我怎样才能实现这个目标?
你在方法 "a" 中是否有任何静态方法引用,如果不直接使用 Mockito,PowerMock 基本上用于存根静态方法、模拟私有变量、构造函数等。我希望你没有进行集成测试,因此只需模拟 class B 的方法并使用 Mockito.verify 方法来检查您的方法是否实际被调用。请参阅下面我的回答。
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class ClassATest {
@InjectMocks
ClassA classsA;
@Mock
ClassB classB;
@Test
public void testClassAMethod() {
//Assuming ClassA has one method which takes String array,
String[] inputStrings = {"A", "B", "C"};
//when you call classAMethod, it intern calls getClassMethod(String input)
classA.classAMethod(inputStrings);
//times(0) tells you method getClassBmethod(anyString()) been called zero times, in my example inputStrings length is three,
//it will be called thrice
//Mockito.verify(classB, times(0)).getClassBMethod(anyString());
Mockito.verify(classB, times(3)).getClassBMethod(anyString());
}
}
我有一个要测试的 public void 方法 "a",在 "a" 我有一个以字符串作为迭代器的循环,在这个循环中我调用了 B 的 public void 方法以字符串迭代器作为我想模拟的参数,我想编写一个单元测试来测试 "a" 使用 PowerMock,我怎样才能实现这个目标?
你在方法 "a" 中是否有任何静态方法引用,如果不直接使用 Mockito,PowerMock 基本上用于存根静态方法、模拟私有变量、构造函数等。我希望你没有进行集成测试,因此只需模拟 class B 的方法并使用 Mockito.verify 方法来检查您的方法是否实际被调用。请参阅下面我的回答。
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class ClassATest {
@InjectMocks
ClassA classsA;
@Mock
ClassB classB;
@Test
public void testClassAMethod() {
//Assuming ClassA has one method which takes String array,
String[] inputStrings = {"A", "B", "C"};
//when you call classAMethod, it intern calls getClassMethod(String input)
classA.classAMethod(inputStrings);
//times(0) tells you method getClassBmethod(anyString()) been called zero times, in my example inputStrings length is three,
//it will be called thrice
//Mockito.verify(classB, times(0)).getClassBMethod(anyString());
Mockito.verify(classB, times(3)).getClassBMethod(anyString());
}
}