简体   繁体   中英

Spock test is failing on NullPointerException

I am woking on a small grails application and started to use spock as a test framework.

The test is extremely simple at this point:

    @TestFor(TokenService)
class TokenServiceSpec extends Specification {

    TokenService tokenService = new TokenService()

    def setup() {
    }

    def cleanup() {
    }

    def "test generateToken"() {
        expect: 
        tokenService.generateToken(5).length() == 5
    }
}

Where generateToken is an existing public method in TokenService .

When I execute the test I am getting:

Failure:  test generateToken(com.iibs.security.TokenServiceSpec)
|  java.lang.NullPointerException
    at com.iibs.security.TokenServiceSpec.test generateToken(TokenServiceSpec.groovy:22)

When I debug it, I can verify that tokenService is instantiated properly. What could be a reason for this failure?

Thanks for any advice.

As you are writing a Unit Test Case, you need not to create the TokenService object using :-

TokenService tokenService = new TokenService()

Already an implicit service object is present there, which you can make use of like :-

    @TestFor(TokenService)
    class TokenServiceSpec extends Specification {

def setup() {
}

def cleanup() {
}

def "test generateToken"() {
    expect: 
    service.generateToken(5).length() == 5
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM