简体   繁体   English

如何使用Mockito在Junit测试用例中比较多个条件

[英]How to Compare Multiple Conditions in Junit Test Cases using Mockito

I want to give multiple conditions in the Junit Test cases using Mockito. 我想在使用Mockito的Junit测试案例中给出多个条件。 The Code for which i need Junit Test case using mockito is below.Help me out in this issue. 我需要使用模仿工具进行Junit测试用例的代码如下。在这个问题上帮助我。

      Customer customer;//Cutomer is a class;
      String temp;
      if(customer.isSetValid() &&
      StringUtil.hasvalue(temp=customer.isGetValid.getValue()))

How to use Multiple conditions in Mockito.Syntax is-When(conditions).thenReturn(true); 如何在Mockito中使用多个条件。语法是-When(conditions).thenReturn(true);

The when conditions are input parameters to a method, not if conditions, so you can pass two method parameters and those will be conditions for the mock. when条件是方法的输入参数,而不是if条件,因此您可以传递两个方法参数,这些将成为模拟的条件。

So when mocking a method, you can pass a mocked customer and a value for temp that you will pass to the method when testing it, that way the mock will return whatever you pass in the thenReturn function. 因此,在模拟一个方法时,您可以传递一个模拟的客户和一个temp值,该值将在测试时传递给该方法,这样,该模拟将返回您在thenReturn函数中传递的内容。

You can also use matchers like any 您也可以像任何其他方式使用匹配器

I am guessing that you want to use Customer as parameter to method done on mock based on your question, but you want to be sure that customer is in expected state. 我猜想您要根据Customer的问题将Customer用作模拟方法的参数,但是您要确保Customer处于预期状态。 You might try to clarify intent or use case, or write in pseudo language what you want to do. 您可能会尝试澄清意图或用例,或者用伪语言编写您想做什么。

If you have ie http client and it has saveCustomer(Customer customer) and Customer creation is outside of your control (class 1 save customer is creating customer and saving it over http), and you want to verify state of Customer object at time http client uses it you can do something like: 如果您拥有http客户端,并且它具有saveCustomer(Customer customer)并且客户创建超出了您的控制范围(类1,则save客户正在创建客户并将其保存在http上),并且您想在http客户端时验证Customer对象的状态使用它,您可以执行以下操作:

Client client = Mockito.mock(Client.class);
Class1 class1 = new Class1(client); //class that uses client and creates customer
ArgumentCaptor<Customer> customerCaptor = ArgumentCaptor.forClass(Customer.class);

class1.createCustomer(); //method that does create and save

verify(client).saveCustomer(customerCaptor.capture());
final Customer customer = Customer.getValue();

Assert.assertTrue(customer.isSetValid());
Assert.assertTrue(StringUtil.hasvalue(temp=customer.isGetValid.getValue()));
//do other asserts on customer

Please check mockito argument captor for further details but it is nice way of both verifying that method is called with expected class and capturing instance so you can do asserts on it. 请检查mockito参数捕获器以获取更多详细信息,但这是一种验证用预期类调用该方法并捕获实例的好方法,以便您可以对它进行断言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM