So I am writing some Scala tests for some Java code (I am very new at both of them). What I am trying to do is instead of calling .create on the Configuration class, I want to call create on the conf mock object. How can I go about doing this?
When I try to call .create on a mock of the Configuration class, I get an error since (I think) .create is a static method from a custom abstract Configuration java class
Scala test code:
var conf: Configuration = mock[Configuration]
when(Configuration.create("var1","var2", "var3")).thenReturn(testConfiguration)
Thanks!
I have a class with a method like this
class MyClass(){
public String myMethod(){
Logger.info(new MyOtherClass().myOtherMethod());
}
}
How can I mock the call of myOtherMethod() with EasyMock?
Background :
Initially I wrote myOtherMethod as static method. For testing, as I cannot mock static method calls
I ended up writing an instance method which calls static method.I tried mocking the static method versin of my code with PowerMock, but it is showing some errors while working with JSR-303 bean validators (please see here) and also I didn't find any working solution for integrating PowerMockRunner with SpringJunit4ClassRunner which is one of my case.
You can use PowerMock.expectNew(...) mocking functionality as described here.
Make sure you have annotated the test case class correctly. Many times folks miss out on the detail that you have to use the class invoking the constructor in the #PrepareForTest(ClassThatCreatesTheNewInstance.class) annotation.
If you still face error, please post your Test case code and stack trace.
I have an Spring-powered app and want to integrate groovy. Specifically, I have one abstract java class with a set of abstract method definitions and one repository inyected with autowired.
This class must be implemented by several final groovy external classes (one for each client).
At this moment, I am calling the Groovy class in java this way:
final Class parsedClass = groovyClassLoader.parseClass(groovyFile);
final GroovyObject groovyObject = (GroovyObject) parsedClass.newInstance();
final Object response = groovyObject.invokeMethod(methodName, methodParameters);
The problem is that I need to autowired the repository variable in each Groovy external class but currently are null.
How can I notify the Groovy class to get the inyected repository variable when I create it at runtime?
Thanks!
Edit
Y have solved it using the setProperty method from groovyObjectObject this way:
groovyObject.setProperty("myRepository", myRepositoryImpl);
The instance here is not created by spring, hence I don't think spring can automagically set the instance of repository in the groovyObject that you have.
However, if you can can autowire the repository into the class thats generating the groovyObject then you can manually inject the repo in the newInstance call.
parsedClass.newInstance(repository:your_autowired_repo_ref)
I have solved it using the setProperty method from groovyObjectObject this way:
groovyObject.setProperty("myRepository", myRepositoryImpl);
I am using PowerMock to try and mock a final class with static methods, but whenever my code calls MyClass.getInstance() it returns null
In my tests I have annotated the test class
#RunWith(PowerMockRunner.class)
#PrepareForTest(MyClass.class)
In my method to make the mock I do the following
suppressConstructor(MyClass.class);
PowerMock.mockStatic(MyClass.class);
mockClass = PowerMock.createMock(MyClass.class);
expect(MyClass.getInstance()).andReturn(mockClass);
Should PowerMock.createMock create an EasyMock class?
When I call this in my code (MyClass.getInstance()), it always returns null but if I step through the test class the variable mockClass gets instantiated.
It seems like you using the EasyMock way of mocking. Have you replayed the MyClass before calling the getInstance() method, e.g.
PowerMock.replay(MyClass.class);
?
From the PowerMock MockStatic documentation:
Use PowerMock.mockStatic(ClassThatContainsStaticMethod.class) to mock all methods of this class.
Use PowerMock.replay(ClassThatContainsStaticMethod.class) to change the class to replay mode.
Use PowerMock.verify(ClassThatContainsStaticMethod.class) to change the class to verify mode.
I have a very simple test case that is using Mockito and Spring Test framework. When I do
when(pcUserService.read("1")).thenReturn(pcUser);
I get this exception.
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.
at com.project.cleaner.controller.test.PcUserControllerTest.shouldGetPcUser(PcUserControllerTest.java:93)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
I have tried with different methods but keep on getting this error message. I am using Spring 3.1.0.RELEASE with Mockito. Please share and guide me in the right direction.
You need to create a MOCK of pcUserService first, and then use that mock.
PcUserService mock = org.mockito.Mockito.mock(PcUserService.class);
when(mock.read("1")).thenReturn(pcUser);
In case others hit this issue....
It could also be the case that the method you are trying to mock out,pcUserService.read, is declared as a final method. From what I've noticed this appears to cause issues with Mockito.
If you use Kotlin, you should know that methods are final by default. So write open fun instead of fun. Thanks to #djkelly99 for a tip.
Another solution to this issue might be that in case of a test class that is using PowerMockRunner, you might have to add the class that you are mocking to the list, in #PrepareForTest annotation.
For instance -
#PrepareForTest({ PcUserService.class })
In my case it was solved by injecting #MockBean.
For ex.
#MockBean
StateRepository mockStateRepository;
There's another possible reason for such error - sometimes IDE prefers to statically import Mockito.when() from another package:
import static io.codearte.catchexception.shade.mockito.Mockito.when;
vs
import static org.mockito.Mockito.when; //should normally use this one
The thing is 'when' from io.codearte package is compliant with org.mockito.Mockito.any() on compilation level, but fails during runtime with that exact same error message.
I had the same issue, the method that I was trying to mock it was a final method. I removed the modifier and it worked fine.
For the help of others who stuck with the same problem;
The method you are trying to mock , pcUserService.read, is declared as a final method. Static methods appears to cause issues with Mockito.
If you get this exception when using MockedStatic or Mockito.mockStatic, it can also mean that you are mixing matchers and literals in the call to the static method.
Try changing any mixes like YourClass.staticMethod(any(), "literal") to YourClass.staticMethod(any(), eq("literal"))
Basically You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.
For example:
PowerMockito.mockStatic(TestClass.class);
when(TestClass.getString()).thenReturn("HelloWorld!");
Note: you have to add #PrepareForTest({ TestClass.class }) to your unit test class.
If you use KOIN, include in the gradle's dependencies:
dependencies {
...
testImplementation "org.koin:koin-test:2.0.0"
}
I faced similar issue when mocking static method of anotherClass called inside testing a method of someClass. In that case, we need to add #PrepareForTest({anotherClass.class, someClass.class}) both the class having the static method and caller class.
When I got this exception, I was using #InjectMocks on the class that I needed to have the #Mock objects injected into (via constructor injection).
AFter much searching, I finally stumbled across this article:
https://mkyong.com/spring-boot/mockito-when-requires-an-argument-which-has-to-be-a-method-call-on-a-mock/
The key part to take away from it is (from the article):
When Mockito see this #InjectMocks, it doesn’t mock it, it just
creates a normal instance, so the when() will be failed.
So this make this exception message I was getting
when() requires an argument which has to be 'a method call on a mock'.
make sense now; you aren't using when on an actual mock but an actual instance.
The link also provides the solution to the problem:
To solve it, annotate #Spy to mock it partially.
On top of #InjectMocks, put #Spy.
As a side note, if you try to make it a Mock by putting #Mock on top of #InjectMocks, you will get exception:
org.mockito.exceptions.base.MockitoException: This combination of
annotations is not permitted on a single field: #Mock and #InjectMocks
Using #Spy on top of #InjectMocks solved the problem for me.
I faced same issue and it was because the mocked object is defined as #Beanand the overriden #Bean in the test was not working because of a missing spring property value
#Bean
#Primary
public JwtTokenUtil jwtTokenUtil() {
return Mockito.mock(JwtTokenUtil.class);
}
#Autowired
private JwtTokenUtil jwtTokenUtil;
when(jwtTokenUtil.validateToken(jwtToken)).thenReturn(true);
Fix
spring.main.allow-bean-definition-overriding=true in application-test.properties
if anything above answers your case, then check that you did missed the #Test annotation for your test method.
#Test
public void my_test_method(){
}
just quoting, as this was my case. just missed the annotation.