gpt4 book ai didi

java - 无法模拟 EntityManager jMockit

转载 作者:行者123 更新时间:2023-12-02 05:21:12 25 4
gpt4 key购买 nike

我在尝试使用 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(),但它仍然抛出相同的空指针。

最佳答案

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

关于java - 无法模拟 EntityManager jMockit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26508998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com