mercredi 25 février 2015

Unittest Spring @RestController PUT-Method

is it possible to test the PUT-Method of a Controller like this:



@RestController
@RequestMapping("/EventListenerProcessor")
public class EventListenerProcessorController {

@Autowired
EventListenerRepository eventListenerRepository;

@Autowired
EventListenerProcessor eventListenerProcessor;

@RequestMapping(value = "/{eventName}", method = RequestMethod.PUT)
public void processEvent(@PathVariable("eventName") Event event){

if(event == null){
throw new EventDoesNotExistException();
}

ArrayList<EventListener> eventListeners = Lists.newArrayList(eventListenerRepository.findByEvent(event));

for(EventListener eventListener : eventListeners){
eventListenerProcessor.processEventListener(eventListener);
}

}

@ResponseStatus(value= HttpStatus.NOT_FOUND, reason = "No such event.")
public class EventDoesNotExistException extends RuntimeException{
}
}


with a testcase like this:



@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class EventProcessorControllerTest {

private MockMvc mvc;

@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new EventListenerProcessorController()).build();
}

@Test
public void postEventTest() throws Exception {
mvc.perform(MockMvcRequestBuilders.
put("/EventListenerProcessor/{eventName}", "Test"))
.andExpect(status().isNotFound());
}
}


My Problem is that i alwas get StatusCode 500 instead of 404. I think this happens because of the mapping of the eventName to a Event Object and the reduced Context of the Testcase. But I don't really want to load the whole application context. Is there any other more elegant way to test this Controller?


Aucun commentaire:

Enregistrer un commentaire