What are JUnit @Before and @Test [closed]

感情迁移 提交于 2019-12-17 19:27:09

问题


What is the use of a Junit @Before and @Test annotations in java? How can I use them with netbeans?


回答1:


Can you be more precise? Do you need to understand what are @Before and @Test annotation?

@Test annotation is an annotation (since JUnit 4) that indicates the attached method is an unit test. That allows you to use any method name to have a test. For example:

@Test
public void doSomeTestOnAMethod() {
  // Your test goes here.
  ...
}

The @Before annotation indicates that the attached method will be run before any test in the class. It is mainly used to setup some objects needed by your tests:

(edited to add imports) :

import static org.junit.Assert.*; // Allows you to use directly assert methods, such as assertTrue(...), assertNull(...)

import org.junit.Test; // for @Test
import org.junit.Before; // for @Before

public class MyTest {

    private AnyObject anyObject;

    @Before
    public void initObjects() {
        anyObject = new AnyObject();
    }

    @Test
    public void aTestUsingAnyObject() {
        // Here, anyObject is not null...
        assertNotNull(anyObject);
        ...
    }

}



回答2:


  1. If I understood you correctly, you want to know, what the annotation @Before means. The annotation marks a method as to be executed before each test will be executed. There you can implement the old setup() procedure.

  2. The @Test annotation marks the following method as a JUnit test. The testrunner will identify every method annotated with @Test and executes it. Example:

    import org.junit.*;
    
    public class IntroductionTests {
        @Test
        public void testSum() {
          Assert.assertEquals(8, 6 + 2);
        }
    }
    
  3. How can i use it with Netbeans? In Netbeans, a testrunner for JUnit tests is included. You can choose it in your Execute Dialog.



来源:https://stackoverflow.com/questions/531371/what-are-junit-before-and-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!