我想在参数化测试类中的类上使用@Mock。但由于某些原因,mockClassB 为 NULL。我的代码类似于
@RunWith(Parameterized.class)
public class ClassATest extends EasyMockSupport {
private String uniqueIdentifier;
private String value;
@Mock
private ClassB mockClassB;
public ClassATest(String uniqueIdentified, String value) {
this.uniqueIdentifier = uniqueIdentified;
this.value = value;
}
...
@Parameterized.Parameters(name = "{index}: id = {0}; value = {1}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{"1", "val1"},
{"2", "val2"}});
}
@Test
public void testMethod() {
...
expect(mockClassB.someMethod(uniqueIdentifier)).andReturn(value); // mockClassB is NULL
replayAll();
....
}
}
是否可以在参数化类中创建模拟对象?
最佳答案
EasyMock 需要一个规则或一个运行器来实例化带注释的模拟。由于您已经在使用运行者,因此您唯一的选择就是规则。以下内容将起作用。
@RunWith(Parameterized.class)
public class ClassATest extends EasyMockSupport {
@Rule
public EasyMockRule rule = new EasyMockRule(this);
private String uniqueIdentifier;
private String value;
@Mock
private ClassB mockClassB;
public ClassATest(String uniqueIdentified, String value) {
this.uniqueIdentifier = uniqueIdentified;
this.value = value;
}
@Parameterized.Parameters(name = "{index}: id = {0}; value = {1}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{"1", "val1"},
{"2", "val2"}});
}
@Test
public void testMethod() {
expect(mockClassB.someMethod(uniqueIdentifier)).andReturn(value); // mockClassB is NULL
replayAll();
}
}
另一种方法是直接调用 injectMocks
,它可在 EasyMockSupport
上使用。
@RunWith(Parameterized.class)
public class ClassATest extends EasyMockSupport {
private String uniqueIdentifier;
private String value;
@Mock
private ClassB mockClassB;
public ClassATest(String uniqueIdentified, String value) {
this.uniqueIdentifier = uniqueIdentified;
this.value = value;
}
@Before
public void before() {
injectMocks(this);
}
@Parameterized.Parameters(name = "{index}: id = {0}; value = {1}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{"1", "val1"},
{"2", "val2"}});
}
@Test
public void testMethod() {
expect(mockClassB.someMethod(uniqueIdentifier)).andReturn(value); // mockClassB is NULL
replayAll();
}
}
关于java - EasyMock 和参数化测试(JUnit 参数化),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50354705/