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
What are JUnit @Before and @Test
提问by
What is the use of a Junit @Before
and @Test
annotations in java? How can I use them with netbeans?
java中Junit@Before
和@Test
注解有什么用?我如何将它们与 netbeans 一起使用?
回答by guerda
If I understood you correctly, you want to know, what the annotation
@Before
means. The annotation marks a method as to be executed before eachtest will be executed. There you can implement the oldsetup()
procedure.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); } }
How can i use it with Netbeans?
In Netbeans, a testrunner for JUnit tests is included. You can choose it in your Execute Dialog.
如果我理解正确,您想知道注释的
@Before
含义。注释将方法标记为在执行每个测试之前要执行的方法。在那里您可以实施旧setup()
程序。该
@Test
注释标记以下方法作为JUnit测试。testrunner 将识别每个注释的方法@Test
并执行它。例子:import org.junit.*; public class IntroductionTests { @Test public void testSum() { Assert.assertEquals(8, 6 + 2); } }
How can i use it with Netbeans?
在 Netbeans 中,包含了一个用于 JUnit 测试的测试运行程序。您可以在执行对话框中选择它。
回答by Romain Linsolas
Can you be more precise?
Do you need to understand what are @Before
and @Test
annotation?
你能更准确吗?你需要了解什么是@Before
和@Test
注解吗?
@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
annotation 是一个注解(自 JUnit 4 起),表明附加的方法是一个单元测试。这允许您使用任何方法名称进行测试。例如:
@Test
public void doSomeTestOnAMethod() {
// Your test goes here.
...
}
The @Before
annotation 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);
...
}
}