2015-04-02 103 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欲瞭解更多信息和示例。