Mockito - Invalid use of argument matchers - unit-testing

I have Junit test that is testing jms message sending. I am using Spring jmsTemplate to to do this. Here I as in the following code I want to check whether the JMS template has called send message regardless what is it in the values of actuall parameters that are passed.
my publisher method the uses the jmsTemplate to send method looks like following inside..
jmsTemplate.send(jmsQueueProperties.getProperty(key), new MessageCreator()
{
public Message createMessage(Session session) throws JMSException
{
ObjectMessage obj = session.createObjectMessage(dialogueServiceResponse);
return obj;
}
});
in My tests..
JmsTemplate mockTemplate = Mockito.mock(JmsTemplate.class);
...
publisher.publishServiceMessage(response);
....
Mockito.verify(mockTemplate,
Mockito.times(1)).send("appointment.queue",
Mockito.any(MessageCreator.class));
But when in the execution i get
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers!
....
Cause is due to Mockito.any(MessageCreator.class) , but isn't there a way to test my send method is getting executed without creating an actual object in the MessageCreator.
Update
And is there a way to check my session.createObjectMessage(dialogueServiceResponse) is getting called as well

I think the rest of the message tells you what the problem is. When you use an argument matcher for one of the arguments, all the other arguments must also use an argument matcher:
Mockito.verify(mockTemplate, Mockito.times(1)).send(
Mockito.eq("appointment.queue"),
Mockito.any(MessageCreator.class));

For future readers. This will save you a lot of time.
We cannot use argument matcher and primitive/raw values together.
when(fooService.getResult("string",any(MyClass.class))).thenReturn(1); // will give error
when(fooService.getResult(anyString(),any(MyClass.class))).thenReturn(1); // correct

I think you cannot use argument matchers outside stubbing. I also got the same error but when I return, I had to do new string() instead of Mockito.anyString() and the error goes away.
Example:
Mockito.when(mockedBean.mockedMethod(Mockito.anyString(),
Mockito.anyInt(),
Mockito.anyInt(),
Mockito.anyInt(),
Mockito.anyBoolean())).thenReturn(new String());

I can see that this question is about Java code, but I will share this because we use Mockito in Scala as well.
I had this exception thrown from the following code that mocks Play.api configurations
"Configurations Service" should {
"return all dataset configurations" in {
val configs = mock[Configuration]
val testData = Seq("SOME VALUE")
val loader = any[ConfigLoader[Seq[String]]]
when(configs.get[Seq[String]](any[String])).thenReturn(testData) // EXCEPTIONN HERE !
val configuration: ConfigurationsService = new ConfigurationsService(configs)
assert(configuration.getSupportedDatasets() == testData)
}
}
In Scala methods can have Implicit parameters configs.get method has one explicit param and an Implicit one I passed a mock object and when an exception was thrown I was wondering what is going on as I didn't MIX params and mocks, it turned out that I had to pass mocks to implicit parameters as well, and this solved the problem.
val loader = any[ConfigLoader[Seq[String]]] // configs.get has one implicit parameter that accepts ConfigLoader[Seq[String]]
when(configs.get[Seq[String]](any[String])(loader)).thenReturn(testData)

I was seeing this error about a mismatched # of arguments, despite having the correct number...
I realized this was because method being stubbed was static. When I converted it to non-static, it worked as expected.

Related

Why typecasting is required in below code?

I have a snipped as mentioned below for step processing.
#Bean
#JobScope
public Step readStep(StepBuilderFactory sbf,
ItemReader reader,ItemWriter writer, TaskExecutor taskExecutor,
RefFileReaderComponentFactory componentFactory, String file){
final Step step = sbf.get(file)
.chunk(100)
.reader(reader)
.faultTolerant()
.skipPolicy(new SkipPolicy()) //dummy skip policy for representation purpose
.writer(writer)
.faultTolerant()
.skipPolicy(new SkipPolicy())
.listener(new NewStepExecutionListener()) //This dummy listener is implementation of the StepExecutionListener
//.listener(new NewItemWrtieListener) //This dummy listener is implementation of the ItemWriteListener
.taskExecutor(taskExecutor)
.build();
return step;
}
But the above code throws compile time error - The method taskExecutor(TaskExecutor) is undefined for the type StepBuilderHelper.
Interestingly, this error is only shown when I put NewStepExecutionListener listener but if I comment it out and uncomment NewItemWrtieListener then it works fine.
Post typecasting, code looks like this:
#Bean
#JobScope
public Step readStep(StepBuilderFactory sbf,
ItemReader reader,ItemWriter writer, TaskExecutor taskExecutor,
RefFileReaderComponentFactory componentFactory, String file){
final Step step = ((AbstractTaskletStepBuilder<SimpleStepBuilder<Object, Object>>) sbf.get(file)
.chunk(100)
.reader(reader)
.faultTolerant()
.skipPolicy(new SkipPolicy()) //dummy skip policy for representation purpose
.writer(writer)
.faultTolerant()
.skipPolicy(new SkipPolicy())
.listener(new NewStepExecutionListener())) //This dummy listener is implementation of the StepExecutionListener
//.listener(new NewItemWrtieListener) //This dummy listener is implementation of the ItemWriteListener
.taskExecutor(taskExecutor)
.build();
return step;
}
I tried finding reason behind this but cannot understand why a change in Listener Type would require typecasting for step processing.
Can someone explain why ?
The order of method calls matters because some methods may change the builder type. For example, when you call faultTolerant(), the builder type is changed from SimpleStepBuilder to FaultTolerantStepBuilder, adding new methods to configure fault tolerance (skip, retry, etc).
So you need to check the order and return type of each method and make sure the builder type returned defines the next method you want to call.

EasyMock failing test case with "Invalid use of argument matchers! 2 matchers expected, 1 recorded" error

Let's name our test file as ExecutorTest.java. In this file we have a unit test case which mocks a static method using EasyMock like this -
Executor exectorInstance;
PowerMock.mockStaticPartial(SomeClass.class, "someStaticMethod", Map.class, SomeOtherClass.class);
EasyMock.expect(SomeClass.someStaticMethod(Mockito.any(Map.class), SomeOtherClassObject)).andReturn(false);
PowerMock.replayAll();
exectorInstance.execute();
Executor.java -
public void execute() {
String clientName = someObject.getInformation(); //using this string while logging the metric
logMetric(className + clientName);
if(SomeClass.someStaticMethod(someMapObject, someOtherClassObject){
// some code
}
}
I have added only this line in my code after which that unit test case started failing with error : "Invalid use of argument matchers! 2 matchers expected, 1 recorded" error"
String someInformation = someObject.getInformation();
I got this string & added that string to a metric which we were already logging.
The line which has started throwing the error is this :
PowerMock.mockStaticPartial(SomeClass.class, "myStaticMethod", Map.class, SomeOtherClass.class);
I am scratching my head for a few days now but not able to find the root cause. I am very new to this mocking stuff. It doesn't look like I have made any change related to matcher. I am just getting a string & adding that string to a already existing metric. My small change looks completely unrelated to this but don't know why it has started failing the test case.
Please help me finding the reason.
These two points should solve your problem.
You are using a matcher (Mockito.any()) from Mockito while using EasyMock. Won't work
As soon as you use a matcher in an expectation, you need to use one for all parameters.
Your expectation should be something like this:
EasyMock.expect(SomeClass.someStaticMethod(EasyMock.any(Map.class), EasyMock.eq(SomeOtherClassObject))).andReturn(false);

How to mockup TWebRequest/TIdHTTPAppRequest?

I have a function that accept a TWebRequest by argument, eg.:
function foo(const request: TWebRequest ): boolean;
how can i create a TWebRequest and set some property like:
Host
ServerPort
QueryFields
ContentFields
I have tried:
var
aWebRequest: TWebRequest;
begin
aWebRequest := TWebRequest.Create;
but on creation Delphi raise an exception:
First chance exception at $XXXXXXXX. Exception class EAbstractError
with message 'Abstract Error'.
the descendant is TIdHTTPAppRequest, but it require:
constructor TIdHTTPAppRequest.Create(
AThread: TIdContext;
ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo
);
each argument require other object etc etc.
there is a simple way (eg. third party unit, unknown snippet or trick) for mockup a request for unit test purpose?
EAbstractError usually means that you are trying to instantiate generic abstract class (e.g. TStrings) instead of it's descendant that contains required implementations (e.g. TStringList). So you need to find the TWebRequest descendant and use it instead.
For mocking purposes you could try to write your own "empty" descendant, but I doubt that will work as expected.

getting InvalidUseOfMatchersException in a proper use of matchers

Everything sounds correct but I get org.mockito.exceptions.misusing.InvalidUseOfMatchersException, when I try to mock a protected method.How Can I solve it ?
private Service service;
private System system;
#BeforeMethod
public void setupMocks() throws Exception {
service = powerMock.mock(Service.class);
system = powerMock.mock(System.class);
}
public void sample_Test() {
PowerMockito.doReturn(system).when(service, "getValidatedDto",
Matchers.any(Long.class), Matchers.any(Date.class));
// some code
}
I suspect you are seeing this exception:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
4 matchers expected, 2 recorded:
With this additional context:
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
If so, then this is because you are mixing parameters in the form of matchers (Matchers.any(Long.class), Matchers.any(Date.class)) with parameters in the form of raw values (service, "getValidatedDto").
The signature of the method under test is unclear to me but I think it might be something like
System getValidatedDto(Long aLong, Date aDate);
If so, then the correct invocation would be:
PowerMockito.doReturn(system).when(service).getValidatedDto(
Matchers.any(Long.class), Matchers.any(Date.class));

Avoiding downcasts in a Swift 3 completion handler with Google Drive REST API

I'm using the Google Drive REST API in a Swift 3 app. Queries are executed using the executeQuery method of GTLRDriveService. This method takes a completion block of type GTLRServiceCompletionHandler?, which in turn is declared as
public typealias GTLRServiceCompletionHandler = (GTLRServiceTicket, Any?, Error?) -> Swift.Void
Because of this declaration, the second parameter must be downcast to the appropriate type inside the block. For instance:
let createPermissionQuery = GTLRDriveQuery_PermissionsCreate.query(
withObject: permission, fileId: toShare.id)
...
driveService.executeQuery(createPermissionQuery) { (ticket, result, error) in
if (error == nil) {
// need to downcast result to GTLRDrive_Permission
let permission = result as! GTLRDrive_Permission
...
}
}
The second parameter is always of a specific type that is completely determined by the particular query passed to executeQuery. For instance, if one passes an instance of GTLRDriveQuery_PermissionsCreate, then the second parameter (if the query succeeds) will always be of type GTLRDrive_Permission. However, if I try to declare result to be of any type other than Any?, the code won't compile.
In Objective C, the completion block can be specified with a type that's specific to the query. For instance (adapted from here):
GTLRDriveQuery_PermissionsCreate *createPermissionQuery =
[GTLRDriveQuery_PermissionsCreate queryWithObject:permission
fileId:fileId];
...
[driveService executeQuery:createPermissionQuery
completionHandler:^((GTLRServiceTicket *ticket,
GTLRDrive_Permission *permission,
NSError *error) {
if (error == nil) {
// work directly with permission
...
}
}];
Is there any way to avoid this downcast? (I'm asking out of ignorance; I'm somewhat of a newbie to Swift.) If I was writing my own library, I'd design the method signatures differently, but this is Google's library and am kind of stuck with what they supply. Perhaps some sort of extension or layer on top of Google's code?
You might be able to specify an extension that wraps the Google execute method, takes a generic and casts to your generic type in the block. This would basically just be a pretty abstraction of what you're doing already, but for all types your extension would be designed to cover.