2015-04-02 118 views
0

我正在使用Junit和Mockito。我想测试的EntityManager,我得到显示java.lang.NullPointerException使用JUnit的测试EntityManager Mockito

以下是我已经尽力了, 主类的方法是,

@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豆文件的方法是,

@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); 
    } 

我正在收到NPE errorPerspectiveQuery Bean文件在下面的行

ReplicationPerspective perspective = 
      this.em.find(ReplicationPerspective.class, replicationDomain); 

如何测试实体管理器,帮我解决。

我也试图嘲笑像下面,但没有工作,

Mockito.when(this.replicationPerspectiveQuery.findReplicationPerspective(REPLICATION_DOMAIN)).thenReturn(null); 

回答

0

而是缺乏说明有做的Mockito的实际注射。现在你的EntityManager被嘲笑了,但它并没有在任何地方使用。

您可以将bean声明为testclass的成员,并使用@InjectMocks为其注释以让Mockito为您执行布线。

另请参阅the documentation欲了解更多信息和示例。