Non-sensical Error: Misplaced argument matcher detected here. You cannot use argument matchers outside of verification or stubbing in Mockito - unit-testing

I have multiple Spock Test Suites in my code. When I try to execute them serially, I am getting the following error message on running Spock Tests:
Misplaced or misused argument matcher detected here:
[junit]
[junit] -> at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
[junit]
[junit] You cannot use argument matchers outside of verification or stubbing.
[junit] Examples of correct usage of argument matchers:
[junit] when(mock.get(anyInt())).thenReturn(null);
[junit] doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
[junit] verify(mock).someMethod(contains("foo"))
[junit]
[junit] This message may appear after an NullPointerException if the last matcher is returning an object
[junit] like any() but the stubbed method signature expect a primitive argument, in this case,
[junit] use primitive alternatives.
[junit] when(mock.get(any())); // bad use, will raise NPE
[junit] when(mock.get(anyInt())); // correct usage use
[junit]
[junit] Also, this error might show up because you use argument matchers with methods that cannot be mocked.
[junit] Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
[junit] Mocking methods declared on non-public parent classes is not supported.
[junit]
[junit] org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
[junit] Misplaced or misused argument matcher detected here:
[junit]
[junit] -> at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
[junit]
[junit] You cannot use argument matchers outside of verification or stubbing.
[junit] Examples of correct usage of argument matchers:
[junit] when(mock.get(anyInt())).thenReturn(null);
[junit] doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
[junit] verify(mock).someMethod(contains("foo"))
[junit]
[junit] This message may appear after an NullPointerException if the last matcher is returning an object
[junit] like any() but the stubbed method signature expect a primitive argument, in this case,
[junit] use primitive alternatives.
[junit] when(mock.get(any())); // bad use, will raise NPE
[junit] when(mock.get(anyInt())); // correct usage use
[junit]
[junit] Also, this error might show up because you use argument matchers with methods that cannot be mocked.
[junit] Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
[junit] Mocking methods declared on non-public parent classes is not supported.
[junit]
[junit] at com.example.app.MySecondTest.test update usages(MySecondTest.groovy:19)
[junit]
However, the error points to MySecondTest.groovy:19 which in my case contains the following code
ExampleService exampleService = Mockito.mock(ExampleService.class)
There is no use of Argument Matcher in MySecondTest. But still I am getting this error.
Curiously, if I run only this test, I do not get any error and the test runs successfully

It turns out the error message points to next TestSuite that is executed after the test that actually contains a misplaced Argument Matcher.
In my case, the test suite MyFirstTest, which was executed before the test suite MySecondTest contained a test method that had a misplaced Argument Matcher.

Related

What is difference between argThat and captureThat matchers in dart mockito?

I've tried to find the difference here https://pub.dev/packages/mockito and using documentation to this matchers but didn't get it. Could someone provide example where I supposed to use captureThat rather than argThat?
The documentation for argThat states:
An argument matcher that matches an argument that matches matcher.
The documentation for captureThat states:
An argument matcher that matches an argument that matches matcher, and captures the argument for later access with captured.
Therefore the difference is that captureThat captures the matched argument for later examination whereas argThat does not.
See Capturing arguments for further assertions from the Mockito documentation for examples for how to use captured arguments.

Why does []mutable{} not compile?

This compiles:
[]{};
This as well:
[]() mutable {};
But with this code, compilers throw error messages at me:
[] mutable {};
^~~~~~~
error: lambda requires '()' before 'mutable'
Is there any particular reason why?
It's just a consequence of the way the grammar is written in the standard. I don't know if this is an oversight or not.
A lambda expression starts with a lambda introducer (the brackets), followed by an optional lambda declarator.
The lambda declarator contains the argument list, mutable, attributes, exception specifier and return type. All these are optional, except for the argument list. So if a lambda declarator is present at all, the parentheses must be there.
This is why you can't only have the mutable keyword.
Looking in section 5.1.2 [expr.prim.lambda] in n4296 (which is the C++14 final draft), that's just the way it falls out of the grammar. mutable is only allowed in a lambda-declarator - which includes the brackets. The whole lambda-declarator is optional though (which is why you can omit the brackets).

CDI Unit Test fails with unsatisified dependency Exception for Qualifier Type

Hi I have a following Qualifier Type defined..
#Qualifier
#Retention(RetentionPolicy.RUNTIME)
#Target({ ElementType.TYPE, ElementType.FIELD })
public #interface SortAndFilterType {
/**
* The value for the sort and filter.
*
* #return the sort and filter type value.
*/
String value();
}
And Two Implementations out of it.
#SortAndFilterType("Users")
public class UserSortAndFilterProviderImpl implements SortAndFilterProvider<Field, User> {}
#SortAndFilterType("ReportsList")
public class ReportListSortAndFilterProviderImpl implements SortAndFilterProvider<Field, ReportList> {}
And I'm injecting from the Client as ..
#Inject
#SortAndFilterType("Users")
private SortAndFilterProvider mSortAndFilterProvider;
Every thing works fine at run time..
But the Problem comes when I ran Unit tests..
I'm getting the below Exception..
org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type SortAndFilterProvider with qualifiers #SortAndFilterType
at injection point [BackedAnnotatedField] #Inject #SortAndFilterType private com.collabnet.ctf.saturn.client.apps.users.ChangeUsersStatus.mSortAndFilterProvider
I invoke this from unit tests like this..it runs with #RunWith(CdiRunner.class)
#Produces
#SortAndFilterType("Users")
#Mock
private SortAndFilterProvider mSortAndFilterProvider;
Whats going wrong here?
One nice thing with CDI (which is a problem for you here) is that its type safe resolution takes parameter in parameterized types into account. In other word : "no type erasure in CDI"
The spec is very detailed about parameterized types resolution :
A parameterized bean type is considered assignable to a parameterized
required type if they have identical raw type and for each parameter:
the required type parameter and the bean type parameter are actual types with identical raw type, and, if the type is parameterized, the
bean type parameter is assignable to the required type parameter
according to these rules, or
the required type parameter is a wildcard, the bean type parameter is an actual type and the actual type is assignable to the upper
bound, if any, of the wildcard and assignable from the lower bound, if
any, of the wildcard, or
the required type parameter is a wildcard, the bean type parameter is a type variable and the upper bound of the type variable is
assignable to or assignable from the upper bound, if any, of the
wildcard and assignable from the lower bound, if any, of the wildcard,
or
the required type parameter is an actual type, the bean type parameter is a type variable and the actual type is assignable to the
upper bound, if any, of the type variable, or
the required type parameter and the bean type parameter are both type variables and the upper bound of the required type parameter is
assignable to the upper bound, if any, of the bean type parameter.
You can read the original text here : http://docs.jboss.org/cdi/spec/1.2/cdi-spec.html#assignable_parameters.
Now Weld 1.x is not enough strict with this point and accept to assign a parameterized type to its raw type. That's probably why you don't have issue at runtime (running with JBoss AS 7.x for instance) and have this problem in your test (cdi-runner is probably using Weld 2.x). Yes I'm guessing here and I may be wrong, that's why it's always a good thing to give version of framework you're using in your question.
Anyway you should resolve your problem by changing you injection point to
#Inject
#SortAndFilterType("Users")
private SortAndFilterProvider<Field,?> mSortAndFilterProvider;
It respects the specification and will work under Weld 1.x and 2.x.
By the way you probably don't need your qualifier since there won't be any ambiguity between :
#Inject
private SortAndFilterProvider<Field,User> mSortAndFilterProvider1;
and
#Inject
private SortAndFilterProvider<Field,ReportList> mSortAndFilterProvider2;
Hi that's Exactly the Problem. and my Runtime uses Jboss 7 and the Test Environment uses CDI 2.x.
After adding the type parameters to the Injection point it works perfectly fine.
Thanks a lot.

What does `(&)()` mean in a C++ compiler error message

What does this error mean?
error: no matching function for call to `foo::bar(Qux (&)())`
I understand that the compiler (g++) is failing to match a function call with a foo member function. I am asking specifically about the extra stuff at the end; this bit: (&)().
For reference, my function call is like this:
// inside another member function of `foo`
Qux qux();
this->bar(qux);
And the signature for bar is:
virtual void bar(Qux&);
The compiler is also saying that the only candidate is:
virtual void bar(Qux&);
How does my function call signature differ from my definition signature, and what does (&)() mean?
Well, (&)() alone doesn't mean anything. (&)() is just a part of Qux (&)() which means reference to a function which takes nothing and return Qux. And this arises because of this:
Qux qux(); //PROBLEM!
this->bar(qux);
The first line here does NOT declare an object. It declares a function instead.
Search for vexing parse in C++, on this site, you'll see lots of topic on it, that discuss this problem in detail.
You should use Qux qux; (or alternatively in C++11 Qux qux{};) to avoid the most vexing parse.
The expression Qux (&)() means a reference to a function taking no arguments and returning Qux. This has already been explained by others. But that does not really address the specific detail of What does (&)() mean in a [g++] C++ compiler error message?
When the compiler encounters a function call that it cannot resolve it tried to provide as much information in the error as possible. This particular type of error in g++ is printed as multiple lines, from the second on, the compiler will list the exact signatures of the candidates for overload resolution (i.e. known overloads of the function name found by lookup at the place of call). The first line is a bit trickier, as it represents the actual call:
this->bar(qux). If that was printed in the error message you would have to figure out what are the types of the different arguments, in particular what is the type of this and the type of qux.
The approach taken by the g++ implementation is to write something like a function signature that somehow represents the call. The problem is that it is actually impossible to represent the least restrictive signature that could be used, so it uses the same syntax with a slightly different meaning.
In particular, an lvalue-expression argument will be denoted by a (possibly const) reference to the type of the expression, while an rvalue-expression is denoted by a non-reference type. Going back to the error message you got:
error: no matching function for call to `foo::bar(Qux (&)())`
This means that at the place of call, the first argument is an lvalue-expression denoting an object (well, functions are not objects but bear with me) of type Qux(), that is a function taking no arguments and returning a Qux by value.
In this particular case, the argument being a non-const lvalue-expression, the reading is not more confusing than parsing the type itself, but in other cases it is important to note that this is not really a signature. For example if the error message was:
error: no matching function for call to `foo::bar(Qux)`
It could be non-obvious why the only candidate is not a perfect match, does it not take a Qux, which is what you are telling me that is being passed? Except that this syntax is representing a call with an rvalue-expression that cannot be bound by an lvalue-reference.
Similarly, if the argument was a const Qux lvalue, the error would have been:
error: no matching function for call to `foo::bar(const Qux&)`
Indicating that the argument is an lvalue-expression but that the type is const Qux which again cannot be bound by a non-const lvalue-reference.
Reading error messages is an art in itself, but it is an important part of the craft. You should pay attention whenever you have an error at the language that the compiler is using, as that will help you understand the issue the next time that you see a similar error message.
Qux qux();
declares a function taking no arguments and returning Qux.
You should write
Qux qux;
to define an object of type Qux.
Qux qux();
That is a function declaration.
this->bar(qux);
That is attempting to pass a reference to the function qux to bar.
If you wanted to default-construct qux, leave out the ():
Qux qux;

map with incomplete value type

I'm getting an error with the following:
class Test
{
std::map<std::string,Test> test;
};
The error is "Field has incomplete type 'Test'". I read a few threads with suggested this might be a bug in the version of libcxx which ships with xcode, but it wouldn't surprise me at all if I just have to change it to:
class Test
{
std::map<std::string,std::shared_ptr<Test>> test;
};
I just wanted to double check that this is definitely a correct error and not a bug.
Cheers!
The standard requires that, all types used in template components of the standard library must be complete, unless otherwise stated. Thus libc++'s error is correct. Using an incomplete type is undefined behavior (§17.6.4.8[res.on.functions]/2), so libstdc++ accepting it isn't wrong either.
You could use a pointer object to construct the complete type as you did. But you could also use some third-party collections library which allows incomplete types, e.g. boost::container::map is designed to allow incomplete types.
§17.6.4.8 Other functions / 2:
In particular, the effects are undefined in the following cases:
...
if an incomplete type (3.9) is used as a template argument when instantiating a template component, unless specifically allowed for that component.
(The only components that explicitly allow incomplete types are declval, unique_ptr, default_delete, shared_ptr, weak_ptr and enable_shared_from_this.)