Home > front end >  NullPointerException after mock object in test
NullPointerException after mock object in test

Time:08-30

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()

CodePudding user response:

Did you put the annotation? This error means that the object is not in the context of the Spring.

CodePudding user response:

You need to mock a Spring component, so inside your test class inject this component mock as:

public testClass{
    
    @Mock
    private VertexGetTaxResilience vertexGetTaxResilience;
    
    //your test methods...
}

So now you can call methods from this mock

  • Related