【问题标题】:Unit test fails单元测试失败
【发布时间】:2016-01-19 17:03:35
【问题描述】:

我是 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

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

【问题讨论】:

  • 就这些了吗?没有其他测试,项目中没有交易?
  • 类Bservice包含更多方法,但我没有附上它们

标签: unit-testing grails groovy spock


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    @TestFor(BService)
    class BServiceSpec extends Specification {
    
        def setup() {
            User u = new User(1)
            u.save()
        }
    
        def cleanup() {
        }
    
        def "test something"(){
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2020-02-14
      • 2014-04-13
      • 2012-06-01
      相关资源
      最近更新 更多