Gowtham Murugesan
Gowtham Murugesan

Reputation: 417

How to Compare Multiple Conditions in Junit Test Cases using Mockito

I want to give multiple conditions in the Junit Test cases using Mockito. The Code for which i need Junit Test case using mockito is below.Help me out in this issue.

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

Upvotes: 0

Views: 3293

Answers (2)

Nenad Bozic
Nenad Bozic

Reputation: 3784

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. You might try to clarify intent or use case, or write in pseudo language what you want to do.

If you have i.e. 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:

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.

Upvotes: 0

tinker
tinker

Reputation: 1406

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.

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.

You can also use matchers like any

Upvotes: 1

Related Questions