Search code examples
clienthttpclientmicronautmicronaut-restmicronaut-test

How to Mock a Declarative Client in Micronaut?


I have Class in which I call a method from a declarative client. But for my test I don't want it to call the actual URL. Instead I want to Mock it. How can I do that as it is not a class but an Interface annotated with @Client?

Example code:- here. Please check section 4.3


Solution

  • In your test you can replace the http client bean with a mock. Please find a Spock snippet below.

    // replace the client with a mock
    @MockBean(YourClientInterface)
    YourClientInterface yourClientInterface() {
        return Mock(YourClientInterface)
    }
    
    // inject the mock in order to configure responses when it gets called
    @Inject
    YourClientInterface client
    
    

    Now you can write tests and your code will run against the mock instead of the actual http client.