I tried to search the answer here, but couldn't find it. So here it goes: I am using Spring Boot. I am parsing Query String dynamically using
@RestController()
@RequestMapping("/processors")
public class ProcessorsController {
protected static transient Logger log = LoggerFactory.getLogger(ProcessorsController.class);
private Gson gson = new Gson();
@Autowired HttpServletRequest request;
private Options options = new Options();
@Autowired
ProcessorRepository processorRepository;
@CrossOrigin
@RequestMapping(value = "/{name}/run", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
String run(@RequestBody String input, @PathVariable("name") String name) {
Validate.notEmpty(input, "The request body must contain an not empty text");
return runProcessor(input, name);
}
private String runProcessor(String input, String name) {
Validate.notEmpty(name, "The processor name cannot be empty");
Processor processor = processorRepository.getProcessorCalled(name);
addOptions();
return processor.run(input, options);
}
private void addOptions() {
request.getParameterMap().forEach((k,v) -> {
if(!k.equals("text")) {
if (v[0] != null && !v[0].isEmpty()) {
options.put(k, v[0]);
}
}
});
}
}
This works fine in manual testing, but I am trying to write a unit test. Following is the example:
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {HAL.class, ProcessorsController.class})
@WebAppConfiguration
public abstract class ProcessorsControllerAbstractTest {
MockMvc mvc;
@Autowired
ProcessorRepository processorRepository;
@Autowired
HttpServletRequest request;
@Autowired
ProcessorsController processorsController;
@Before
public void setUp() throws Exception {
processorsController.processorRepository = processorRepository;
processorsController.request = request;
mvc = MockMvcBuilders.standaloneSetup(processorsController).build();
}
}
and within the actual test class
public class ProcessorsControllerTest extends ProcessorsControllerAbstractTest {
//other test cases
@Test
public void testAddOptions() throws Exception {
mvc.perform(MockMvcRequestBuilders.post("/processors/default/run").param("size","500").content(input).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
Assert.assertEquals("500", options.get("size"));
}
}
I am not able to get the request object values (e.g. params like size) at request.getParameterMap(). Is there any way I can access it? If not, what would be another way to test it? Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire