Let's say I have the following class:
class MyClass {
public MyClass(){
}
public void hello() {
System.out.println("hello");
}
}
and I want to test 'hello' method:
#Test
public void testHello() {
MyClass mc = new MyClass();
mc.hello();
}
Now, I want to spy System.out.println and make sure that this method was called with "hello" as argument. How do I do it?
System.out is actually an instance of PrintStream, so my approach would be to create a mock of this class and direct output to that using the System.setOut method:
PrintStream outMock = Mockito.mock(PrintStream.class);
System.setOut(outMock);
System.out.println("Hello");
Mockito.verify(outMock).println("Hello");
Remember to restore the previous PrintStream instance after the test, preferably in a finally clause.
Related
I have a method whose JUnit test case I have to write. It just calls the main processing method of the project and does nothing else. Also, the main processing method also has return type as void.
How shall I test such a "method1"?
public void method1() {
obj1.mainProcessingMethod():
}
Given a class:
public class A {
private Obj obj1;
public void method1() {
obj1.mainProcessingMethod();
}
public void setObj1(Obj obj1) {
this.obj1 = obj1;
}
}
In test for this class, the only thing to test would be verification whether method obj1.mainProcessingMethod() was invoked exactly once.
You can achieve this with Mockito.
import org.junit.Test;
import org.mockito.Mockito;
public class ATest {
private Obj obj1 = Mockito.mock(Obj.class);
private A a = new A();
#Test
public void testMethod1() {
a.setObj1(obj1);
a.method1();
Mockito.verify(obj1).mainProcessingMethod();
}
}
Here you create a mock object for class Obj, inject it into instance of A, and later use mock object to check which method invocations it recorded.
Inside the test you need to verify that the method mainProcessingMethod(): is called on the object obj1.
you can use something like
Mockito.verify(yourMockObject);
I have a two class's for testing regression test. We have in some case more than one test method in the class and in the methods we are usually using assertions. I want to know if there any method is available, to make use #Rule test method only the last method in the class. Here is my code:
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class JustOneClass extends ParentClass {
#Rule
public class GeneralRule articleHotspotRule = new class GeneralRule (this);
#Test
aMethod(){
Assert.assertTrue()
}
#Test
bMethod(){
Assert.assertTrue()
}
#Test
cMethod(){
Assert.assertTrue()
}
#Test
dMethod(){
if this assert is failed Assert.assertTrue()
}
}
We have a another class which extends TestWatcher
public class GeneralRule extends TestWatcher {
private ParentClass baseTest;
public GeneralRule (final GeneralRule generalRule) {
this.baseTest = generalRule;
}
#Override
protected void failed(final Throwable e, final Description description) {
baseTest.after();
}
}
in this case I want that baseTest.after() will be used only if assertion of dMedthod is failed.
Rather than using a rule to try and check for the failure, how about checking for the failure condition and then fail the test programatically? Certainly not as elegant or reusable as a rule but may satisfy your requirement.
#Test
public void dMethod() {
...
if(actual == false) { // check for failure scenario
after(); // call the after method
Assert.fail("hello failure"); // programatically fail the test
}
}
I’m using Mockito 1.9.5. How do I mock what is coming back from a protected method? I have this protected method …
protected JSONObject myMethod(final String param1, final String param2)
{
…
}
However, when I attempt to do this in JUnit:
final MyService mymock = Mockito.mock(MyService.class, Mockito.CALLS_REAL_METHODS);
final String pararm1 = “param1”;
Mockito.doReturn(myData).when(mymock).myMethod(param1, param2);
On the last line, I get a compilation error “The method ‘myMethod’ is not visible.” How do I use Mockito to mock protected methods? I’m open to upgrading my version if that’s the answer.
This is not an issue with Mockito, but with plain old java. From where you are calling the method, you don't have visibility. That is why it is a compile-time issue instead of a run-time issue.
A couple options:
declare your test in the same package as the mocked class
change the visibilty of the method if you can
create a local (inner) class that extends the mocked class, then mock this local class. Since the class would be local, you would have visibility to the method.
Responding to the request for a code sample of option 3 from John B's answer:
public class MyClass {
protected String protectedMethod() {
return "Can't touch this";
}
public String publicMethod() {
return protectedMethod();
}
}
#RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
class MyClassMock extends MyClass {
#Override
public String protectedMethod() {
return "You can see me now!";
}
}
#Mock
MyClassMock myClass = mock(MyClassMock.class);
#Test
public void myClassPublicMethodTest() {
when(myClass.publicMethod()).thenCallRealMethod();
when(myClass.protectedMethod()).thenReturn("jk!");
}
}
You can use Spring's ReflectionTestUtils to use your class as it is and without needing of change it just for tests or wrap it in another class.
public class MyService {
protected JSONObject myProtectedMethod(final String param1, final String param2) {
return new JSONObject();
}
public JSONObject myPublicMethod(final String param1) {
return new JSONObject();
}
}
And then in Test
#RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
#Mock
private MyService myService;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(myService.myPublicMethod(anyString())).thenReturn(mock(JSONObject.class));
when(ReflectionTestUtils.invokeMethod(myService, "myProtectedMethod", anyString(), anyString())).thenReturn(mock(JSONObject.class));
}
}
Something like following worked for me, using doReturn() and Junit5's ReflectionSupport.
[Note: I tested on Mockito 3.12.4]
ReflectionSupport.invokeMethod(
mymock.getClass()
// .getSuperclass() // Uncomment this, if the protected method defined in the parent class.
.getDeclaredMethod("myMethod", String.class, String.class),
doReturn(myData).when(mymock),
param1,
param2);
John B is right, this is because the method you're trying to test is protected, it's not a problem with Mockito.
Another option on top of the ones he has listed would be to use reflection to gain access to the method. This will allow you to avoid changing the method you are testing, and avoid changing the pattern you use to write tests, and where you store these tests. I've had to do this myself for some tests where I was not allowed to change the existing code base which included a large number of private methods that needed to be unit tested.
These links explain Reflection and how to use it very well, so I will link to them rather than copy:
What is reflection and whit is it useful
How to test a class that has private methods, fields, or inner classes
WhiteBox.invokeMethod() can be handy.
public class Test extend TargetClass{
#Override
protected Object method(...) {
return [ValueYouWant];
}
}
In Spring, you can set it high high-priority like this:
#TestConfiguration
public class Config {
#Profile({"..."})
#Bean("...")
#Primary // <------ high-priority
public TargetClass TargetClass(){
return new TargetClass() {
#Override
protected WPayResponse validate(...) {
return null;
}
};
}
}
It is the same to override the origin bean.
I am to mock a static function named toBeMockedFunction in Util class. This method is called from toBeUnitTested which is a public static void method. I want toBeMockedFunction to do nothing. I tried many approaches (snippet posted of such 2) of partial mock and stubbing and unable to succeed.
Please suggest what I am doing wrong.
public class Util {
// Some code
public static void toBeUnitTested(CustomObject cb, CustomObject1 cb1, List<CustomObject2> rows, boolean delete) {
// some code
toBeMockedFunction(cb, "test", "test");
}
public static CustomObject toBeMockedFunction(CustomObject cb, String str1) {
// some code
}
}
And below is my junit class
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Util.class})
public class UtilTest {
#Test
public void Test1() {
PowerMockito.spy(Util.class);
//mock toBeMocked function and make it do nothing
PowerMockito.when(PowerMockito.spy(Util.toBeMockedFunction((CustomObject)Mockito.anyObject(), Mockito.anyString()))).thenReturn(null);
Util.toBeUnitTested(cb, "test", "test");
}
}
Approach2
PowerMockito.mockStatic(Util.class);
PowerMockito.when(Util.toBeUnitTested((CustomObject)Mockito.anyObject(),Mockito.anyString())).thenCallRealMethod();
Util.toBeUnitTested(cb, "test", "test");
This is an example of how can do that:
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Util.class})
public class UtilTest {
#Test
public void Test1() {
PowerMockito.spy(Util.class);
PowerMockito.doReturn(null).when(Util.class, "toBeMockedFunction", Mockito.any(CustomObject.class), Mockito.anyString(), Mockito.anyString());
List<CustomObject2> customObject2List = new ArrayList<>();
customObject2List.add(new CustomObject2());
Util.toBeUnitTested(new CustomObject(), new CustomObject1(), customObject2List, true);
}
}
Please note that the code of your OP doesn't compile. Method toBeMockedFunction(CustomObject cb, String str1) receives only 2 parameters and you are calling with 3: toBeMockedFunction(cb, "test", "test");. As you could see, I've added the last one to the method signature.
Hope it helps
We're using #Before's all along the hierarchy to get some test data inserted into the database before tests execute. I want to commit all that data to the database just before the #Test starts running.
One way to do this would be to commit the data as the last step in this test class' #Before method. But we have hundreds of such classes, and don't want to go in and modify all of those.
I've played with ExternalResource #Rule and TestWatcher #Rule...but they don't afford a way to hook in after all the #Before's have happened.
I'm thinking I need to look at building a custom TestRunner to do this.
Is that the right track?
What you are looking for, seems inconsistent to me. Settind some data and committing them are very close operations and shouldn't belong to different places. On the contrary, I would rather put them into one function and call it with actual parameters set to values you want to insert. Or use SQL strings as actual parameters. And call this finction from #Before
If you are insisting, there is no problem to do it. Create descendant classes for your Junit classes:
package ...;
import org.junit.Before;
public class NewAndBetterYourTest1 extends YourTest1 {
#Override
#Before
public void setUp() {
super.setUp(); // this is where you are setting everything.
makeCommits();
}
}
Only don't forget to launch these new tests
While you can't do quite what you are asking without a custom Runner, you could ensure that all of the data created in the #Before methods is committed with a Rule:
public class LocalDatabase extends ExternalResource {
private DataSource dataSource;
#Override
protected void before() {
dataSource = createLocalDatabase();
}
#Override
protected void after() {
try {
destoyLocalDatabase(dataSource);
} finally {
dataSource = null;
}
}
public void run(Callback callback) {
if (dataSource == null) {
throw new IllegalStateException("No DataSource");
}
Collection con = null;
try {
con = ds.getConnection(DB_USERNAME, PASSWORD);
callback.execute(con);
con.commit();
} finally {
if (con != null) con.close();
}
}
You can have this as a Rule in your base class:
public DatabaseTest {
#Rule
public LocalDatabase final localDatabase = new LocalDatabase();
}
And could could use it in a #Before method in any subclass
public UserDaoTest extends DatabaseTest {
#Before
public void populateInitialData() {
localDatabase.run(new Callback() {
#Override
public void execute(Connection con) {
...
}
});
}
...
}