单元测试失败

时间:2016-01-19 17:03:36

标签: unit-testing grails groovy spock

我是Grails的新手,我想使用Spock为服务编写单元测试。但是我有以下问题。

  import grails.transaction.Transactional

    @Transactional
    class BService {

        boolean createB(){
            return true
        }
    ...
    }

对于本课程,我写了以下测试:

class BServiceTest extends Specification {

    def "test createB"(){
        given:
        def service = new BService()

        when:
        def boolean temp
        temp = service.createB()

        then:
        temp == true
    }
}

我在运行此测试时遇到的错误如下:

java.lang.IllegalStateException: No transactionManager was specified. Using @Transactional or @Rollback requires a valid configured transaction manager. If you are running in a unit test ensure the test has been properly configured and that you run the test suite not an individual test method.

and it shows in GrailsTransactionTemplate.groovy:60

如果有人能给我一个暗示,我真的很感激。

2 个答案:

答案 0 :(得分:1)

在单元测试中添加@TestFor(BService)注释,并使用它自动提供的服务实例。有关测试的详细信息,请参阅http://grails.github.io/grails-doc/3.0.x/guide/testing.html

答案 1 :(得分:0)

感谢ataylor的回复。但是我犯了一个错误,所以我现在正在回答我自己的问题。

首先,名称转换是错误的。当我在grails中创建服务时,会自动为此设置单元测试,因此在这种情况下我会:

@TestFor(BService)
class BServiceSpec extends Specification {

    def setup() {
        User u = new User(1)
        u.save()
    }

    def cleanup() {
    }

    def "test something"(){
    }
}

在这种情况下,当我编写单元测试时,它会运行。 我以前的测试是一个功能测试,我无法从域中传递对象,所以我遇到了事务管理器的错误。