2

When trying to make a spek test (new thing for us), we get an error while trying to verify the invocations on the mock. The error is:

'm3CustomerService' can not be accessed in this context. java.lang.AssertionError: 'm3CustomerService' can not be accessed in this context.

I have not been able to figure out why this error keeps happening. Does anyone have any idea.

package com.crv.decustomeradapter.m3

import com.crv.decustomeradapter.m3.client.M3Client
import org.assertj.core.api.Assertions.assertThat
import org.mockito.BDDMockito.then
import org.mockito.Mockito.mock
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe

object M3CustomerServiceSpekTest : Spek({
    val m3ClientMock by memoized { mock(M3Client::class.java) }
    val m3LocationEligibilityCheckServiceMock by memoized { mock(M3LocationEligibilityCheckService::class.java) }
    val m3CustomerEligibilityCheckServiceMock by memoized { mock(M3CustomerEligibilityCheckService::class.java) }

    describe("Calling the mock") {
        it("makes it return empty list") {
            assertThat(m3ClientMock.unfilteredCustomersFromM3).isEmpty();
        }
    }

    describe("Initiating the service ") {
        val m3CustomerService by memoized {
            M3CustomerService(m3CustomerEligibilityCheckServiceMock, m3LocationEligibilityCheckServiceMock,
                    m3ClientMock)
        }
        describe("and calling it with no return values for the mocks") {
            val m3Customers = m3CustomerService.processM3CustomersFromM3()
            it("makes it return an empty list") {
                assertThat(m3Customers).isEmpty()
            }
            it("calls the m3ClientMock") {
                //This test gives the error
                then(m3ClientMock).should().unfilteredCustomersFromM3
            }
        }
    }
})

Update: When using memoized to get the list the call to the m3CustomerService is never done, so the test fails.

jelmew
  • 543
  • 1
  • 7
  • 15
  • You are using memoized wrong, have a look at https://www.spekframework.org/core-concepts/. tldr; You are getting this error because you are using a scoped value during the discovery phase (describe block is invoked during this phase) which is wrong. – raniejade Jan 17 '20 at 04:45

1 Answers1

2

your m3CustomerService is declared as by memoized

which means Spek will create a new instance before each test.

so you can't use it as a normal val inside describe(...)

please move this line into it("makes it return an empty list"):

val m3Customers = m3CustomerService.processM3CustomersFromM3()
Li Ying
  • 2,261
  • 27
  • 17