无法在grails单元测试中注入服务类 - 测试失败

时间:2014-02-18 17:18:03

标签: unit-testing grails

我正在执行一个简单的测试,但测试失败,因为无法将服务bean注入测试类。下面是我的考试类

class QuoteServiceTests extends GrailsUnitTestCase {

      def quoteService
    void testStaticQuote() {
        def staticQuote = quoteService.getStaticQuote()

        assertEquals("Messi", staticQuote.author)
        assertEquals("Watch me today against Man-City", staticQuote.content)
    }
}

我的测试失败并出现以下错误

 Cannot invoke method getStaticQuote() on null object
 java.lang.NullPointerException: Cannot invoke method getStaticQuote() on null object
 at qotd.QuoteServiceTests.testStaticQuote(QuoteServiceTests.groovy:9)

1 个答案:

答案 0 :(得分:3)

假设您使用的是2之前的版本(以及JUnit而不是Spock),您需要手动添加服务:

class QuoteServiceTests extends GrailsUnitTestCase {
    def quoteService 

    void setUp() {
        quoteService = new QuoteService()
    }

    void testStaticQuote() {
        def staticQuote = quoteService.getStaticQuote()
        // ...

如果您使用的是Grails 2或更高版本,则需要注释:

@TestFor(QuoteService) // Allows you to call the QuoteService via 'service'
class QuoteServiceTests {
    void testStaticQuote() {
        def staticQuote = service.getStaticQuote()
        // ...