JUnit 4 @Test Annotation实际上做了什么

时间:2015-04-02 17:48:48

标签: testing junit junit4

@Test实际上做了什么?没有它我有一些测试,它们运行良好。

我的班级以

开头
public class TransactionTest extends InstrumentationTestCase {

测试运行于:

public void testGetDate() throws Exception {

@Test
public void testGetDate() throws Exception {

编辑:有人指出我可能正在使用JUnit 3测试,但我认为我正在使用JUnit 4:

enter image description here

4 个答案:

答案 0 :(得分:7)

@Test 
public void method()

@Test => annotation identifies a method as a test method.
@Test(expected = Exception.class) => Fails if the method does not throw the named exception.
@Test(timeout=100)  =>  Fails if the method takes longer than 100 milliseconds.

@Before 
public void method() =>This method is executed before each test. It is used to prepare the test environment (e.g., read input data, initialize the class).

@After 
public void method() => This method is executed after each test. It is used to cleanup the test environment (e.g., delete temporary data, restore defaults). It can also save memory by cleaning up expensive memory structures.

@BeforeClass 
public static void method() => This method is executed once, before the start of all tests. It is used to perform time intensive activities, for example, to connect to a database. Methods marked with this annotation need to be defined as static to work with JUnit.

@AfterClass 
public static void method() =>  This method is executed once, after all tests have been finished. It is used to perform clean-up activities, for example, to disconnect from a database. Methods annotated with this annotation need to be defined as static to work with JUnit.

@Ignore => Ignores the test method. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included.

答案 1 :(得分:1)

它将方法识别为测试方法。 JUnit调用该类,然后调用带注释的方法。

如果发生异常,则测试失败;但是,您可以指定应发生异常。如果没有,测试将失败(测试异常 - 进行反向测试):

@Test(expected = Exception.class) - 如果方法没有抛出命名异常,则失败。

您还可以设置时间限制,如果功能未按指定的时间结束,则会失败:

@Test(timeout = 500) - 如果方法花费的时间超过500毫秒,则失败。

答案 2 :(得分:1)

在JUnit 4中,@Test注释用于告诉JUnit特定方法是一个测试。相比之下,在JUnit 3中,如果每个方法的名称都以test开头,并且其类扩展为TestCase,则每个方法都是一个测试。

我假设InstrumentationTestCase扩展junit.framework.TestCase。这意味着您在JUnit 3测试中使用了JUnit 4注释。在这种情况下,运行测试的工具(您的IDE或构建工具,如Ant或Maven)决定是否识别@Test注释。您可以通过将testGetDate()重命名为不以test开头的内容来验证这一点,例如shouldReturnDate()。如果您的工具仍然运行17次测试,那么您知道它在JUnit 3测试中支持JUnit 4注释。如果它运行了16个测试而不是你知道@Test注释只是一个什么都不做的flashbang。

JUnit 4仍提供JUnit 3(junit.framework包)的类。这意味着您可以对JUnit 4使用JUnit 3样式测试。

答案 3 :(得分:0)

在JUnit中注释用于根据测试执行的观点赋予方法或类的含义。一旦你使用方法使用@Test注释,那么该方法不再是普通方法,它是一个测试用例,它将由IDE执行为测试用例,JUnit将根据测试用例传递或基于邮件的方式显示其执行结果你的断言。

如果您作为初学者开始使用JUnit,请在此处查看简单的Junit教程 - http://qaautomated.blogspot.in/p/junit.html

相关问题