Cyntech
Cyntech

Reputation: 5572

Spring Boot - Mock a POST REST request to an external API

I have a Spring-Boot 1.5.21 application that serves as a REST gateway between an Angular UI and an external API that provides the data (long story - acts as auth between UI and datasource). A request comes to the Spring-Boot application, it calls the data source API with the request payload.

I am new to Unit Testing for Spring-Boot and am trying to write a test for the POST REST method in the Gateway application that creates a new record (create). I've read a couple of tutorials and other websites detailing how to unit test Spring-Boot APIs but nothing that helps me in my situation.

I want to:

Controller Method:

@PostMapping(value = "/" + Constants.API_CHANGE_REQUEST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public String submitChangeRequest(@RequestBody ChangeRequestWrapper changeRequestWrapper) {
    logger.info("API Request: Posting Change Request: " + changeRequestWrapper.toString());
    return restService.makeApiPost(sharedDataService.buildApiUrlPath(Constants.API_CHANGE_REQUEST), changeRequestWrapper);
}

AppConfig:

@PropertySource({"classpath:application.properties"})
@Configuration
public class AppConfig {

    @Resource
    private Environment env;

    @Bean
    public RestTemplate restTemplate() {
        RestTemplateBuilder builder = new RestTemplateBuilder();
        return builder
                .setConnectTimeout(Constants.API_TIMEOUT_CONNECT)
                .setReadTimeout(Constants.API_TIMEOUT_READ)
                .basicAuthorization(env.getProperty("bpm.user"), env.getProperty("bpm.password"))
                .build();
    }
}

RestServiceImpl:

@Service
public class RestServiceImpl implements RestService {

    private static final Logger logger = LoggerFactory.getLogger(RestServiceImpl.class);

    @Autowired
    private RestTemplate myRestTemplate;

    @Value("${bpm.url}")
    private String restUrl;

    public String getApiUri() {
        return restUrl;
    }

    public String makeApiCall(String payload) /*throws GradeAdminException */{
        logger.info("Implementing API call.");
        logger.debug("userApi: " + payload);
        return myRestTemplate.getForObject(payload, String.class);
    }

    public String makeApiPost(String endpoint, Object object) {
        logger.info("Implementing API post submission");
        logger.debug("userApi endpoint: " + endpoint);
        return myRestTemplate.postForObject(endpoint, object, String.class);
    }
}

SharedDataServiceImpl:

@Service
public class SharedDataServiceImpl implements SharedDataService {

    @Autowired
    private RestService restService;

    @Override
    public String buildApiUrlPath(String request) {
        return buildApiUrlPath(request, null);
    }

    @Override
    public String buildApiUrlPath(String request, Object parameter) {
        String path;
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(restService.getApiUri());

        if (parameter != null) {
            builder = builder.path(getApiPath(request) + "/{object}");
            UriComponents buildPath = builder.buildAndExpand(parameter);
            path = buildPath.toUriString();
        } else {
            builder = builder.path(getApiPath(request));
            path = builder.build().toUriString();
        }

        return path;
    }
}

What I've done for the GET methods:

@RunWith(SpringRunner.class)
@WebMvcTest(ClientDataRequestController.class)
@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigWebContextLoader.class)
public class ClientDataRequestControllerTest {

    @Autowired
    private MockMvc mvc;

    @Before
    public void setUp() {

    }

    @Test
    public void test_no_endpoint() throws Exception {
        this.mvc.perform(get("/")).andExpect(status().isNotFound()).andReturn();
    }

    @Test
    public void test_controller_no_endpoint() throws Exception {
        this.mvc.perform(get("/api/")).andExpect(status().isOk()).andReturn();
    }

    @Test
    public void test_getStudent_valid_parameters() throws Exception {
        this.mvc.perform(get("/api/students/?pidm=272746")).andExpect(status().isOk()).andReturn();
    }
}

I would greatly appreciate some assistance with this.

Solution:

I've since found this SO answer that has solved my problem.

Upvotes: 2

Views: 8251

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36123

You could mock the RestServiceImpl. Add a dependency in your test and annotate it with MockBean:

@MockBean
private RemoteService remoteService;

Now you can go ahead and mock the methods:

import org.mockito.BDDMockito;


BDDMockito.given(this.remoteService.makeApiPost()).willReturn("whatever is needed for your test");

Upvotes: 2

Related Questions