Programmer Khan
Programmer Khan

Reputation: 45

Couldn't Inject Service class in grails unit test- Test Fails

I am executing a simple test, but the test fails because couldn't inject service bean into test class. below is my test class

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

my test fails with following error

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

Upvotes: 1

Views: 341

Answers (1)

Igor
Igor

Reputation: 33993

Assuming you are using a version before 2 (and JUnit instead of Spock), you need to manually add the service:

class QuoteServiceTests extends GrailsUnitTestCase {
    def quoteService 

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

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

If you are using Grails 2 or later, then you need an annotation:

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

Upvotes: 3

Related Questions