简体   繁体   中英

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

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

Do you have any static methods refernces in method "a", if not use Mockito directly, PowerMock is bascially used to stub static methods, mock private variables, constructors etc..and I hope you aren't doing integration testing so just mock class B's method and use Mockito.verify method to check whether your method is actually called or not. See my answer below.

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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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