2016-08-19 64 views
0

我想驗證一個注入的依賴方法被調用兩次不同的參數類型。因此,假設我的類是:JMockit驗證注入方法調用兩次不同的參數

public class MyClass { 
    @PersistenceContext(name = "PU") 
    EntityManager entityManager; 

    public void doSomething() { 
     Customer customer = new Customer(); 
     Address customerAddress = new Address; 
     entityManager.persist(customer) 
     entityManager.persist(customerAddress); 
    } 
} 

@PersistenceContext是Java EE特定的註解來告訴應用服務器注入EntityManager特定peristence單元。

所以,我想測試一下,一旦傳遞一個Customer對象並且另一次傳遞一個Address對象,就會調用persist兩次。

創建下面的測試類將:

public class MyClassTests { 
    @Tested 
    MyClass myClass; 
    @Injectable 
    EntityManager entityManager; 

    @Test 
    public void TestPersistCustomerAndAddress() { 
     new Expectations() {{ 
      entityManager.persist(withAny(Customer.class)); 
      entityManager.persist(withAny(Address.class)); 
     }}; 

     myClass.doSomething(); 
    } 
} 

然而JMockit似乎忽略傳遞到鄭州一家類的類型。我基本上可以用AnyAny來更改withAny(Date.class),測試仍然會通過。

有沒有一種方法來驗證傳遞給持久化的特定對象類型?

+0

注意沒有'withAny(Class)'方法,但只有'withAny(T)'方法,其中'T'是一個泛型類型參數,它僅僅是避免了類型轉換的需要。我還建議設置您的Java IDE,以便您可以及時從代碼編輯器中查看API文檔。 –

回答

3

您是否嘗試過使用withInstanceOf(Customer.class)?我認爲這應該做你想做的。

+0

謝謝,這個工程。 – ChrisM

相關問題