我越来越NPE而嘲讽的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不为空(也可等论调REPLICATION_DOMAIN,SOURCE_NODE_INDEX,NODE_CHANGE_NUMDER NOT NULL)在实体类,而em.createNamedQuery( “NodeChangeDelta.findIdByNaturalKey”,String.class)为空。