无法模拟EntityManager jMockit

时间:2014-10-22 13:47:17

标签: java unit-testing jpa junit jmockit

我在尝试使用jMockit模拟测试EntityManager时遇到了一些麻烦。

我有这个基类:

public abstract class BaseEntityManager {

    @PersistenceContext private EntityManager entityManager;

    protected EntityManager getEntityManager(){
         return entityManager;
    }
}

一个扩展它的类:

@Stateless
public class PlayerManager extends BaseEntityManager{

    public Collection<PlayerDTO> getPlayersByDraftClass(int draftClass){
        EntityManager em = getEntityManager();
        Query query = em.createNamedQuery("Player.findByDraftClass", Player.class);
        query.setParameter("draftClass", draftClass);
        List<Player> players =  query.getResultList();
        return convertPlayersToPlayerDTOs(players);
    }
    ...some other methods
}

在我的测试中,我有:

public class PlayerManagerTest {

    @Injectable EntityManager em;
    @Tested PlayerManager pm;

    @Test
    public void testGetPlayersByDraftClass_PlayersReturned() throws FYPException{

        final List<Player> players = new ArrayList();
        players.add(createBasicPlayer(PLAYER_1_ID, PLAYER_1_NAME, PLAYER_1_POSITION));
        players.add(createBasicPlayer(PLAYER_2_ID, PLAYER_2_NAME, PLAYER_2_POSITION));

        new NonStrictExpectations(){
            @Mocked TypedQuery playerQuery;
            {   
                em.createNamedQuery(anyString, Player.class);
                result = playerQuery;

                playerQuery.getResultList();
                result = players;
            }
        };

        final ArrayList<PlayerDTO> result = (ArrayList<PlayerDTO>)pm.getPlayersByDraftClass(TEST_YEAR);

        new Verifications(){{
            assertNotNull("The list of players should not be null", result);
            assertFalse("The list should not be empty", result.isEmpty());
            assertEquals("The number of dtos returned should match the query result", players.size(), result.size());
            assertDTOsMatchEntities(players, result);
        }};

    }
    ...some other tests and helper methods
}

我在行playerQuery.getResultList()上得到一个空指针异常,所以我假设playerQuery永远不会被初始化,因为它没有注册em.createNamedQuery(anyString, Player.class)被调用。

我甚至尝试将EntityManager移动到PlayerManager类中,因此无需调用getEntityManager(),但它仍会抛出相同的空指针。

1 个答案:

答案 0 :(得分:2)

@Mocked TypedQuery playerQuery本地字段移动到测试方法,作为模拟参数。