繁体   English   中英

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

[英]How to mock method from other class in a loop using PowerMock?

我有一个待测试的公共无效方法“ a”,在“ a”中,我有一个以字符串为迭代器的循环,在此循环中,我以字符串迭代器为参数调用了B的公共无效方法,我想模​​拟它,我想编写一个使用PowerMock来测试“ a”的单元测试,如何实现这个目标?

您在方法“ 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());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM