I want to test the following example code:
public class Example {
...
public void doStuff() {
...
Lift lift = new Lift();
lift.call(5);
...
}
...
}
How can I 'intercept' lift.call(5)?
Generally I would use when(lift.call(anyInt()).thenReturn(...), but I have no reference to the Lift object.
You can't do it with mockito alone. The cleanest solution is to refactor your code so you can have access to it. However if that's not an option then "power mockito" is what you want. Grab "powermock-api-mockito"+"powermock-module-junit4" and then something like this will do the trick:
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(Example.class)
public class ExampleTest {
private Example testSubject;
#Mock
private Lift lift;
#Test
public void testDoStuff() throws Exception {
testSubject.doStuff();
verify(lift).call(5);
}
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
PowerMockito.whenNew(Lift.class).withNoArguments().thenReturn(lift);
testSubject = new Example();
}
}
Can you modify the Example class? If yes, the simplest way would be to extract the Lift dependency and provide it via constructor. Like this:
public class Example {
private final Lift lift;
public Example(Lift lift) {
this.lift = lift;
}
public void doStuff() {
this.lift.call(5);
}
}
Then you can stub lift as you want since now you have access to the instance.
Related
Why do I get a NullPointerExeption for testManuscript when trying to run my test?
This is my Manuscript.java:
package org.lhoffjann;
public class Manuscript {
private String msID;
private String path;
public void setMSid(String msID){
this.msID = msID;
}
public String getMSid() {
return this.msID;
}
}
This is my ManuscriptTest.java:
package org.lhoffjann;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ManuscriptTest {
private static Manuscript testManuscript;
#Before
public void setUp(){
testManuscript = new Manuscript();
}
#Test
public void testGetMSid() {
testManuscript.setMSid("1234");
assertTrue("1234" == testManuscript.getMSid());
}
}
You have imported #Test from JUnit 5, while you're using #Before from JUnit 4, that combination doesn't work. You need to choose which JUnit version you want to use, 4 or 5, and then consistently import classes from that JUnit version. I would recommend using JUnit 5, and removing all JUnit 4 dependencies from your classpath, or at least configure your IDE to not suggest those imports.
For this specific case, replace #Before (org.junit.Before) with #BeforeEach (org.junit.jupiter.api.BeforeEach).
In the example as shown, you don't even need this setUp method, as each test-execution gets its own instance of the test class. You can use:
private Manuscript testManuscript = new Manuscript();
That is, remove static, initialize the field directly, and remove the setUp method.
Even if you continue to use the setUp method, I recommend removing the static, so testManuscript is an instance field, like it is actually used.
You have mixed Junit4 with Junit5. You should use only one version.
Junit4 or
package org.lhoffjann;
import org.junit.Before;
import org.junit.Test;
import org.junit.Assert;
public class ManuscriptTest {
private static Manuscript testManuscript;
#Before
public void setUp(){
testManuscript = new Manuscript();
}
#Test
public void testGetMSid() {
testManuscript.setMSid("1234");
Assert.assertEquals("1234",testManuscript.getMSid());
}
or
Junit5
package org.lhoffjann;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class ManuscriptTest {
private static Manuscript testManuscript;
#BeforeEach
public void setUp() {
testManuscript = new Manuscript();
}
#Test
void testGetMSid() {
testManuscript.setMSid("1234");
Assertions.assertEquals("1234", testManuscript.getMSid());
}
}
I cannot mock a method defined as default in an interface. Can anyone help me here?
The interface has default method providing a logger.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public interface Loggable {
default Logger logger() {
return LoggerFactory.getLogger(this.getClass());
}
}
It is used this way:
public class AppShowOff implements Loggable{
public void doMagic() {
logger().debug("It works");
System.out.println("Works");
}
}
now I would like to write a test proving that debug method has been called.
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.mockito.Mockito;
import org.slf4j.Logger;
public class AppShowOffTest {
#Test
public void doMagic() {
Logger loggerMock = mock(Logger.class);
Loggable loggableMock = mock(Loggable.class); // <- not needed, but I also tried this way
// mocks done
AppShowOff app = new AppShowOff();
AppShowOff appSpy = Mockito.spy(new AppShowOff());
when(loggableMock.logger()).thenReturn(loggerMock);
when(appSpy.logger()).thenReturn(loggerMock);
app.doMagic();
verify(loggerMock, times(1)).debug(any());
}
}
as you can see I have tried to mock the default method in two ways:
when(loggableMock.logger()).thenReturn(loggerMock);
when(appSpy.logger()).thenReturn(loggerMock);
but it does not work. The result is:
Wanted but not invoked: logger.debug();
-> at so.AppShowOffTest.doMagic(AppShowOffTest.java:29) Actually, there were zero interactions with this mock.
Here:
AppShowOff app = new AppShowOff();
AppShowOff appSpy = Mockito.spy(new AppShowOff());
That first app ... is never used, besides to call your method under test doMagic().
The simple answer: drop app completely, and invoke appSpy.doMagic().
How can I mock nested static methods using PowerMockito?
The following is a very simple example on how I want to use it.
Class:
public class SomeClass {
public static String someMethodA(){
//some very important codes here
return someMethodB();
}
private static String someMethodB(){
return someMethodC();
}
private static String someMethodC(){
return "Some Text";
}
}
Already tried the following but did not work:
PowerMockito.mockStatic(SomeClass.class);
PowerMockito.stub(PowerMockito.method(SomeClass.class, "someMethodB")).toReturn("Some Other Text");
I wanted to run someMethodA() as is, which is why I want to stub someMethodB() instead. Is there anyway I can do this? Hoping that there is a way without having to modify the access modifiers because the codes I am working with are legacy codes.
You can spy the private static methods.
Tested in JUnit4
import static org.junit.Assert.assertEquals;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(SomeClass.class)
public class SomeClassTest {
#Test
public void test() throws Exception {
spy(SomeClass.class);
when(SomeClass.class, "someMethodB").thenReturn("Some Other Text");
assertEquals("Some Other Text", SomeClass.someMethodA());
}
}
I have a final class as below
public class firstclass{
private String firstmethod(){
return new secondclass("params").somemethod();
}
}
public final class secondclass{
secondclass(String params){
//some code
}
public String somemethod(){
// some code
return somevariable";
}
}
I have to here test first class so I have mocked this as below
secondclass classMock = PowerMockito.mock(secondclass .class);
PowerMockito.whenNew(secondclass .class).withAnyArguments().thenReturn(classMock);
Mockito.doReturn("test").when(classMock).somemethod();
But it is not mocking as I expected can anyone help me?
The method firstclass.firstmethod() is private method. So try to test this method through public method in which it is getting called.
You can mock SecondClass and its final method using #RunWith(PowerMockRunner.class) and #PrepareForTest(SecondClass.class) annotations.
Please see below the working code:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(SecondClass.class)
public class FirstClassTest{
#Before
public void init() {
}
#After
public void clear() {
}
#Test
public void testfirstmethod() throws Exception{
SecondClass classMock = PowerMockito.mock(SecondClass.class);
PowerMockito.whenNew(SecondClass.class).withAnyArguments().thenReturn(classMock);
Mockito.doReturn("test").when(classMock).somemethod();
new FirstClass().firstmethod();
}
}
Libraries used:
MyClass.java:
package test;
public final class MyClass {
public MyClass() { }
public Package returnPackage() {
return MyClass.class.getPackage();
}
}
TestClass.java:
package test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.powermock.api.mockito.PowerMockito.*;
#RunWith(PowerMockRunner.class)
#PrepareForTest(MyClass.class)
public class TestClass {
#Test
public void test() throws Exception {
System.out.println(new MyClass().returnPackage());
mockStatic(MyClass.class);
System.out.println(new MyClass().returnPackage());
}
}
However, this results in:
package test
null
Any MyClass.class method call returns null after PowerMockito.mockStatic(Class). Is there any way to prevent this?
Workaround: I can use the EasyMock-API to set up the static mocks without PowerMockito.mockStatic().