美文网首页
JUnit SetUp / TearDown

JUnit SetUp / TearDown

作者: 萌妈码码 | 来源:发表于2018-08-21 10:58 被阅读0次

通常在执行测试用例之前,需要做一些设置,或者MOCK一些数据。可以在每个测试用例中都写一段这样的逻辑,但是更好的一种做法是覆写TestCasesetupteardown方法。如下:

public class JUnitTestCaseWOAnnotation extends TestCase {
    
    private AccountService accountService = new AccountService();
    private Account dummyAccount;
    
    //覆写该方法,做些准备工作
    @Override
    protected void setUp() throws Exception {
        System.out.println("Setting it up!");
        dummyAccount = accountService.getAccountDetails();
    }
    
    public void testDummyAccount() {
        System.out.println("Running: testDummyAccount");
        assertNotNull(dummyAccount.getAccountCode());
    }
    public void testDummyAccountTransactions() {
        System.out.println("Running: testDummyAccountTransactions");
        assertEquals(dummyAccount.getAccountTransactions().size(),3);
    }
    
        //覆写该方法,做些必要的清理工作
    @Override
    protected void tearDown() throws Exception {
        System.out.println("Running: tearDown");
        dummyAccount = null;
        assertNull(dummyAccount);
    }

}

另一种更推荐的做法是使用注解@Before@After

public class JUnitTestCaseWAnnotation {
    
    private AccountService accountService = new AccountService();
    private Account dummyAccount;
    
     // setup()
    @Before
    public void before() throws Exception {
        System.out.println("Setting it up!");
        dummyAccount = accountService.getAccountDetails();
    }
    
    @Test
    public void testDummyAccount() {
        System.out.println("Running: testDummyAccount");
        assertNotNull(dummyAccount.getAccountCode());
    }
    @Test
    public void testDummyAccountTransactions() {
        System.out.println("Running: testDummyAccountTransactions");
        assertEquals(dummyAccount.getAccountTransactions().size(),3);
    }

     // tearDown()
    @After
    public void after() throws Exception {
        System.out.println("Running: tearDown");
        dummyAccount = null;
        assertNull(dummyAccount);
    }

}

类似的注解还有@BeforeClass@AfterClass。比较如下:
@BeforeClass会在所有测试用例执行之前执行。且只会执行一次;
@Before会在每个测试用例执行之前都执行一次。
@AfterClass@After 的比较类似。
此外,

  1. @BeforeClass@AfterClass只能注释static方法。
  2. 无论@BeforeClass@Before是否执行成功,或有异常抛出,@AfterClass@After都会执行。

引用
JUnit SetUp / TearDown Example
Difference between @Before and @BeforeClass.

相关文章

网友评论

      本文标题:JUnit SetUp / TearDown

      本文链接:https://www.haomeiwen.com/subject/bgediftx.html