thisisdude
thisisdude

Reputation: 576

is there a way to mock internal service calls while writing Component testcases

I'm writing my component level test-cases for my repository. My API calls internally a third party API which I need to mock. I don't have direct access to that API neither I can directly call it, it needs to be called from within the API calls. I need to mock in order to run the component test-cases successfully. I tried wiremock but looks like it is not working and my API is still calling the 3rd party URL. Is there any way to solve this problem. Here is my code -

Annotation at class level

 @Rule
    public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().port(8888));

    WireMockServer wm;

Started server

 @BeforeEach
    void setUp() {
        wm = new WireMockServer(WireMockConfiguration.options().port(8888));
        wm.start();
    }

In the tests.

wireMockServer.start();
        wm.stubFor(get("https://someurl")
                .willReturn(badRequest()
                        .withHeader("Content-Type", "application/json")
                        .withBody("<response>SUCCESS</response>")));


MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders
                .post(apiContextPath)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .content(gson.toJson(offerParams)))
                .andExpect(status().isOk()).andReturn();

wireMockServer.stop();

Sorry can't paste whole code due to security reasons.

Upvotes: 0

Views: 620

Answers (1)

Tom
Tom

Reputation: 4149

It looks like you're trying to use the JUnit 4 rule with JUnit 5, meaning the WireMock server won't be started.

Try the JUnit Jupiter extension instead: https://wiremock.org/docs/junit-jupiter/

Upvotes: 1

Related Questions