Java 什么是 JUnit @Before 和 @Test

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/531371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:53:45  来源:igfitidea点击:

What are JUnit @Before and @Test

javajunitannotations

提问by

What is the use of a Junit @Beforeand @Testannotations in java? How can I use them with netbeans?

java中Junit@Before@Test注解有什么用?我如何将它们与 netbeans 一起使用?

回答by guerda

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

  2. The @Testannotation marks the following method as a JUnit test. The testrunner will identify every method annotated with @Testand 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.

  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 测试的测试运行程序。您可以在执行对话框中选择它。

回答by Romain Linsolas

Can you be more precise? Do you need to understand what are @Beforeand @Testannotation?

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

@Testannotation 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:

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

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

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

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

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

}