-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,082,665
  • 372
  • 3,610
  • 3,555
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 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
  • 125,838
  • 23
  • 214
  • 215
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
  • 12,211
  • 5
  • 29
  • 43
  • 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