【发布时间】:2019-09-05 19:31:26
【问题描述】:
我正在尝试模拟具有嵌套类的类。该嵌套类带有构造函数参数。 当我尝试使用模拟而不是模拟进行测试时,实际方法正在执行。
我在外部类上做了@InjectMocks,在内部类上做了@Mock。
//Actual Class to test using Mockito.
public class ClassA {
public void initMethod(String s1, String s2, String s3, String s4) throws Exception {
ClassB objB = null;
if (objB == null && s3 != null && s4 != null && s2 != null) {
SampleUtil.KeyStorePasswordPair pair = SampleUtil.getKeyStorePasswordPair(s3, s4);
objB = new ClassB(s1, s2, pair.keyStore, pair.keyPassword);
try {
objB.meth1(); //Note: meth1 and meth2 are void methods.
objB.meth2(); // These two methods only to be accessed. something like doNothing
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
我像往常一样尝试使用@Mock 调用该类,但实际方法 meth1() 正在被访问。
//Somthing which I tried
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
@InjectMocks
ClassA classA;
@Mock
ClassB classB;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testInitClient() throws Exception {
// Setup
// Run the test
classA.initMethod("Lorem", "Ipsum", "TestStr1", "TestStr2");
doNothing().when(classB).meth1(); // This is the line need to be mocked. But instead calling the actual method and executing
// Verify the results
}
需要模拟内部的 ClassB 方法,而不是访问真实的方法。
作为 mockito 的初学者,我想弄清楚这一点。但是对访问 void 方法等几点感到困惑,所以那时不能使用。使用参数等访问构造函数,
【问题讨论】:
标签: java junit mockito powermock