I write following row in my test:
when(Product.fromNode(any(Node.class), any(Locale.class),anyString())).thenReturn(productMock);
I see following error message:
you cannot use argument matchers outside of verification or stubbing
It is impposible because I can't use any at this case. But I don't know what concrete argument will be passed to the method but I know that I should handle it same.
What can you advice for me ?
Problem was that I used PowerMockito.mockStatic
but I used RunWith annotation different than:
#RunWith(PowerMockRunner.class)
Related
I am curious if when(mock.method(SPECIFIC_PARAM)).thenReturn(RETURN_VAlUE); checks for invocation of method. Or should I do verify(mock).method(SPECIFIC_PARAM); to make sure the method has been invoked?
If you use #RunWith(MockitoJUnitRunner.class) or #ExtendWith(MockitoExtension.class), you will get an UnnecessaryStubbingException after running a test if you provided a mock that is not used.
You can avoid this by setting #MockitoSettings(strictness = Strictness.LENIENT) if you want to.
But even with the UnnecessaryStubbingException, it's still better to do an actual verify inside your test for readability. Your 'verify' can also be stricter than your stub, e.g:
when(mock.method(anyCollection())).thenReturn(...)
...
mock.method(collection);
...
verify(mock).method(argThat(collection -> collection.size()==1));
Basically when(mock.method(SPECIFIC_PARAM)).thenReturn(RETURN_VAlUE); signifies that when the method is invoked on the mock then the specified value is returned. The whenis used to configure the mocking, so it doesn't perform any verifications. It is the verify that checks if a method is called.
With the method when(..).thenReturn(...) you are defining a rule on the mock object, in your particular case, you are instructing the mock object to return "RETURN_VALUE" when the method mock.method is invoked with input parameter "SPECIFIC_PARAM".
You are actually not asserting anything over the mock object.
Instead, you can check the effective invocation of the mock's method, by using verify(mock), as you did in your description.
For example, this is what you should expect when your method is not invoked:
got: <Wanted but not invoked: mock.method(SPECIFIC_PARAM);
I am trying to mock Calendar.getInstance() for unit testing purpose.
I am thus using PowerMock (powermock-core:2.0.4 & powermock-module-junit4:2.0.4) and its Mockito API (powermock-api-mockito2:2.0.4).
I am well aware that similar cases do exist, but I am facing an exception that does not seem to appear on other's case.
Indeed, when doing
mockStatic(Calendar.class);
when(Calendar.getInstance()).thenReturn(aCalendar);
on a test method within a class annotated with
#RunWith(PowerMockRunner.class)
#PrepareForTest({DateUtils.class})
I get the following error : org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: class java.lang.Class.
What did I do wrong and how to solve it ?
Thanks
There are a couple issues here.
mockStatic(Calendar.class); this should be in setUp method or something.
Then you do this.
verifyStatic(Calendar.class)
when(Calendar.getInstance()).thenReturn(aCalendar);
Another important thing is the following,
#RunWith(PowerMockRunner.class)
#PrepareForTest({DateUtils.class, Calendar.class})
Any class that has static method you would like to mock should be included in #PrepareForTest either at the class level or method level, if it is used only once.
I have some testing method:
#Test
public void test_method() {
MyObj mock = mock(MyObj.class);
when(mock.get("testName", "1")).thenReturn("Result1");
when(mock.get("test", "2")).thenReturn("rrrr");
}
when I trying run this method I had exception:
org.mockito.exceptions.misusing.PotentialStubbingProblem:
Strict stubbing argument mismatch. Please check:
Typically, stubbing argument mismatch indicates user mistake when writing tests.
Mockito fails early so that you can debug potential problem easily.
However, there are legit scenarios when this exception generates false negative signal:
- stubbing the same method multiple times using 'given().will()' or 'when().then()' API
Please use 'will().given()' or 'doReturn().when()' API for stubbing.
- stubbed method is intentionally invoked with different arguments by code under test
Please use default or 'silent' JUnit Rule (equivalent of Strictness.LENIENT).
For more information see javadoc for PotentialStubbingProblem class.
How can I mock this method?
The error message tells you:
stubbing the same method multiple times using 'given().will()' or 'when().then()' API
Please use 'will().given()' or 'doReturn().when()' API for stubbing.
You can use any() to mock one method with different parameters. any() will be used as a dynamic variable.
e.g doReturn(order).when(orderRepository).save(any(Order.class));
I was saving orderRepository with 2 different Order parameters so I have used any with Order class.
I have such method:
<T extends Entity> boolean putObject(T value);
But can`t find out how to mock it using mockito? anyObject() and any() produce error:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
1 matchers expected, 3 recorded.
Mock:
when(service.putObject(any(ProcessingTransaction.class))).thenReturn(true);
How it shold work?
Most likely, you have one or two improperly-formed calls to Mockito methods, somewhere earlier in your test (or even in a previous test). When you call a Mockito method that makes an argument matcher (like any()), the matcher gets added to an internal data structure. It's then removed when it's actually used.
The fact that Mockito found three argument matchers instead of just one suggests that you made some argument matchers but didn't use them. For example, if you use when(...) without thenReturn(), this can happen; but there are lots of other cases too.
If you want help finding exactly what you've done wrong, you need to post more of your test code.
I am using EasyMock to create mock classes in test cases.
expect(entity.getType()).andReturn("string");
Type belongs to the String datatype. In my development environment it is working fine. But If I transfer to my server and take build, it is failing with following error:
java.lang.IllegalStateException: incompatible return value type
I don't know why it is failing in server and getting executed in my development machine.
Development EasyMock version: 2.5.2
I just had the same problem.
I had a partial mock in EasyMock, but forgot to call addMockedMethod for the method I wanted to set the expectation for.
The error message was the same as above, I'd say that was somewhat misleading.
In my case the method was final on which I called expect on. So EasyMock was not able to mock the method and thus did not record the method invocation.
Make sure that your entity object is not a simple POJO (eg. new Entity()), and it was created with the createMock() methods of EasyMock.
For me, I had to remember to call reset(...) on it after having used it once, or I (bizarrely) got this error message calling expect on it a second time.
If anyone gets this error when trying to mock behavior of a class's toString() method, e.g. expect(entity.toString()).andReturn("string");, EasyMock will instead invoke a special version of the toString() method on that line in the test, and will not modify the expected behavior of the method in the code under test. You basically can't mock any toString() behavior, and your test will liekly still pass if you just remove the line where you're trying to mock the call. PowerMock does not seem to offer any solutions in this case, since its #PrepareForTest doesn't change this behavior.