Interview Questions

What Happens If a JUnit Test Method Is Declared to Return "String"?

JUnit Questions and Answers

(Continued from previous question...)

What Happens If a JUnit Test Method Is Declared to Return "String"?

If a JUnit test method is declared to return "String", the compilation will pass ok. But the execution will fail. This is decause JUnit requires that all test methods must be declared to return "void". For example:


import org.junit.Test;
import static org.junit.Assert.*;
// by
public class HelloTestNonVoid {
    @Test public String testHello() {
        String message = "Hello World!";
        assertEquals(12, message.length());
        return message;

javac -cp junit-4.4.jar

java -cp .;junit-4.4.jar org.junit.runner.JUnitCore 

JUnit version 4.4
Time: 0
There was 1 failure:
1) initializationError0(HelloTestNonVoid)
java.lang.Exception: Method testHello should be void
        at org.junit.internal.runners.MethodValidator.validateTe
        at org.junit.internal.runners.MethodValidator.validateIn
        at org.junit.internal.runners.MethodValidator.validateMe
        at org.junit.internal.runners.JUnit4ClassRunner.validate
        at org.junit.internal.runners.JUnit4ClassRunner.<init>(J
        at sun.reflect.NativeConstructorAccessorImpl.newInstance
        at sun.reflect.NativeConstructorAccessorImpl.newInstance
        at sun.reflect.DelegatingConstructorAccessorImpl.newInst
        at java.lang.reflect.Constructor.newInstance(Constructor
        at org.junit.internal.requests.ClassRequest.buildRunner(
        at org.junit.internal.requests.ClassRequest.getRunner(Cl
        at org.junit.internal.requests.ClassesRequest.getRunner(
        at org.junit.runner.JUnitCore.runMain(
        at org.junit.runner.JUnitCore.main(

Tests run: 1,  Failures: 1

(Continued on next question...)

Other Interview Questions