2

I have recently started out with Spring and am unsure about how to approach this issue. I have a Spring boot program which makes calls to remote REST APIs. For example an AddressService class with getAddress(String user) method, which makes a HTTP call and returns a JSON response. I would like to set up Spring profiles for development purposes local, dev, uat, prod.

When the program is running with the local profile, I would like to "mock" these external API calls with an expected JSON response, so I can just test logic, but when it is run in any of the other profiles I would like to make the actual calls. How can I go about doing this? From what I read, there's many ways people approach this, using WireMock, RestTemplate, Mockito etc. I'm confused about which is the way to go.

Any advice would be greatly appreciated. Thanks.

Boa
  • 321
  • 3
  • 11

2 Answers2

1

WireMock,Mockit is for unittest, to mock the real request. Example here: How do I mock a REST template exchange?

When you need a running implementation with a mock, i think the easiest way is that you have a interface

public interface AdressAdapter {
    public List<Adress> getAddress(String name);
}

And two different implementations depending on the profile.

@Profile("local")
public class DummyAdress implements AdressAdapter{
    @Override
    public List<Adress> getAddress(String name) {
        //Mock here something
        return null;
    }
}

! means NOT locale profile in this case.

@Profile("!local")
public class RealAdress implements AdressAdapter{
    @Override
    public List<Adress> getAddress(String name) {
        //Make Restcall
        return null;
    }
}
pL4Gu33
  • 2,045
  • 16
  • 38
  • but how would you mock a call to a downstream API in your code? I am not talking about doing it in test, but in the code? – d.b Sep 01 '22 at 20:59
0

What you could do is use different application.properties files depending on your profile. That way, you just change the url to a mock server for your local profile.

So what you have to do is :

  1. Create another application.properties in your resources folder named : application-local.properties.
  2. Change the url of the desired service.
  3. Start your application with the VM option -Dspring.profiles.active=local.

Here is a link that describe well what you want to achieve.

For your mock server, you could use Wiremock, Mountebank, Postman,... that can be start separately and mock specific endpoints to return what you want.

GabLeg
  • 352
  • 4
  • 14