I'm quite new to spring boot and got a basic microservice put together (It accepts a Yelp url and scrapes the images for that restaurant). I thought it would be a good time to write some unit tests, but one thing I'm having trouble with is injecting mock classes into my tests for the servlet request/response.
The code I'm trying to test is quite simple, it looks like this. This is basically the entry point for my service, it accepts a JSON body, extracts a Yelp url from it, and thenYelpRequestController.makeYelpRequest()
takes care of scraping the images and returning the image links in an ArrayList.
@RestController
public class RequestController {
@PostMapping(value = "/")
public ArrayList<String> index(@RequestBody String reqBodyString) {
//my own function to parse the json string
HashMap<String, String> requestBody = parseReqBodyString(reqBodyString);
String yelpURL = requestBody.get("yelpURL");
YelpRequestController yelpRequest = new YelpRequestController(yelpURL);
ArrayList<String> yelpImgLinks = yelpRequest.makeYelpRequest();
return yelpImgLinks;
}
}
This is my unit test code. It basically creates a JSON string and sends a request to my RequestController and makes sure the response is okay. It passes right now, but I want the test to just test RequestController
and nothing else. Currently it sends the url from the test through YelpRequestController
and starts scraping images, which is what I don't want since I just want to isolate the RequestController
in this test. I've been trying to mock the YelpRequestController
class and return result, but I'm really having a lot of trouble.
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class RequestControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void postRequestController() throws Exception {
ObjectMapping jsonObject = new ObjectMapping();
jsonObject.setYelpUrl("https://www.yelp.ca/biz/l-industrie-pizzeria-brooklyn");
Gson gson = new Gson();
String json = gson.toJson(jsonObject);
mvc.perform(MockMvcRequestBuilders.post("/")
.accept(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(status().isOk());
}
}
I've been reading about how to use Mockito, and understand how to mock another class and inject it into a class you are testing. But I'm really stuck trying to apply that here. Any help would be appreciated.