我正在和Mockito一起使用Junit。我想测试EntityManager,我得到java.lang.NullPointerException
以下是我的尝试, 主类方法是,
@Override
public ReplicationPerspective buildReplicationPerspective(final String replicationDomain)
throws ReplicationStateException {
try {
System.out.println("Test");
final ReplicationPerspective localPerspective =
this.replicationPerspectiveQuery.findReplicationPerspective(replicationDomain);
List<String> ncdKeys = new ArrayList<String>();
for (NodeChangeDelta ncd : this.nodeChangeDeltaQuery.findByChangeStatus(
replicationDomain, ChangeStatus.PENDING)) {
ncdKeys.add(ncd.getKey());
}
localPerspective.setPendingNodeChangeDeltaKeys(ncdKeys);
LOGGER.debug("Local perspective is {} ", localPerspective);
return localPerspective;
}
catch (Throwable t) {
LOGGER.error("Failed to build replication perspective", t);
throw new ReplicationStateException(t);
}
}
replicationPerspectiveQuery Bean文件方法是,
@PersistenceContext
private EntityManager em;
@Override
public ReplicationPerspective findReplicationPerspective(final String replicationDomain) {
Validate.notBlank(replicationDomain);
ReplicationPerspective perspective =
this.em.find(ReplicationPerspective.class, replicationDomain);
if (perspective == null) {
this.replicationPerspectiveInitializer
.initializeReplicationPerspective(replicationDomain);
perspective = this.em.find(ReplicationPerspective.class, replicationDomain);
}
return perspective;
}
我的测试用例方法是,
@Test
public void testBuildReplicationPerspective() throws ReplicationStateException {
this.replicationStateServiceBean =
new ReplicationStateServiceBean(null, null, null, null,
new ReplicationPerspectiveQueryBean(), null, null);
this.em = Mockito.mock(EntityManager.class);
Mockito.when(this.em.find(ReplicationPerspective.class, REPLICATION_DOMAIN))
.thenReturn(null);
this.replicationStateServiceBean.buildReplicationPerspective(REPLICATION_DOMAIN);
}
我在下面一行的replicationPerspectiveQuery Bean文件中遇到NPE错误
ReplicationPerspective perspective =
this.em.find(ReplicationPerspective.class, replicationDomain);
如何测试实体经理,帮我解决。
我也试过像下面那样嘲笑但是没有用,
Mockito.when(this.replicationPerspectiveQuery.findReplicationPerspective(REPLICATION_DOMAIN)).thenReturn(null);
答案 0 :(得分:0)
你缺乏让Mockito进行实际注射的指示。现在你已经模拟了EntityManager,但它没有在任何地方使用。
您可以将bean声明为测试类的成员,并使用@InjectMocks对其进行注释,让Mockito为您进行布线。
有关更多信息和示例,另请参阅the documentation。