简体   繁体   中英

Java - Spock "where" block is not working

I am trying to write some test with where but it seems like the data mentioned in where block is not being passed, (I found the values to be null). Here is my unit test:

    def "method response should contain count as expected" () {
        given:
        SomeServiceImpl service = applicationContext.getBean(SomeServiceImpl.class)

        when:
        mockConnector.getResponse(userId) >> responseData
        service.setTokenConnector(mockConnector)
        ResponseData res = tokenService.getAllData(userId)
        def count = ((ListResponseMeta)(res.getMeta())).getCount()

        then:
        count == expected

        where:
        responseData | expected
        tokenInfos | 1
        null | 0
    }

The tokenInfos is initialized previously as an array of object with some values.

    @Shared
    @AutoCleanup
    Info[] tokenInfos = null

    def setup() {
        tokenInfos = getMockInfoBody()
        mockTokenConnector = Mock(SampleConnector.class)
    }

    private static Info[] getMockInfoBody() {
        Info infoDeactivated = new Info("123", "http://abc.xyz.com", "D")
        Info infoActive = new Info("234", "http://abc.xyz.com", "A")
        Info infoSuspended = new Info("235", "http://abc.xyz.com", "S")

        Info[] tokenInfos = new Info[3]
        tokenInfos[0] = infoDeactivated
        tokenInfos[1] = infoActive
        tokenInfos[2] = infoSuspended

        return tokenInfos
    }

I tried moving responseData within when block previously responseData was being used in given block. Please help here.

I'll try to answer, but as @krigaex pointed out, without a minimal, complete, and verifiable example it is hard to be sure.

There are multiple things that are wrong or have no effect.

  1. @AutoCleanup will call the close() method on the field's object. Here, the field is an array, which doesn't have a close() method.
  2. You declare tokenInfos to be @Shared , but you only initialize it in the first setup() call, which will happen too late for the first entry in the where block. So, either initialze the field directly, or move the assignment to setupSpec .
    @Shared
    Info[] tokenInfos = getMockInfoBody()
    // OR
    def setupSpec() {
        tokenInfos = getMockInfoBody()
    }

Currently, you were method basically looks like this


        where:
        responseData | expected
        null         | 1        // tokenInfos is still null as setup() didn't run yet
        null         | 0

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