我想在参数化测试类中的类上使用@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();
....
}
}
是否可以在参数化类中创建模拟对象?
答案 0 :(得分:1)
尝试添加setUp方法:
@Before
public void setUp() {
initMocks(this);
}
答案 1 :(得分:0)
将在
后面查看正确的代码@RunWith(Parameterized.class)
public class ClassATest extends EasyMockSupport {
private String uniqueIdentifier;
private String value;
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"}});
}
@Before
public void setup() {
...
mockClassB = mock(ClassB.class);
...
}
@Test
public void testMethod() {
...
expect(mockClassB.someMethod(uniqueIdentifier)).andReturn(value); // mockClassB will be mocked :)
replayAll();
....
}
}
答案 2 :(得分:0)
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();
}
}