GroovyTestCase不支持@BeforeClass和@AfterClass

时间:2014-04-18 16:04:29

标签: unit-testing groovy junit4

我为我的Shard类创建了一个JUnit4 TestCase,但是当我尝试扩展GroovyTestCase时,它不会运行我的@BeforeClass和@AfterClass方法。

这是我的代码

import groovy.sql.*
import org.junit.*

class ShardUnitTests {
    static def shard
    static def sql
    static def mysqlserver = "REDACTED"
    @BeforeClass
    static void beforeClassSetUp(){
        def db = [url:'jdbc:mysql://${mysqlserver}:3306/test', user:'root', password:'password', driver:'com.mysql.jdbc.Driver']
        sql = Sql.newInstance(db.url, db.user, db.password, db.driver)
        shard = new Shard(sql: sql)
    }
    @AfterClass
    static void afterClassTearDown(){
        sql.execute("DROP TABLE test")
        sql.close()
    }
    @Test
    //Test that createObjectTable creates a table with 2 columns
    void testCreateObjectTable(){
        shard.createObjectTable("test")
        sql.rows("SELECT * FROM test"){meta ->
            assert meta.getColumnName(1) == "id"
            assert meta.getColumnName(2) == "data"
        }
    }
}

当我将类定义更改为

class ShardUnitTests extends GroovyTestCase{

不调用beforeClassSetUp()和afterClassTearDown()方法。 我应该为这些方法使用其他语法,还是只是与GroovyTestCase不兼容?

1 个答案:

答案 0 :(得分:4)

我使用@RunWith注释来使用JUnit 4样式运行这些测试来执行前/后类方法。例如:

package org.apache

import org.apache.log4j.Logger
import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.junit.*

import org.junit.runner.RunWith
import org.junit.runners.JUnit4

import java.security.Security

@RunWith(JUnit4.class)
class SomeClassTest extends GroovyTestCase {
    private static final Logger logger = Logger.getLogger(SomeClassTest.class)

    private SomeClass someClass

    @BeforeClass
    static void setUpOnce() {
        // Do things once for the whole test suite

        logger.metaClass.methodMissing = { String name, args ->
            logger.info("[${name?.toUpperCase()}] ${(args as List).join(" ")}")
        }

        Security.addProvider(new BouncyCastleProvider())
    }

    @Before
    void setUp() {
        // Do things before every test case
        someClass = new SomeClass()
    }

    @After
    void tearDown() {
        // Do things after every test case
    }

    @AfterClass
    static void tearDownOnce() {
        // Do things once for the whole test suite
    }

    @Test
    void testShouldDoSomething() {
        // Arrange

        // Act
        int result = someClass.doSomething()

        // Assert
        assert result == 0
    }
}