Dear Folks,
In this blog I'll tell how to write the JUnit Test Cases to test your application's methods.
Suppose we have a class which manipulates with the date and time. See the sample class:
package com.test.util;
import java.util.Calendar;
public class DateManipulation {
public static String getDate() {
Calendar c = new Calendar ();
return c.getTime().toString();
}
}
public static String getDate() {
Calendar c = new Calendar ();
return c.getTime().toString();
}
}
* Create a directory src_test parallel to src directory in your project.
* Now create the same package in it as your original src file.
* Create a class file TestDateManipulation in it.
package com.test.util;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertTrue;
@RunWith(JMock.class)
public class TestDateManipulation {
private Mockery context = new JUnit4Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
@Test
public void getDate(){
String returnValue = DateManipulation.getDate();
assert returnValue != null;
assertTrue(!returnValue.equals(""));
}
}
* Use @Test annotation to show this is a JUnit Test method which is called to test the existing method.
* Mockery is mandatory to create otherwise it will give "no Mockery found in test class" error.
* assertTrue will validate the output of the program by evaluating the condition written in it. You can learn more about them in
http://www.junit.org/apidocs/junit/framework/TestCase.html link.
Hope this will help you in writing test cases for your application. :)
--
Best regards,
