如何使用PowerMock在循环中模拟其他类的方法?

时间:2017-10-17 06:27:44

标签: java unit-testing mockito powermock

我有一种公共无效方法" a"这是待测试的,并且在" a"我有一个循环字符串作为迭代器,在这个循环中我调用了B&#39的公共void方法,字符串迭代器作为参数我想模拟,我想写一个单元测试来测试" a&#34 ;使用PowerMock,我该如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

你在方法“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());
    }
}
相关问题