首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用jmockit的Mockups API模拟EntityManager?

如何使用jmockit的Mockups API模拟EntityManager?
EN

Stack Overflow用户
提问于 2015-01-28 16:38:36
回答 1查看 1.4K关注 0票数 0

我在模拟EntityManager时遇到了问题。一切编译完成后,测试运行,但模拟的方法返回null。

当我在模拟的'find‘方法中设置断点时,应用程序永远不会在那里挂起。我设法用这种方式成功地用静态方法模拟了不同的类--但用这种方法我遇到了问题。

我使用Jmockit 1.7和Java 1.8.0。我试图模拟的类是: javax.persistence.EntityManager

如果需要更多信息,请联系我们。如果有任何帮助,我将非常感激。

下面是我的代码:

代码语言:javascript
复制
@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();
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2015-01-28 21:17:53

将JMockit升级到1.8版或更高版本,并将测试类更改为以下内容:

代码语言:javascript
复制
@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());
    } 
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28187815

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档