Interview Questions

How To Write a JUnit Test Method?

JUnit Questions and Answers


(Continued from previous question...)

How To Write a JUnit Test Method?

This interview question is to check if you know the basic rules about writing a JUnit test method:

  • You need to mark the method as a JUnit test method with the JUnit annotation: @org.junit.Test.
  • A JUnit test method must be a "public" method. This allows the runner class to access this method.
  • A JUnit test method must be a "void" method. The runner class does not check any return values.
  • A JUnit test should perform one JUnit assertion - calling an org.junit.Assert.assertXXX() method.

Here is a simple JUnit test method:

import org.junit.*; 
// by FYICenter.com
...
    @Test public void testHello() {
        String message = "Hello World!";
        Assert.assertEquals(12, message.length());
    }

(Continued on next question...)

Other Interview Questions