如何使用PowerMock在循环中从其他类中模拟方法?
问题描述:
我有一个公共无效的方法“a”是要测试,并在“a”我有一个循环与字符串作为迭代器,在此循环中我调用B的公共无效方法与字符串迭代器作为参数,我想嘲笑,我想写一个单元测试来测试使用PowerMock的“a”,我该如何实现这个目标?如何使用PowerMock在循环中从其他类中模拟方法?
答
您是否有方法“a”中的任何静态方法引用,如果不是直接使用Mockito,PowerMock基本上用于存根静态方法,模拟私有变量,构造函数等..我希望你没有进行集成测试所以只是嘲笑类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());
}
}
你有方法“一”任何静态方法refernces,如果不能直接使用的Mockito,PowerMock是bascially用于存根静态方法,模拟私有变量,构造etc..and我希望你不这样做集成测试,所以只是模拟类B的方法,并使用Mockito.doverify方法来检查您的方法是否实际调用。 –