0

EntityManager のモックアップに問題があります。すべてがコンパイルされ、テストが実行されますが、モックされたメソッドは null を返します。

モックされた「find」メソッド内にブレークポイントを設定すると、アプリがそこで中断されることはありません。この方法で静的メソッドを使用してさまざまなクラスを正常にモックすることができましたが、これには問題があります。

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();
        }
    }
}
4

1 に答える 1

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());
    } 
}
于 2015-01-28T13:17:53.097 に答える