ZAKARIA BOURHIL
03/04/2024, 4:12 PMpackage net.javaguides.springboot.integration;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import net.javaguides.springboot.model.Intern;
import net.javaguides.springboot.repository.InternRepository;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("wiremock")
public class InternControllerITwiremock {
private static WireMockServer wireMockServer;
@Autowired
private MockMvc mockMvc;
private static String urlToStub;
private static long internId;
@BeforeAll
static void init() {
wireMockServer = new WireMockServer(
new WireMockConfiguration()
.port(7070)
);
wireMockServer.start();
WireMock.configureFor("localhost", 7070);
internId = 1L;
urlToStub = String.format("/api/interns/%d", internId);
}
@Test
void shouldCallGetAllInterns() throws Exception {
Intern resource = getExpectedInternResponse();
stubFor(WireMock.get(urlMatching(urlToStub))
.willReturn(aResponse()
.withHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.withBody("{ \"id\": 1, \"firstName\": \"salma\", \"lastName\": \"mhalou\" , \"email\": \"<mailto:salma@gmail.com|salma@gmail.com>\" }")
.withStatus(OK.value())));
mockMvc.perform(get("/api/interns/{id}", internId))
.andDo(print()).andExpect(status().isOk())
.andExpect(content().json(parseToJson(resource)));
verify(getRequestedFor(urlPathEqualTo(urlToStub)));
}
private static String parseToJson(Intern intern) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(intern);
}
private Intern getExpectedInternResponse(){
return Intern.builder()
.firstName("salma")
.lastName("mhalou")
.email("<mailto:salma@gmail.com|salma@gmail.com>")
.build();
}
}
this is my controller :
package net.javaguides.springboot.contoller;
import lombok.AllArgsConstructor;
import net.javaguides.springboot.model.Intern;
import net.javaguides.springboot.service.InternService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController // make this class as Spring MVC Controller
@RequestMapping("/api/interns")// provide a base URL for all the REST APIs defined in this controller
@AllArgsConstructor
public class InternController {
private InternService internService;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Intern createIntern(@RequestBody Intern intern){
return internService.saveIntern(intern);
}
@GetMapping
@ResponseStatus(HttpStatus.OK)
public List<Intern> getAllInterns(){
return internService.getAllInterns();
}
@GetMapping("{id}")
public ResponseEntity<Intern> getInternById(@PathVariable("id") long internId){
return internService.getInternById(internId)
.map(ResponseEntity::ok)
.orElseGet(()-> ResponseEntity.notFound().build());
}
@PutMapping("{id}")
public ResponseEntity<Intern> updateIntern(@PathVariable("id") long internId ,@RequestBody Intern intern){
return internService.getInternById(internId)
.map(
savedIntern ->{
savedIntern.setFirstName(intern.getFirstName());
savedIntern.setLastName(intern.getLastName());
savedIntern.setEmail(intern.getEmail());
Intern updatedIntern = internService.updateIntern(savedIntern);
return new ResponseEntity<>(updatedIntern , HttpStatus.OK);
})
.orElseGet(()-> ResponseEntity.notFound().build());
}
@DeleteMapping("{id}")
public ResponseEntity<String> deleteIntern(@PathVariable("id") long internId){
internService.deleteIntern(internId);
return new ResponseEntity<>("intern deleted successfully !!!",HttpStatus.OK);
}
}
and my service :
package net.javaguides.springboot.service.impl;
import lombok.AllArgsConstructor;
import net.javaguides.springboot.exception.InternNotFoundException;
import net.javaguides.springboot.model.Intern;
import net.javaguides.springboot.repository.InternRepository;
import net.javaguides.springboot.service.InternService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
@AllArgsConstructor
public class InternServiceImpl implements InternService {
private InternRepository internRepository;
@Override
public Intern saveIntern(Intern intern) {
// boolean exist = internRepository.checkInternEmailExists(intern.getEmail());
// if (exist){
// throw new ResourceNotFoundException("intern email already exist with this email : "+intern.getEmail());
// }
Optional<Intern> internSaved = internRepository.findByEmail(intern.getEmail());
if (internSaved.isPresent()){
throw new InternNotFoundException("intern email already exist with this email : "+intern.getEmail());
}
return internRepository.save(intern);
}
@Override
public List<Intern> getAllInterns() {
return internRepository.findAll();
}
@Override
public Optional<Intern> getInternById(long id) {
Optional<Intern> optionalIntern = internRepository.findById(id);
if (optionalIntern.isPresent()) {
return optionalIntern;
} else {
throw new InternNotFoundException("Intern not found with id : " + id);
}
}
@Override
public Intern updateIntern(Intern updatedIntern) {
Optional<Intern> internSaved = internRepository.findById(updatedIntern.getId());
if (internSaved.isEmpty()){
throw new InternNotFoundException("Intern not found with id : "+updatedIntern.getId());
}
return internRepository.save(updatedIntern);
}
@Override
public void deleteIntern(long id) {
Optional<Intern> optionalIntern = internRepository.findById(id);
if (optionalIntern.isPresent()) {
internRepository.deleteById(id);
} else {
throw new InternNotFoundException("Intern not found with id : " + id);
}
}
}