-2

I have this doubt about JUnit logic.

I have implemented this simple method:

@Test
public void testBasic() {
    System.out.println("testBasic() START");

    assert(true);

    System.out.println("testBasic() END");

}

And, as expected, it is green because the assert() condition is setted to true.

Then I change it using:

assert(false);

And running the test it is green again also if the condition is false.

Reading the documentation I know that I also have the assertTrue() to test if a condition is true or false so I can use it.

But then: what is the exact purpose of the simple assert() method? When have I to use it and how is used?

BalusC
  • 1,040,783
  • 362
  • 3,548
  • 3,513
AndreaNobili
  • 38,251
  • 94
  • 277
  • 514
  • See also http://stackoverflow.com/questions/10039079/unit-test-assert-not-work and http://stackoverflow.com/questions/2966347/assert-vs-junit-assertions – Tunaki Nov 14 '16 at 10:27

2 Answers2

2

assert is a Java keyword which refers to Java assertions and not a reference to assertTrue/False/Equals...() methods from JUnit. Here is doc for assertions : http://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html

To perform JUnit assertions, import the suitable class : org.junit.Assert and do :

import org.junit.Assert;
import org.junit.Test;

public class YourTestClass{
  @Test
  public void testBasic() {
    System.out.println("testBasic() START");

    Assert.assertTrue(true); // pass
    Assert.assertFalse(true); // fail

    System.out.println("testBasic() END");

  }
}
davidxxx
  • 115,998
  • 20
  • 192
  • 199
0

You're using Java assertions there, not JUnit's.

Java assertions are disabled by default. You need to enable them using -ea commandline option:

java -ea MyClass
Jiri Tousek
  • 11,964
  • 5
  • 27
  • 41
  • mmm what do you mean? Can you explain it better? – AndreaNobili Nov 14 '16 at 10:20
  • Unless you explicitly turn them on, the runtime will ignore the assertion (and not even evaluate the expression inside). Source: http://www.oracle.com/us/technologies/java/assertions-139853.html – Jiri Tousek Nov 14 '16 at 10:23
  • Ah, I see the reason of your confusion now. See davidxxx's post. You're using Java assertions while you think you're using JUnit's assertions. – Jiri Tousek Nov 14 '16 at 10:25