NullPointerException after mock object in test

Issue

I have a getDefaultRetryInstance which can be used to retry a call when have exception

@Component
class VertexGetTaxResilience(var retryRegistry: RetryRegistry) extends Serializable {
    private val logger = LoggerFactory.getLogger(this.getClass)
    val GET_VERTEX_TAX_RETRY_DEFAULT_NAME = "getVerTexTaxDefaultRetry"

    val defaultVertexRetryInstance = Retry.of(GET_VERTEX_TAX_RETRY_DEFAULT_NAME, retryRegistry.getConfiguration(GET_VERTEX_TAX_RETRY_DEFAULT_NAME).get())

    def getDefaultRetryInstance(): Retry = {
        // default retry instance configured in yaml
        logger.info("Retrieving default retry instance: {}", GET_VERTEX_TAX_RETRY_DEFAULT_NAME)
        defaultVertexRetryInstance
    }
}

I’m using this function.

val invoiceRequestResult = Decorators.ofSupplier {...}.withRetry(vertexGetTaxResilience.getDefaultRetryInstance())
            .get()

Here is how I do a mock for this retry object, but I got "java.lang.NullPointerException was thrown" above, how can I fix this?

 @Mock
 val vertexGetTaxResilience: VertexGetTaxResilience = null
 val retry = Retry.ofDefaults("getVerTexTaxDefaultRetry")
 //val vertexGetTaxResilienceMock = mock[VertexGetTaxResilience]
 doReturn(retry).when(vertexGetTaxResilienceMock).getDefaultRetryInstance()

Solution

I fix this by using reflection for object.

ReflectionTestUtils.setField

Answered By – Nick

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published