javablogspot

Just another WordPress.com weblog

Posts Tagged ‘Junit’

unrooted tests of junit 3.4 runner

Posted by damuchinni on March 14, 2009

When using Eclipse 3.3 or above, By the default, the JUnit 4 test runner will be used. In the olden days, with Eclipse 3.0 and JUnit 3.8, user could select a single test method in the Outline view and run just that method. However, when try to do that in Eclipse 3.3 or above. It’s test runner runs all the tests in the class. The results are shown in a tree, and the tests I didn’t ask to be run are all under a node called “Unrooted Tests [Runner: JUnit 4]”.

The problem is because,your class extends TestCase (in Junit 3.8 favior,not use the 4.0 annotation), but eclispe will Using the JUnit 4 runner by the default which causes that unrooted test. if you want to use the old Junit 3.8 runner for your 3.8 testcase. you have change the run configurations manually.

the old Junit 3.8 runner will show up after that:

Posted in IDEs, Junit | Tagged: , , | 1 Comment »

A Simple Servlet for Running JUnit in Glassfish

Posted by damuchinni on February 15, 2009

When teaching unit testing in the context of a simple EJB3.1 application, I was looking for an easy way of testing managed beans and session beans inside Glassfish. Of course, one can test out-of-container or use an embedded container (but I didn’t quite figure out how to do that with Glassfish v3—I’d appreciate hints), or a mock container (but that seemed to require a bit of setup).

I hit upon a scheme that I had not seen elsewhere: put the unit tests in the container and trigger them with a servlet that reports the outcomes. Advantages:

  1. There is very little setup to learn
  2. It is easy to run the tests from a browser
  3. The tests run in the exact same environment as your app
  4. No need to wait for container startup with every test. (This could also be a disadvantage because the database isn’t in a pristine state at the beginning of each test.)

Here is how to do it.

Add the JUnit 4 JAR to WEB-INF/lib.

Add the following servlet to your WAR file:

package myapp.servlets;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.internal.JUnitSystem;
import org.junit.runner.JUnitCore;

public class TestServlet extends HttpServlet {
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
       String className = request.getParameter("class");
       response.setContentType("text/plain");
       OutputStream out = response.getOutputStream();
       final PrintStream pout = new PrintStream(out);
       new JUnitCore().runMain(new JUnitSystem() {
         public PrintStream out() { return pout; }
         public void exit(int arg0) {}
       }, className);
       out.close();
   }

   protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
       doGet(request, response);
   }
}

Add the following entries to web.xml:

    <servlet>
        <servlet-name>TestServlet</servlet-name>
        <servlet-class>myapp.servlets.TestServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>

Write your JUnit test case in the usual way. For example, here is a test for a session bean:

package myapp.session;

import static org.junit.Assert.assertEquals;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.junit.Before;
import org.junit.Test;

import myapp.entity.Person;

public class UserSBTest {
   private UserSB userSB;

   @Before public void init() throws NamingException {
      InitialContext context = new InitialContext();
      userSB = (UserSB) context.lookup("java:global/MyApp/UserSB");
   }

   @Test public void testAddUser() {
      Person p = new Person();
      p.setFirstName("Fred");
      p.setUsername("fred");
      userSB.save(p);
      Person q = userSB.find("fred");
      assertEquals(p.getFirstName(), q.getFirstName());
      userSB.removePerson("fred");
   }

unit-test-in-browser.png

Proverbial exercise to the reader: Add a green bar when the test cases pass.

}

Unfortunately, you can’t just have the container inject the session bean.

   @EJB private UserSB userSB; // Doesn't work when JUnit loads the class

When JUnit loads the class, it doesn’t deal with EJB annotations.

Then point your browser to http://localhost:8080/MyApp/test?class=myapp.session.UserSBTest

Posted in IDEs | Tagged: | Leave a Comment »

A Simple Servlet for Running JUnit in Glassfish

Posted by damuchinni on February 15, 2009

When teaching unit testing in the context of a simple EJB3.1 application, I was looking for an easy way of testing managed beans and session beans inside Glassfish. Of course, one can test out-of-container or use an embedded container (but I didn’t quite figure out how to do that with Glassfish v3—I’d appreciate hints), or a mock container (but that seemed to require a bit of setup).

I hit upon a scheme that I had not seen elsewhere: put the unit tests in the container and trigger them with a servlet that reports the outcomes. Advantages:

  1. There is very little setup to learn
  2. It is easy to run the tests from a browser
  3. The tests run in the exact same environment as your app
  4. No need to wait for container startup with every test. (This could also be a disadvantage because the database isn’t in a pristine state at the beginning of each test.)

Here is how to do it.

Add the JUnit 4 JAR to WEB-INF/lib.

Add the following servlet to your WAR file:

package myapp.servlets;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.internal.JUnitSystem;
import org.junit.runner.JUnitCore;

public class TestServlet extends HttpServlet {
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
       String className = request.getParameter("class");
       response.setContentType("text/plain");
       OutputStream out = response.getOutputStream();
       final PrintStream pout = new PrintStream(out);
       new JUnitCore().runMain(new JUnitSystem() {
         public PrintStream out() { return pout; }
         public void exit(int arg0) {}
       }, className);
       out.close();
   }

   protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
       doGet(request, response);
   }
}

Add the following entries to web.xml:

    <servlet>
        <servlet-name>TestServlet</servlet-name>
        <servlet-class>myapp.servlets.TestServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>

Write your JUnit test case in the usual way. For example, here is a test for a session bean:

package myapp.session;

import static org.junit.Assert.assertEquals;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.junit.Before;
import org.junit.Test;

import myapp.entity.Person;

public class UserSBTest {
   private UserSB userSB;

   @Before public void init() throws NamingException {
      InitialContext context = new InitialContext();
      userSB = (UserSB) context.lookup("java:global/MyApp/UserSB");
   }

   @Test public void testAddUser() {
      Person p = new Person();
      p.setFirstName("Fred");
      p.setUsername("fred");
      userSB.save(p);
      Person q = userSB.find("fred");
      assertEquals(p.getFirstName(), q.getFirstName());
      userSB.removePerson("fred");
   }
}

Unfortunately, you can’t just have the container inject the session bean.

   @EJB private UserSB userSB; // Doesn't work when JUnit loads the class

When JUnit loads the class, it doesn’t deal with EJB annotations.

Then point your browser to http://localhost:8080/MyApp/test?class=myapp.session.UserSBTest

unit-test-in-browser.png

Proverbial exercise to the reader: Add a green bar when the test cases pass.

Posted in Java | Tagged: | Leave a Comment »

JUnit 3 & JUnit 4: Oil & water

Posted by damuchinni on February 15, 2009

Version 4 of the popular JUnit test framework has been available for use for quite some time (In fact, it is up to version 4.5). However, many projects have a wealth of JUnit 3-style tests and developers may choose to continue using it. If, on the other hand, you decide to dip your toes in JUnit 4 waters, make it a complete immersion. Don’t try to mix and match.

As you may be aware, couple of the touted “benefits” of JUnit 4 are the obviation of extending the TestCase class and the identification of test and lifecycle methods (setUp and tearDown) using Java 5 annotations. For example, the following is a valid JUnit 4-style test case (minus the necessary imports):

public class BusinessLogicTests {
@Before
public void do_this_before_every_test() {
// set up logic goes here
}

@After
public void clean_up_after_a_test() {
// teardown logic goes here
}

@Test
public void addition() {
assertEquals("Invalid addition", 2, 1+1);
}
}

Observe how

  • The class does not extend TestCase
  • The “setup” and “tearDown” methods are identified by annotations
  • The test method does not require a “test” prefix and is also annotated

I’ll let you be the judge of whether this is an improvement on JUnit 3. What I want to alert you to are the perils of subconciously mixing JUnit-3 and JUnit-4 style programming. Consider the following test case:

public class BusinessLogicTests extends TestCase {
@Before
public void do_this_before_every_test() {
// set up logic goes here
}

@After
public void clean_up_after_a_test() {
// teardown logic goes here
}

@Test
public void testAddition() {
assertEquals("Invalid addition", 2, 1+1);
}

@Test
public void subtraction() {
assertEquals("Invalid subtraction", 1, 1-1);
}
}

This will result in a green-bar even though there is an error in the test of subtraction. Can you guess why?

It was that pesky little extends TestCase that I added from force of habit. The flips the switch to JUnit-3, which knows nothing about annotations, ignores my setup and teardown methods and looks for methods prefixed by test. It completely ignores the method named subtraction!

And of course, conversely, the following is just a plain old Java class that won’t be acknowledged by either JUnit-3 or JUnit-4.

public class BusinessLogicTests {
public void testAddition() {
assertEquals("Invalid addition", 2, 1+1);
}
}

Final word of advice, if you are using Struts Test Case, you have no choice but to write JUnit-3 style tests since the parent class of the framework (MockStrutsTestCase) extends Junit-3’s TestCase

.

Posted in IDEs | Tagged: | Leave a Comment »