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.
CodePudding user response:
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.
@AutoCleanup
will call theclose()
method on the field's object. Here, the field is an array, which doesn't have aclose()
method.- You declare
tokenInfos
to be@Shared
, but you only initialize it in the firstsetup()
call, which will happen too late for the first entry in thewhere
block. So, either initialze the field directly, or move the assignment tosetupSpec
.
@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