I am having a service whose method looks somewhat like this -
class ServiceClass {
@Inject
EventService event;
public void handleUser(User user) throws ServiceClassException {
Customer customer = userToCustomer(user);
CustomerDetail detail = userToCustomerDetail(user);
try {
Response response1 = event.generateEvent(customer);
} catch(Exception e) {
throw new ServiceClassException();
}
try {
Response response2 = event.generateEvent(detail);
} catch(Exception e) {
throw new ServiceClassException();
}
}
private Customer userToCustomer(User user) {
// Some logic
}
private CustomerDetail userToCustomerDetail(User user) {
// Some logic
}
}
Now while writing the test, I wanna check the exception handling. This is how my test case looks like.
class ServiceClassTest {
@InjectMocks
ServiceClass service;
@Mock
EventService event;
@Before
public void setUp() {
User user = new User();
user.setValue("fsfw");
}
@Test
public void handleUserThrowsException() throws Exception {
Mockito.when(event.generateEvent(Mockito.any(Customer.class))).thenThrow(new RuntimeException());
try {
Response response1 = service.handleUser(user);
} catch(ServiceClassException e) {}
Mockito.verify(event, Mockito.never()).generateEvent(Mockito.any(CustomerDetail.class));
}
}
The above test case is failing with the message Never wanted here:, But invoked here:
Since both are of type any
it is unable to differentiate between which method should not be executed.
I have tried different variations like replacing the line -
Mockito.when(event.generateEvent(Mockito.any(Customer.class))).thenThrow(new RuntimeException());
with
Mockito.when(event.generateEvent(Customer.class)).thenThrow(new RuntimeException());
But it is not working because the Customer
object is something which is created inside handleUser
method and so both the instance are different and it is not throwing Exception which I setup in the Test.
Similar with,
Customer customer = new Customer;
customer.setValue("fsfw");
Mockito.when(event.generateEvent(customer)).thenThrow(new RuntimeException());
Again since both the Customer instance are different it is not throwing Exception as it is suppose to according to the Test setup.
Can any of you suggest how to test this one? Writing a test case like this works, but I don't know if this is the correct way to do it or not -
@Test
public void handleUserThrowsException() throws Exception {
Mockito.when(event.generateEvent(Mockito.any(Customer.class))).thenThrow(new RuntimeException());
try {
Response response1 = service.handleUser(user);
} catch(ServiceClassException e) {}
Mockito.verify(event, Mockito.never()).generateEvent(CustomerDetail.class);
}
Please let me know the correct way to do this kind of testing?