我在模拟EntityManager时遇到问题。一切都编译完毕,测试运行但模拟方法返回null。
当我在嘲笑中设置断点时,找到'应用程序永远不会在那里暂停。 我设法用这种方式用静态方法成功地模拟了不同的类 - 但是这个我有问题。
我使用Jmockit 1.7和Java 1.8.0。 我试图模拟的类是:javax.persistence.EntityManager
如果还需要更多信息,请询问。我会非常感谢任何帮助。
这是我的代码:
@RunWith(JMockit.class)
public class ShapefileSerializerTest {
@Mocked
private EntityManager em;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
new MockDatabase();
}
@Test
public void testPrepareShapefile() {
String[][] data = new String[][] {{"1", "100"}, {"1", "101"}, {"1", "102"}, {"1", "103"}, {"2", "200"}, {"2", "201"}};
List<Map<String, String>> featuresData = Stream.of(data).map(row -> {
Map<String, String> map = new HashMap<>(2);
map.put("layerId", row[0]);
map.put("id", row[1]);
return map;
}).collect(Collectors.toList());
ShapefileSerializer shapefileSerializer = new ShapefileSerializer("shapefiles");
// if I do not set up the em here - then it will be null inside the tested class
Deencapsulation.setField(shapefileSerializer, em);
Response response = shapefileSerializer.prepareShapefile(featuresData);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
public static final class MockDatabase extends MockUp<EntityManager> {
@Mock
@SuppressWarnings("unchecked")
public <T> T find(Class<T> entityClass, Object primaryKey) {
return (T) new ProjectLayer();
}
}
}
答案 0 :(得分:0)
将JMockit升级到1.8或更高版本,并将测试类更改为以下内容:
@RunWith(JMockit.class)
public class ShapefileSerializerTest {
@Mocked EntityManager em;
@Test
public void testPrepareShapefile() {
String[][] data = ...
List<Map<String, String>> featuresData = ...
ShapefileSerializer shapefileSerializer = new ShapefileSerializer("shapefiles");
Deencapsulation.setField(shapefileSerializer, em);
new Expectations() {{
em.find((Class<?>) any, any); result = new ProjectLayer();
}};
Response response = shapefileSerializer.prepareShapefile(featuresData);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
}