Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Mock A Specific URL Path?

I am using okhttp to mock my http responses during my tests.

//Create a mock server
mockWebServer.start(8080)
mockWebServer.enqueue(MockResponse().setBody("").setResponseCode(HttpURLConnection.HTTP_OK))

However, this responds to every path as OK.

How do I mock a specific url instead of all of them?

like image 291
opticyclic Avatar asked Oct 20 '25 13:10

opticyclic


1 Answers

Using Dispatcher

        Dispatcher dispatcher = new Dispatcher() {
            @Override
            public MockResponse dispatch(RecordedRequest request) {
                switch (request.getPath()) {
                    case "/get":
                        return new MockResponse().setResponseCode(200).setBody("test");
                }
                return new MockResponse().setResponseCode(404);
            }
        };

        mockBackEnd.setDispatcher(dispatcher);

Above can be written inside your test method. You can have a bunch of URLs conditions there.

The mockwebserver can be started once like:

   public static MockWebServer mockBackEnd;

    @BeforeAll
    static void setUp() throws IOException {
        mockBackEnd = new MockWebServer();
        mockBackEnd.start();
    }


    @AfterAll
    static void tearDown() throws IOException {
        mockBackEnd.shutdown();
    }

Use @DynamicPropertySource to change any property with mockserver host/port.

like image 164
Dhananjay Avatar answered Oct 23 '25 08:10

Dhananjay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!