How to set up profile in spring boot to mock external api for development

225 Views Asked by At

I'm trying to set up my spring boot application so that when I run:

mvn spring-boot:run

and then go to localhost:9099/api/resources, the code accesses the actual endpoint. Then, if I run

mvn spring-boot:run -Pmock

and go to localhost:9099/api/resources, the code returns a mocked list of resources.

Right now, if I exclude the -Pmock argument, I can access the actual endpoint just fine, but if I include the -Pmock argument, I get a 404. Can anyone see what I am doing wrong? Here is what I have implemented:

pom.xml

...
    <profiles>
        <profile>
            <id>macos-m1</id>
            <activation>
                <os>
                    <family>mac</family>
                    <arch>aarch64</arch>
                </os>
            </activation>
            <dependencies>
                <dependency>
                    // mac m1 specific dependency - needed on dev machine only
                </dependency>
            </dependencies>
        </profile>
        <profile>
            <id>mock</id>
            <properties>
                <spring.profiles.active>mock</spring.profiles.active>
            </properties>
        </profile> -->
    </profiles>
...

ResourceController.java

@RestController
@Profile("!mock")
public final class ResourceController {

    @GetMapping("/api/resources")
    public ResponseEntity<List<Resource>> getAll() {
        List<Resource> payload = // call service to get all resources
        return ResponseEntity
            .status(HttpStatus.OK)
            .contentType(MediaType.APPLICATION_JSON)
            .body(payload);
    }
}

ResourceControllerMock.java

@RestController
@Profile("mock")
public final class ResourceController {

    @GetMapping("/api/resources")
    public ResponseEntity<List<Resource>> getAll() {
        List<Resource> payload = List.of(new Resource(x,y,z));
        return ResponseEntity
            .status(HttpStatus.OK)
            .contentType(MediaType.APPLICATION_JSON)
            .body(payload);
    }
}

1

There are 1 best solutions below

0
Gyan-Lucifer On BEST ANSWER

You are using the command wrong to run a specific profile.

Use the below command and it should work fine

mvn spring-boot:run -Dspring-boot.run.profiles=mock

Also you don't need to write a mock profile section in the pom.xml file, if you use the above command.

Reference: https://docs.spring.io/spring-boot/docs/2.0.1.RELEASE/maven-plugin/examples/run-profiles.html