JUnit 4 @Test 注释实际上做了什么

What does the JUnit 4 @Test Annotation actually do

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

我的 class 以

开头
public class TransactionTest extends InstrumentationTestCase {

测试 运行s 有:

public void testGetDate() throws Exception {

@Test
public void testGetDate() throws Exception {

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

它将方法标识为测试方法。 JUnit 调用 class,然后调用带注释的方法。

如果出现异常,则测试失败;但是,您可以指定应该发生异常。如果没有,测试将失败(测试异常 - 某种逆向测试):

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

您还可以设置时间限制,如果函数没有在分配的时间内完成,它将失败:

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

@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.

在 JUnit 4 中,@Test 注释用于告诉 JUnit 特定方法是一个测试。相反,在 JUnit 3 中,每个方法都是一个测试,如果它的名称以 test 开头并且它的 class 扩展 TestCase.

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

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

在 JUnit 中,根据测试执行的观点,注释用于为方法或 class 赋予意义。一旦您将 @Test 注释与方法一起使用,那么该方法不再是普通方法,它是一个测试用例,它将作为测试用例由 IDE 执行,JUnit 将根据通过的测试用例显示其执行结果或根据您的断言发送邮件。

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