Reputation: 28981
I want to do: check if error
is invoked once with particular argument, but I don't care if other methods are called on the same mock.
final Logger logger = mock(Logger.class);
//code under test
logger.debug("Something");//I don't care if it's here
logger.error("Boo");// must be one
//logger.error("Baa");// must fail if un-comment
logger.info("Stuff");//I don't care if it's here
//assertions
verify(logger, times(1)).error("Boo");
???verify(logger, never()).error(anyString());// Wrong solution
???verifyNoMoreInteractions(logger);// Wrong solution
In other words, I want to verify how errors are reported, but I don't mind about debug and info.
How can I do it?
Upvotes: 1
Views: 100
Reputation: 1759
In General
If you want to check that you receive exactly x
errors but do not care about the text in the error:
verify(logger, times(x)).error(anyString());
If you want to check that you receive x
errors total, and that y
should have the text foo
and z
should have the text bar
:
verify(logger, times(x)).error(anyString());
verify(logger, times(y)).error("foo");
verify(logger, times(z)).error("bar");
// ... (potentially other cases)
In Context
So, for the example you provided, if you do not care about the error text, it would look like:
verify(logger, times(1)).error(anyString());
If you do care about the error text (IE: you want exactly 1 "Boo", and 1 total error):
verify(logger, times(1)).error("Boo");
verify(logger, times(1)).error(anyString());
As Jeff pointed out, the count parameter can be neglected if you are only looking for exactly one occurance.
Upvotes: 1
Reputation: 95704
times(1)
is the default behavior for verify
, so verify(logger).error("Boo");
should be sufficient. Mockito is designed on a philosophy of "nice mocks" that allow unexpected operations, so if you hold to that, it shouldn't matter whether it's called otherwise.
If you do want to check other calls, as you listed in the comments, you can use not
and never
:
verify(logger).error("Boo");
verify(logger, never()).error(not(eq("Boo")));
Or just get all calls with an ArgumentCaptor to confirm:
ArgumentCaptor<String> logCaptor = ArgumentCaptor.forClass(String.class);
verify(logger).error(logCaptor.capture());
assertEquals("Boo", logCaptor.getValue());
Upvotes: 1