什么是JUnit @Before和@Test

23 java junit annotations

在java中使用Junit @Before@Test注释有什么用?如何在netbeans中使用它们?

Rom*_*las 55

你能更准确吗?你需要了解什么是@Before@Test注释?

@Testannotation是一个注释(自JUnit 4开始),表示附加的方法是单元测试.这允许您使用任何方法名称进行测试.例如:

@Test
public void doSomeTestOnAMethod() {
  // Your test goes here.
  ...
}
Run Code Online (Sandbox Code Playgroud)

所述@Before注释指示所连接的方法将被运行之前在类中的任何测试.它主要用于设置测试所需的一些对象:

(编辑添加导入):

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);
        ...
    }

}
Run Code Online (Sandbox Code Playgroud)

  • @ziggy'@ Before'在课堂上的每个考试之前被调用.在静态方法上使用'@BeforeClass'只运行一次方法,例如.初始化测试上下文. (3认同)

gue*_*rda 22

  1. 如果我理解正确,你想知道,注释@Before意味着什么.注释标记了在执行每个测试之前执行的方法.在那里你可以实现旧的setup()程序.

  2. @Test注释标记以下方法作为JUnit测试.testrunner将识别每个注释的方法@Test并执行它.例:

    import org.junit.*;
    
    public class IntroductionTests {
        @Test
        public void testSum() {
          Assert.assertEquals(8, 6 + 2);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. How can i use it with Netbeans?在Netbeans中,包括JUnit测试的测试人员.您可以在执行对话框中选择它.