JUnit

JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development.

JUnit is a library packed in a jar file. Among other things it contains a tool (called test runner) to run your test files. It is not an automated testing tool: you still have to write your test files by hand. JUnit does give you some support so that you can write those test files more conveniently.

Suppose you have a class C that you want to test. We will write the tests in a new class; let’s call it Ctest. This Ctest is our test file. Actually, test class is a better name. We will typically group the tests in Ctest in a bunch of methods called test methods. You will see an example soon.

To actually test C we need to execute its test class Ctest. This is done by calling JUnit’s test runner tool; we pass the name Ctest to it. That’s all. JUnit will then execute Ctest for you.

JUnit will report how many of the test methods in Ctest succeed, and how many fail. The detail of each failure will be reported; this will be in the form of a print of Java’s stack trace leading to the location of the failure.

Download JUnit

If you don’t have JUnit yet, you need to download it (from JUnit site). To use it you just need the jar file. A full download also contains its documentation. Now locate where this jar file is; it is usually called:

junit-<version-number>.jar

To use JUnit you will need to add the full path to this jar to your class path.

Example

import org.junit.* ;
import static org.junit.Assert.* ;

public class SubscriptionTest {

   @Test
   public void test_returnEuro() {
      System.out.println(“Test if pricePerMonth returns Euro…”) ;
      Subscription S = new Subscription(200,2) ;
      assertTrue(S.pricePerMonth() == 1.0) ;
   }

   @Test
   public void test_roundUp() {
      System.out.println(“Test if pricePerMonth rounds up correctly…”) ;
      Subscription S = new Subscription(200,3) ;
      assertTrue(S.pricePerMonth() == 0.67) ;
   }
}

The marker @Test is called an annotation in Java. When we later execute JUnit’s test runner it needs to know which methods in your test class are test methods (e.g. you may have several helper methods in your test class). The @Test is used to mark that a method is a test method.

Compiling and executing your test

Next we want to execute the above test class (SubscriptionTest). I’ll show how to do this from a console. If you use an IDE the steps are a bit different.

Open a console. You first need to compile the test class, and then you can execute it. The commands are (in Windows):

prompt> javac -cp .;<full path to JUnit.jar> SubscriptionTest.java

prompt> java  -cp .;<full path to JUnit.jar> org.junit.runner.JUnitCore SubscriptionTest

StrutsTestCase for JUnit v2.1.4

 

StrutsTestCase for JUnit is an extension of the standard JUnit TestCase class that provides

facilities for testing code based on the Struts framework. StrutsTestCase provides both a

Mock Object approach and a Cactus approach to actually run the Struts ActionServlet, allowing

you to test your Struts code with or without a running servlet engine. Because StrutsTestCase

uses the ActionServlet controller to test your code, you can test not only the implementation

of your Action objects, but also your mappings, form beans, and forwards declarations. And

because StrutsTestCase already provides validation methods, it’s quick and easy to write unit

test cases.

 

StrutsTestCase is compliant with the Java Servlet 2.2, 2.3, and 2.4 specifications, and supports Struts 1.2/1.3, and Cactus 1.7 and JUnit 3.8.1.

Please note that StrutsTestCase is no longer backwards compatible with Struts 1.0. The last release compatible with Struts 1.0 is StrutsTestCase v2.0.
 Download link http://sourceforge.net/projects/strutstestcase/files/
Sample Test Case for Struts
public class TestLoginAction extends MockStrutsTestCase {

    public TestLoginAction(String testName) { super(testName); }

    public void testSuccessfulLogin() {
       setRequestPathInfo("/login");
       addRequestParameter("username","deryl");
       addRequestParameter("password","radar");
       actionPerform();
       verifyForward("success");
       assertEquals("deryl",(String) getSession().getAttribute("authentication"));
       verifyNoActionErrors();
    }
}
Class for which test case is shown above
public class LoginAction extends Action {

    public ActionForward perform(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
    {

        String username = ((LoginForm) form).getUsername();
        String password = ((LoginForm) form).getPassword();

        ActionErrors errors = new ActionErrors();

        if ((!username.equals("deryl")) || (!password.equals("radar")))
            errors.add("password",new ActionError("error.password.mismatch"));

        if (!errors.empty()) {
            saveErrors(request,errors);
            return mapping.findForward("login");
        }

        // store authentication info on the session
        HttpSession session = request.getSession();
        session.setAttribute("authentication", username);

        // Forward control to the specified success URI
        return mapping.findForward("success");

}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.