org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito - mockito

getting the error
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
1 matchers expected, 2 recorded.
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
at
when(
getProgramService
.callService(any(GetProgramType.class)))
.thenReturn(jAXBresponse);
please explain the error and possible resolution

The code you posted looks fine; I don't see a problem with it. It is likely the code immediately before or above it causing an exception. The key is here:
Invalid use of argument matchers! 1 matchers expected, 2 recorded.
any, as you used it above, doesn't return a "special kind of null" or "special kind of GetProgramType"; those don't exist. Instead, it returns null and as a side effect puts a matcher on a stack. When checking for matchers, Mockito looks at the stack, and checks that it is either empty (i.e. check equality with all arguments) or exactly equal to the number of arguments in the call you're checking (i.e. there is a matcher for each argument).
What's happening here is that you're getting one more matcher than the callService method expects. I see this often enough when developers mistakenly try to save a matcher in a local variable:
String expectedString = Matchers.anyString(); // DOESN'T WORK
// Instead, this just adds a matcher to the stack, almost certainly where it
// doesn't belong.
...or mock a final method:
// Assume getProgramService.otherMethod is final.
when(getProgramService.otherMethod(anyString())).thenReturn(123L);
// This actually calls getProgramService.otherMethod(null) and leaves an
// anyString matcher on the stack without setting any expectation that
// would returns 123L.
To confirm this is a problem, temporarily add this statement immediately before the one you posted:
Mockito.validateMockitoUsage();
This artificially checks the stack for matchers, and will likely throw an exception on that line. If it does, check the code above your post. Either way, adding some surrounding code to your question will likely help us debug it.

Related

Mockito verify doesn't match multiple stub

It seems that, when I use thenReturn like this:
when(abc.call()).thenReturn(a).thenReturn(b),
I expect:
verify(abc, times(2)).call()
instead, the method seems only get called once, I am a little confused(my test work as expected, the mock seems return the value I expected), but for the invocation times, I don't know if I am getting the wrong result, or it's a expected behavior of the Mockito?
when() is mocking the abc.call() method which has to produce a certain return type. If the method is called once, it will return the value also once, so the stubbing for method invocation is done only once hence the verify only recognizes one call.
You need to customize your function so that the stub(abc.call()) gets called more than once.
You can follow this thread for implementing multiple stubs

Verifying method call with different arguments using argument matchers eq() fails complaining Argument(s) are different

I'm writing a test case to validate execution with specific method call with specific arguments. The test need to pass only when specific values are passed (for ex. only pass when status & ParseError is passed) to the method. Below is the code snippet for the test to verify:
Mockito.verify(exeImpl, Mockito.atLeastOnce()).setData(eq("status"), eq("ParseError"));
and case failed with below:
Argument(s) are different! Wanted:
exeImpl.setData(
"status",
"ParseError"
);
-> at com.TestTask.testRest(TestTask.java:280)
Actual invocation has different arguments:
exeImpl.setData(
"status",
"Error"
);
-> at
com.TestTask.setDefault(Task.java:186)
The actual invocation which is mentioned in the error is because the setData is called with default values before starting the business logic. After the business logic is done, the setData is called again to set the result.
And setData has below definition
setData(final String arg1, final Object arg2) {...}
I know about ArgumentCaptor, but I'm just trying to make it work like this as i believe the matcher eq() is used here to check the equals of the value passed for both the arguments. Or is it causing issue because it is object.
Will it be possible to verify like this? Thanks.
The issue was with my code as my test was not initialized properly with #Before.

Mockito and Mockito.any(Map.class)

Using Mockito I got in trouble with the following:
Mockito.when(restOperationMock.exchange(
Mockito.anyString(),
Mockito.any(HttpMethod.class),
Mockito.any(HttpEntity.class),
Mockito.eq(CustomerResponse.class),
**Mockito.anyMap()**)).
thenReturn(re);
The problem was the method wasn't intercepted because I was using Mockito.any(Map.class) instead of Mockito.anyMap() and I was passing as a parameter a HashMap. What are the differences between Mockito.any(Map.class) and Mockito.anyMap()?
There is only one small difference between any(Map.class) and anyMap(): Starting with Mockito 2.0, Mockito will treat the any(Map.class) call to mean isA(Map.class) rather than ignoring the parameter entirely. (See the comment from Mockito contributor Brice on this SO answer.) Because restOperationMock.exchange takes an Object vararg, you may need anyMap to catch a case where a non-Map object is being passed, or no object at all is passed.
(I'd previously put that as a "dummy value" to return, Mockito can return an empty Map for calls to anyMap(), but can only return a null for calls to any(Map.class). If restOperationMock.exchange delegates to a real implementation during stubbing, such as if it were a spy or unmockable method (final method, method on a final class, etc), then that dummy value may be used in real code. However, that's only true for any(); anyMap() and any(Map.class) both give Mockito enough information to return a dummy Map implementation, where any() has its generics erased and only knows enough to return null.)

what does getType do in antlr4?

This question is with reference to the Cymbol code from the book (~ page 143) :
int t = ctx.type().start.getType(); // in DefPhase.enterFunctionDecl()
Symbol.Type type = CheckSymbols.getType(t);
What does each component return: "ctx.type()", "start", "getType()" ? The book does not contain any explanation about these names.
I can "kind of" understand that "ctx.type()" refers to the "type" rule, and "getType()" returns the number associated with it. But what exactly does the "start" do?
Also, to generalize this question: what is the mechanism to get the value/structure returned by a rule - especially in the context of usage in a listener?
I can see that for an ID, it is:
String name = ctx.ID().getText();
And as in above, for an enumeration of keywords it is via "start.getType()". Any other special kinds of access that I should be aware of?
Lets disassemble problem step by step. Obviously, ctx is instance of CymbolParser.FunctionDeclContext. On page 98-99 you can see how grammar and ParseTree are implemented (at least the feeling - for real implementation please see th .g4 file).
Take a look at the figure of AST on page 99 - you can see that node FunctionDeclContext has a several children, one labeled type. Intuitively you see that it somehow correspond with function return-type. This is the node you retrieve when calling CymbolParser.FunctionDeclContext::type. The return type is probably sth like TypeContext.
Note that methods without 'get' at the beginning are usually children-getters - e.g. you can access the block by calling CymbolParser.FunctionDeclContext::block.
So you got the type context of the method you got passed. You can call either begin or end on any context to get first of last Token defining the context. Simply start gets you "the first word". In this case, the first Token is of course the function return-type itsef, e.g. int.
And the last call - Token::getType returns integral representation of Token.
You can find more information at API reference webpages - Context, Token. But the best way of understanding the behavior is reading through the generated ANTLR classes such as <GrammarName>Parser etc. And to be complete, I attach a link to the book.

Conflict between GroovyTruth and implicit constructor

I have noticed some conflict between implicit constructor and GroovyTruth.
Consider following code
assert new File('/') == ['/'] as File
assert Boolean.TRUE == ["false"] as Boolean
First line is implict call of File(String) constructor.
Second line simply returns true, because list is not empty. But it can(should?) call Boolean(String) constructor with different result value(false).
Is it bug, documented feature or smth. else? Should I report it as bug?
When you do:
['false'] as Boolean
It ends up going through DefaultTypeTransformation.castToType, which calls castToBoolean which as you can see checks for null, then calls asBoolean on the Collection type which just checks it's not empty
With the File example, it falls through to the bottom of castToType and just tries to invoke the constructor with the contents of the list
I wouldn't say this is a bug, but it's definitely an idiosyncrasy of Groovy that has to be taken in to account (and changing it now would be a massive break with compatibility)

Resources