Reputation: 133
I need to do unit testing on a @RestController where every method returns with a ResponseEntity. I have a CRUD repository to use but I don't know how can I test it with the ResponseEntities.
@RestController
@RequestMapping("/events")
public class EventController {
@Autowired
private EventRepository eventRepository;
@GetMapping("")
public ResponseEntity<Iterable<Event>> getAll() {
return ResponseEntity.ok(eventRepository.findAll());
}
@GetMapping("/{id}")
public ResponseEntity<Event> get(@PathVariable Integer id) {
Optional<Event> event= eventRepository.findById(id);
if (event.isPresent()) {
return ResponseEntity.ok(event.get());
} else {
return ResponseEntity.notFound().build();
}
}
@PostMapping("")
public ResponseEntity<Event> post(@RequestBody Event event) {
EventsavedEvent = eventRepository.save(event);
return ResponseEntity.ok(savedEvent);
}
.
.
.
Upvotes: 0
Views: 476
Reputation: 366
So far so good , I can help you .
First of all, you must add unit test dependency. After that you must examine below code. Below code only consist for create. Good luck.
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
@ActiveProfiles("dev")
public class EventControllerTests {
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void testCreateEvent() {
Event event = new Event(); // Your entity
event.setEventName("Test"); // Your entity attributes
URI location = testRestTemplate.postForLocation("http://localhost:8080/events", event);
Event event2 = testRestTemplate.getForObject(location, Event.class);
MatcherAssert.assertThat(event2.getEventName(), Matchers.equalTo(event.getEventName()));
}
}
Upvotes: 1