Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JUnit - Framework Extension


May 15, 2021 jUnit


Table of contents


JUnit - Framework Extension

Here's the JUnit extension

  • Cactus
  • JWebUnit
  • XMLUnit
  • MockObject

Cactus

Cactus is a simple framework for testing server-side Java code (Servlets, EJBs, Tag Libs, Filters). C actus is designed to reduce the cost of writing test samples for server-side code. I t uses JUnit and scales on it. Cactus implements the in-container policy, which means that testing can be performed inside the container.

The Cactus system consists of the following components:

  • The Cactus Framework is at the heart of Cactus. It is the engine that provides the API to write Cactus test code.
  • Cactus Integration Module (Cactus Integration Module) is the front end and framework that is available using Cactus Framework (Ant scripts, Eclipse plugin, Maven plugin).

This is a sample code that uses cactus.

import org.apache.cactus.*;
import junit.framework.*;

public class TestSampleServlet extends ServletTestCase {
   @Test
   public void testServlet() {
      // Initialize class to test
      SampleServlet servlet = new SampleServlet();

      // Set a variable in session as the doSomething()
      // method that we are testing 
      session.setAttribute("name", "value");

      // Call the method to test, passing an 
      // HttpServletRequest object (for example)
      String result = servlet.doSomething(request);

      // Perform verification that test was successful
      assertEquals("something", result);
      assertEquals("otherValue", session.getAttribute("otherName"));
   }
}

JWebUnit

JWebUnit is a Java-based test framework for web applications. It wraps existing frameworks such as HtmlUnit and Selenium in a unified, simple test interface that allows you to quickly test the correctness of your web application.

JWebUnit provides a high-level Java API for web applications that handle assertions that combine a series of validation program correctnesses. This includes the verification of form content and other typical business characteristics of web applications through links, form filling and submission.

This simple navigation method and ready-to-use assertions allow you to establish more quick tests instead of just using JUnit and HtmlUnit. Also, if you want to switch from HtmlUnit to other plug-ins, such as Selenium (which will be available soon), you don't have to rewrite your sample code.

Here's the sample code.

import junit.framework.TestCase;
import net.sourceforge.jwebunit.WebTester;

public class ExampleWebTestCase extends TestCase {
   private WebTester tester;

   public ExampleWebTestCase(String name) {
        super(name);
        tester = new WebTester();
   }
   //set base url
   public void setUp() throws Exception {
       getTestContext().setBaseUrl("http://myserver:8080/myapp");
   }
   // test base info
   @Test
   public void testInfoPage() {
       beginAt("/info.html");
   }
}

XMLUnit

XMLUnit provides a single JUnit extension class, XMLTestCase, and some support classes that allow assertions:

  • Compare the differences between two XML files (by using Diff and DetailedDiff classes)
  • Validation of an XML file (by using the Validator class)
  • Transform the results of an XML file using XSLT (by using the Transform class)
  • Evaluation of an XML file XPath expression (by implementing the XpathEngine interface)
  • A separate node after an XML file for DOM Traversal (by using the NodeTest class)

Let's say we have two XML files that we want to compare and assert their same, and we can write a simple test class like this:

import org.custommonkey.xmlunit.XMLTestCase;

public class MyXMLTestCase extends XMLTestCase {

   // this test method compare two pieces of the XML
   @Test
   public void testForXMLEquality() throws Exception {
      String myControlXML = "<msg><uuid>0x00435A8C</uuid></msg>";
      String myTestXML = "<msg><localId>2376</localId></msg>";
      assertXMLEqual("Comparing test xml to control xml",
      myControlXML, myTestXML);
   }
}

MockObject

In a unit test, a virtual object can simulate the behavior of complex, real (non-virtual) objects, so it is useful when a real object is unrealistic or impossible to include in a unit test.

The general programming style when testing with virtual objects includes:

  • Create an instance of a virtual object
  • Set the state and description in the virtual object
  • The domain code is called as an argument in conjunction with the virtual object
  • Verify consistency in virtual objects

The following is an example of MockObject using Jmock.

import org.jmock.Mockery;
import org.jmock.Expectations;

class PubTest extends TestCase {
   Mockery context = new Mockery();
   public void testSubReceivesMessage() {
      // set up
      final Sub sub = context.mock(Sub.class);

      Pub pub = new Pub();
      pub.add(sub);

      final String message = "message";

      // expectations
      context.checking(new Expectations() {
         oneOf (sub).receive(message);
      });

      // execute
      pub.publish(message);

      // verify
      context.assertIsSatisfied();
   }
}