Reputation: 45
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
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