什么是JUnit @Before和@Test

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

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

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

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

@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); ... } } 
  1. 如果我理解正确,你想知道@Before的注释是什么意思。 注释标记了在执行每个测试之前执行的方法。 在那里,您可以实现旧的setup()过程。

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

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