Marsellus Wallace
Marsellus Wallace

Reputation: 18611

JUnit Testing - assertTrue not throwing Exception

This is my first JUnit test and I don't understand why is not throwing an AssertionError, what am I doing wrong??

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.JUnitCore;

public class MyFirstJUnitTest {

    public static void main(String[] args) {
        JUnitCore.runClasses(MyFirstJUnitTest.class);
    }

    @Test
    public void simpleAdd() {
        int a = 5;
        int b = 3;

        int c = a + b; //8

        Assert.assertTrue(c == 7);
    }
}

Upvotes: 1

Views: 2650

Answers (3)

socha23
socha23

Reputation: 10239

AssertionError is in this case caught by test runner.

Normally, AssertionErrors are thrown by failing assertions made with assert keyword. This:

public static void main(String[] args) {
    int a = 5;
    int b = 3;

    int c = a + b; //8

    assert c == 7;
}

throws an AssertionError as expected, when running with assertion checks enabled.

Upvotes: 1

Garrett Hall
Garrett Hall

Reputation: 30042

To run JUnit from the command line you need to call the main method.

JUnitCore.main("MyFirstJUnitTest");

You are not supposed to use JUnitCore unless you need to access the result in a programmatic way, for instance if you are writing a JUnit plugin for an IDE:

JUnitCore.runClasses(MyFirstJUnitTest.class).getFailures();

JUnitCore catches any exceptions and stores them in the Result, which is a class that your JUnit plugin will read.

Upvotes: 2

dwalldorf
dwalldorf

Reputation: 1379

Assertions are not for throwing exceptions but for checking if your condition is correct. So this will show you, that something went wrong (in your JUnit-view in your IDE) but not throw any exceptions.

Upvotes: -1

Related Questions