我越來越NPE而嘲諷的EntityManager,下面是我的代碼,嘲諷的EntityManager
@Stateless
public class NodeChangeDeltaQueryBean implements NodeChangeDeltaQueryLocal {
@PersistenceContext
private EntityManager em;
@Override
public String findIdByNaturalKey(final String replicationDomain, final int sourceNodeIndex,
final int nodeChangeNumber) {
List<String> result =
NodeChangeDelta.findIdByNaturalKey(this.em, replicationDomain, sourceNodeIndex,
nodeChangeNumber).getResultList();
return result.isEmpty() ? null : result.get(0);
}
}
我的實體類
@Entity
public class NodeChangeDelta implements Serializable, Cloneable, GeneratedEntity, KeyedEntity<String> {
public static TypedQuery<String> findIdByNaturalKey(final EntityManager em, final String replicationDomain, final int sourceNodeIndex, final int nodeChangeNumber) {
return em.createNamedQuery("NodeChangeDelta.findIdByNaturalKey", String.class)
.setParameter("replicationDomain", replicationDomain)
.setParameter("sourceNodeIndex", sourceNodeIndex)
.setParameter("nodeChangeNumber", nodeChangeNumber);
}
}
我的測試類
@RunWith(MockitoJUnitRunner.class)
public class NodeChangeDeltaQueryBeanTest {
@InjectMocks
NodeChangeDeltaQueryBean nodeChangeDeltaQueryBean;
@Mock
EntityManager em;
@Test
public void testFindIdByNaturalKey() {
this.addNodeChangeDelta();
this.nodeChangeDeltaQueryBean.findIdByNaturalKey(this.REPLICATION_DOMAIN,
this.SOURCE_NODE_INDEX, this.NODE_CHANGE_NUMDER);
}
}
在調試EM不null(還有其他參數REPLICATION_DOMAIN, SOURCE_NODE_INDEX,NODE_CHANGE_NUMDER不爲空)在Entit y類,而em.createNamedQuery(「NodeChangeDelta.findIdByNaturalKey」,String.class)爲null。
難道你希望你的模擬執行的實際查詢?這是行不通的。它不知道你的數據源,持久化上下文,命名查詢等。 – 2015-04-06 10:34:05