I am trying to mock a static method of enum which has null value like below
try (MockedStatic<SomEnum> e = Mockito.mockStatic(SomEnum.class)) {
e.when(() -> SomEnum.methodWhichAcceptingNullParam(any())).thenReturn(somValue);
}
here any() is not working... i am not sure I am passing null parameter inside method
methodWhichAcceptingNullParam
I have tried both any and isNull.The fact is SomEnum.methodWhichAcceptingNullParam is always get called however it should not because I provided a mocked value already
any help?
Is your code called with a null or not-null object? This information is missing (at least for me).
Assuming you are calling SomeEnum.methodWhichAcceptingNullParam(null), then you need to use
ArgumentMatchers.isNull()
instead of any().
Related
I have a question regarding using Mockito thenCallRealMethod. I've read the warnings about using this function; basically I want to write this into my test to futureproof my application logic, because it's being used as a library and I want to make sure users of my library have futureproof protection.
My test case looks like this:
#Test
public void Test() {
when(restTemplate.postForEntity(...)).thenReturn(new ResponseEntity<>(realObjectMapper.writeValueAsString(data), HttpStatus.OK));
when(objectMapper.readValue(realObjectMapper.writeValueAsString(data), TestData.class)).thenCallRealMethod();
TestData result = tested.callMethod(...);
....
}
TestData is a simple POJO which contains a bunch of fields but nothing particularly interesting, and data is an instance of TestData. objectMapper is a mocked instance of FasterXML Jackson ObjectMapper, and realObjectMapper is a real (unmocked) instance of the same class.
The problem I'm having is a NullPointerException when my application attempts to execute objectMapper.readValue (on the mocked instance) as per the thenCallRealMethod on the second line of the test. I've verified that when I pass the same inputs to realObjectMapper.readValue then it executes fine, so there is nothing wrong with the input. What am I missing?
Stack trace:
java.lang.NullPointerException
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2842)
.... (my code here)
When you use a mocked object then the real object is not initialized. That means any property even with a default value will be null.
In my case I had a property injected with #Value from a properties file, but if I define a default value it happens the same, it is null when it is going to be used.
Solution: Yo have to check which is the property causing the null pointer exception on the method and then either mock a getter that returns the expected value of that property and call the getter from your real method or set its value with a setter from the test, after the mock object is created
I've seen a lot of examples, and I know what has been discussed.
I do everything right, but I receive an error. Why is that? What am i doing wrong?
Class superClass = rootObject.getSuperclass();
Method addErrorMethod = superClass.getDeclaredMethod("addErrorMessage", ErrorType.class, String.class, String.class, String.class);
_log.info(addErrorMethod.getName());
addErrorMethod.invoke(superClass, ErrorType.FIELD, propertyName, message, "");
I get method, but when you call the invoker. I get the following error.
java.lang.IllegalArgumentException: object is not an instance of declaring class
Thanks.
When you call Method.invoke the first parameter must be either:
when method is non-static instance of the class which contains the method
when method is static null or class itself.
Since you pass the class itself and you got error it suggests that method you are trying to invoke is not static, so you should invoke it like
addErrorMethod.invoke(rootObject, ErrorType.FIELD, propertyName, message, "");
// ^^^^^^^^^^- assuming it is instance on which we want to invoke this method
You did not do everything right:
addErrorMethod.invoke(superClass, ErrorType.FIELD, propertyName, message, "");
should read
addErrorMethod.invoke(rootObject, ErrorType.FIELD, propertyName, message, "");
superClass is an instance of Class, to which has no addErrorMessage() method, as the error message is telling you. The first parameter to the method is a reference to the object that will be used as this within the method.
Collection<T_SI_IDABAREME> tSiIdabaremes;
DAO_F_IDA_DESC mockDaoFIdaDesc
prepareExpects(){
expect(mockDaoTSiIdabareme.findByDate(isA(Date.class)))
.andReturn(searchByParameter(tSiIdabaremes, date));
}
Is it possible to use the date that will be passed to the findByDate in the andReturn?
PS: This is a service test class and I'm doing it in a way to bypass the database.
whenever you use expect method like this
Easymock.expect(someMethod(Date.Class)).andReturn(something);
you are instructing compiler to mock all calls to that method whenever ANY object of Date class is passed as parameter,and you will not be able to use that object in return expression.
on the other hand if you have something like this,
Easymock.expect(someMethod(someSpecificDateObject)).andReturn(someSpecificDateObject);
you are instructing the compiler to mock this method call ONLY when a specific object of Date class is passed as parameter(someSpecificDateObject in this case) and you will be able to use this parameter while returning, because you know that method gets mocked only when this object is passed.
You can use second option if it is favourable to you,but with first option what you ask is not possible.
Hope this helps!
Good luck!
Instead of:
expect(mockDaoTSiIdabareme.findByDate(isA(Date.class)))
.andReturn(searchByParameter(tSiIdabaremes, date));
I should have put
expect(mockDaoTSiIdabareme.findByDate(isA(Date.class)))
.andAnswer(new IAnswer<Collection<T_SI_IDABAREME>>() {
public Collection<T_SI_IDABAREME> answer() throws Throwable {
return searchByParameter((Date)getCurrentArguments()[0]);
}
}
);
Which will only look for the return value when the method is being exectued and then we can use getCurrentArguments() to retrieve the arguments passed to the method.
You can find more about this in the EasyMock Documentation.
I have the following class:
mockStatic(Exception.class);
PowerMockito.doNothing().when(Exception.class);
Exception.throwErrorIfExists(any(Object.class)); // line3
In exception class,method is defined as follows:
static void throwErrorIfExists(def model){
if(model.hasErrors())
throwError(model)
}
The following exception is thrown at line 3: Cannot invoke method hasErrors() on null object
java.lang.NullPointerException: Cannot invoke method hasErrors() on null object
How can any(object.class) be NULL in any circumstances because any simply means return any anything?
I think you are misusing the any() method. This method exists so that you can verify interactions with mocks, e.g. you can say:
// checks yourMethod() was invoked with any argument
verify(mockedObject).yourMethod(any(SomeClass.class));
If you want to call your method with some arbitrary object, you should create the object in your test and pass it in. any() is not a method that just makes objects for you.
You can't invoke ThrowErrorIfExists with a null parameter, as you invoke a method (hasErrors() on it. This has nothing to do with any mocking, but it is just an error in your method.
You use a matcher to call the method
Exception.throwErrorIfExists(any(Object.class));
which is quite strange; matchers are used to configure the behaviour of a mock like
PowerMockito.doNothing().when(Exception.throwErrorIfExists(any(Object.class)));
Then you can call throwErrorIfExists with any object to trigger the "do nothing".
I have an interface containing the declaration of this method :
#WebMethod(operationName = "foo")
public long[] foo(String params[]);
Right now if I call this method with 'param' containing null values they are ignored and only non null values are taken in account.
How can I pass null values? I heard of using 'nillable' within the 'XmlElement' annotation but it doesn't work for me.
Thanks in advance,
Marc.