JUNIT4 identifies the test method by annotating it. The main annotations currently supported are:
@BeforeClassThe global is executed only once, and is the first one to run
@BeforeRun before the test method runs
@TestTest method
@AfterAllows after the test method has been run
@AfterClassThe global only executes once and is the last one to run
@IgnoreIgnore this method
Here's an example:
- Import Org.junit.After;
- Import Org.junit.AfterClass;
- Import Org.junit.Assert;
- Import Org.junit.Before;
- Import Org.junit.BeforeClass;
- Import Org.junit.Ignore;
- Import Org.junit.Test;
- Public class Junit4testcase {
- @BeforeClass
- public static void Setupbeforeclass () {
- System.out.println ("Set Up Before class");
- }
- @Before
- public void SetUp () throws Exception {
- System.out.println ("Set up");
- }
- @Test
- public void Testmathpow () {
- System.out.println ("Test Math.pow");
- Assert.assertequals (4.0, Math.pow (2.0, 2.0), 0.0);
- }
- @Test
- public void Testmathmin () {
- System.out.println ("Test math.min");
- Assert.assertequals (2.0, Math.min (2.0, 4.0), 0.0);
- }
- //Expect this method to throw a NullPointerException exception
- @Test (expected = nullpointerexception. Class)
- public void TestException () {
- System.out.println ("Test exception");
- Object obj = null;
- Obj.tostring ();
- }
- //Ignore this test method
- @Ignore
- @Test
- public void Testmathmax () {
- Assert.fail ("not implemented");
- }
- //Use "assumptions" to ignore test methods
- @Test
- public void Testassume () {
- System.out.println ("Test assume");
- //When the assumption fails, it stops running, but this does not mean that the test method failed.
- Assume.assumetrue (false);
- Assert.fail ("not implemented");
- }
- @After
- public void TearDown () throws Exception {
- System.out.println ("Tear down");
- }
- @AfterClass
- public static void Teardownafterclass () {
- System.out.println ("Tear down after Class");
- }
- }
JUNIT3 's package is junit.framework , and JUNIT4 is org.junit .
After you execute this use case, the console outputs
Wrote set up before class
Set up
Test Math.pow
Tear down
Set up
Test Math.min
Tear down
Set up
Test exception
Tear down
Set up
Test assume
Tear down
Tear down after class
As you can see, the order of execution is-- @BeforeClass @Before @Test @After @Before @Test @After @AfterClass ----------. @Ignorewill be ignored.
Java Unit Test Comment execution order