2016-08-19 106 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

相关问题