Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GroovyTestCase does not support @BeforeClass and @AfterClass

I created a JUnit4 TestCase for my Shard class, but when I try to extend GroovyTestCase it does not run my @BeforeClass and @AfterClass methods.

Here is my code

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"
        }
    }
}

When I change the class definition to

class ShardUnitTests extends GroovyTestCase{

the beforeClassSetUp() and afterClassTearDown() methods are not called. Is there some other syntax I should be using for these methods, or is it just not compatible with GroovyTestCase?

like image 329
Jonathan Woo Avatar asked Apr 18 '14 16:04

Jonathan Woo


1 Answers

I use the @RunWith annotation to run these tests using JUnit 4 style to execute the before/after class methods. Example:

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
    }
}
like image 168
Andy Avatar answered Sep 25 '22 16:09

Andy