├── .github ├── dependabot.yml └── workflows │ └── maven.yml ├── .gitignore ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── example │ │ ├── DemoApplication.java │ │ ├── exception │ │ ├── ErrorResponse.java │ │ ├── RestExceptionHandler.java │ │ └── ToDoException.java │ │ ├── model │ │ ├── Response.java │ │ └── ToDo.java │ │ ├── repository │ │ └── ToDoRepository.java │ │ ├── service │ │ ├── ToDoService.java │ │ └── ToDoServiceImpl.java │ │ ├── util │ │ └── PayloadValidator.java │ │ └── web │ │ └── ToDoController.java └── resources │ └── application.properties └── test └── java └── com └── example ├── DemoApplicationTests.java ├── service └── ToDoServiceTest.java ├── util └── PayloadValidatorTest.java └── web └── ToDoControllerTest.java /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: maven 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: '05:00' 8 | timezone: Asia/Jakarta 9 | open-pull-requests-limit: 10 10 | -------------------------------------------------------------------------------- /.github/workflows/maven.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven 3 | 4 | # This workflow uses actions that are not certified by GitHub. 5 | # They are provided by a third-party and are governed by 6 | # separate terms of service, privacy policy, and support 7 | # documentation. 8 | 9 | name: Java CI with Maven 10 | 11 | on: 12 | push: 13 | branches: [ "master" ] 14 | pull_request: 15 | branches: [ "master" ] 16 | 17 | jobs: 18 | build: 19 | 20 | runs-on: ubuntu-latest 21 | 22 | steps: 23 | - uses: actions/checkout@v4 24 | - name: Set up JDK 21 25 | uses: actions/setup-java@v4 26 | with: 27 | java-version: '21' 28 | distribution: 'temurin' 29 | cache: maven 30 | - name: Build with Maven 31 | run: mvn -B package --file pom.xml 32 | 33 | # Optional: Uploads the full dependency graph to GitHub to improve the quality of Dependabot alerts this repository can receive 34 | - name: Update dependency graph 35 | uses: advanced-security/maven-dependency-submission-action@571e99aab1055c2e71a1e2309b9691de18d6b7d6 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | .idea/ 3 | target/ 4 | demo.iml 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpringBootUnitTestTutorial 2 | 3 | 1. mvn clean 4 | 2. mvn test 5 | 3. mvn clean install 6 | 4. Go to the target folder 7 | 5. java -jar demo-0.0.1-SNAPSHOT.jar 8 | 6. Verify your RESTful calls. 9 | 10 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | demo 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | demo 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 3.5.0 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 21 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-jpa 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | 38 | com.h2database 39 | h2 40 | runtime 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-test 45 | test 46 | 47 | 48 | 49 | 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-maven-plugin 54 | 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /src/main/java/com/example/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import com.example.model.ToDo; 4 | import com.example.repository.ToDoRepository; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.boot.CommandLineRunner; 8 | import org.springframework.boot.SpringApplication; 9 | import org.springframework.boot.autoconfigure.SpringBootApplication; 10 | import org.springframework.context.annotation.Bean; 11 | 12 | @SpringBootApplication 13 | public class DemoApplication { 14 | 15 | private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class); 16 | 17 | public static void main(String[] args) { 18 | SpringApplication.run(DemoApplication.class, args); 19 | } 20 | 21 | @Bean 22 | public CommandLineRunner setup(ToDoRepository toDoRepository) { 23 | return (args) -> { 24 | toDoRepository.save(new ToDo("Remove unused imports", true)); 25 | toDoRepository.save(new ToDo("Clean the code", true)); 26 | toDoRepository.save(new ToDo("Build the artifacts", false)); 27 | toDoRepository.save(new ToDo("Deploy the jar file", true)); 28 | logger.info("The sample data has been generated"); 29 | }; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/example/exception/ErrorResponse.java: -------------------------------------------------------------------------------- 1 | package com.example.exception; 2 | 3 | public class ErrorResponse { 4 | 5 | private int errorCode; 6 | private String message; 7 | 8 | public int getErrorCode() { 9 | return errorCode; 10 | } 11 | 12 | public void setErrorCode(int errorCode) { 13 | this.errorCode = errorCode; 14 | } 15 | 16 | public String getMessage() { 17 | return message; 18 | } 19 | 20 | public void setMessage(String message) { 21 | this.message = message; 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/com/example/exception/RestExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.example.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.http.ResponseEntity; 5 | import org.springframework.web.bind.annotation.ControllerAdvice; 6 | import org.springframework.web.bind.annotation.ExceptionHandler; 7 | 8 | @ControllerAdvice 9 | public class RestExceptionHandler { 10 | 11 | @ExceptionHandler(ToDoException.class) 12 | public ResponseEntity exceptionToDoHandler(Exception ex) { 13 | ErrorResponse error = new ErrorResponse(); 14 | error.setErrorCode(HttpStatus.NOT_FOUND.value()); 15 | error.setMessage(ex.getMessage()); 16 | return new ResponseEntity(error, HttpStatus.NOT_FOUND); 17 | } 18 | 19 | @ExceptionHandler(Exception.class) 20 | public ResponseEntity exceptionHandler(Exception ex) { 21 | ErrorResponse error = new ErrorResponse(); 22 | error.setErrorCode(HttpStatus.BAD_REQUEST.value()); 23 | error.setMessage("The request could not be understood by the server due to malformed syntax."); 24 | return new ResponseEntity(error, HttpStatus.BAD_REQUEST); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/example/exception/ToDoException.java: -------------------------------------------------------------------------------- 1 | package com.example.exception; 2 | 3 | public class ToDoException extends Exception { 4 | 5 | private static final long serialVersionUID = 1L; 6 | private String errorMessage; 7 | 8 | public ToDoException(String errorMessage) { 9 | super(errorMessage); 10 | this.errorMessage = errorMessage; 11 | } 12 | 13 | public ToDoException() { 14 | super(); 15 | } 16 | 17 | public String getErrorMessage() { 18 | return errorMessage; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/example/model/Response.java: -------------------------------------------------------------------------------- 1 | package com.example.model; 2 | 3 | public class Response { 4 | 5 | private int status; 6 | private String message; 7 | 8 | public Response() { 9 | super(); 10 | } 11 | 12 | public Response(int status, String message) { 13 | super(); 14 | this.status = status; 15 | this.message = message; 16 | } 17 | 18 | public int getStatus() { 19 | return status; 20 | } 21 | 22 | public void setStatus(int status) { 23 | this.status = status; 24 | } 25 | 26 | public String getMessage() { 27 | return message; 28 | } 29 | 30 | public void setMessage(String message) { 31 | this.message = message; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/example/model/ToDo.java: -------------------------------------------------------------------------------- 1 | package com.example.model; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.Id; 6 | 7 | @Entity 8 | public class ToDo { 9 | 10 | @Id 11 | @GeneratedValue 12 | private long id; 13 | private String text; 14 | private boolean completed; 15 | 16 | public ToDo() { 17 | super(); 18 | } 19 | 20 | 21 | public ToDo(long id, String text, boolean completed) { 22 | super(); 23 | this.id = id; 24 | this.text = text; 25 | this.completed = completed; 26 | } 27 | 28 | 29 | public ToDo(String text, boolean completed) { 30 | super(); 31 | this.text = text; 32 | this.completed = completed; 33 | } 34 | 35 | public long getId() { 36 | return id; 37 | } 38 | 39 | public void setId(long id) { 40 | this.id = id; 41 | } 42 | 43 | public String getText() { 44 | return text; 45 | } 46 | 47 | public void setText(String text) { 48 | this.text = text; 49 | } 50 | 51 | public boolean isCompleted() { 52 | return completed; 53 | } 54 | 55 | public void setCompleted(boolean completed) { 56 | this.completed = completed; 57 | } 58 | 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/example/repository/ToDoRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.repository; 2 | 3 | import com.example.model.ToDo; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository("toDoRepository") 8 | public interface ToDoRepository extends JpaRepository { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/example/service/ToDoService.java: -------------------------------------------------------------------------------- 1 | package com.example.service; 2 | 3 | import com.example.model.ToDo; 4 | 5 | import java.util.List; 6 | import java.util.Optional; 7 | 8 | public interface ToDoService { 9 | List getAllToDo(); 10 | 11 | Optional getToDoById(long id); 12 | 13 | ToDo saveToDo(ToDo todo); 14 | 15 | void removeToDo(ToDo todo); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/example/service/ToDoServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.service; 2 | 3 | import com.example.model.ToDo; 4 | import com.example.repository.ToDoRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | import java.util.List; 9 | import java.util.Optional; 10 | 11 | @Service("toDoService") 12 | public class ToDoServiceImpl implements ToDoService { 13 | 14 | @Autowired 15 | private ToDoRepository toDoRepository; 16 | 17 | @Override 18 | public List getAllToDo() { 19 | return toDoRepository.findAll(); 20 | } 21 | 22 | @Override 23 | public Optional getToDoById(long id) { 24 | return toDoRepository.findById(id); 25 | } 26 | 27 | @Override 28 | public ToDo saveToDo(ToDo todo) { 29 | return toDoRepository.save(todo); 30 | } 31 | 32 | @Override 33 | public void removeToDo(ToDo todo) { 34 | toDoRepository.delete(todo); 35 | } 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/example/util/PayloadValidator.java: -------------------------------------------------------------------------------- 1 | package com.example.util; 2 | 3 | import com.example.model.ToDo; 4 | 5 | public class PayloadValidator { 6 | 7 | public static boolean validateCreatePayload(ToDo toDo) { 8 | return toDo.getId() <= 0; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/example/web/ToDoController.java: -------------------------------------------------------------------------------- 1 | package com.example.web; 2 | 3 | import com.example.exception.ToDoException; 4 | import com.example.model.Response; 5 | import com.example.model.ToDo; 6 | import com.example.service.ToDoService; 7 | import com.example.util.PayloadValidator; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.http.HttpStatus; 12 | import org.springframework.http.ResponseEntity; 13 | import org.springframework.web.bind.annotation.*; 14 | 15 | import java.util.List; 16 | import java.util.Optional; 17 | 18 | @RestController 19 | public class ToDoController { 20 | 21 | private static final Logger logger = LoggerFactory.getLogger(ToDoController.class); 22 | 23 | @Autowired 24 | private ToDoService toDoService; 25 | 26 | @RequestMapping(value = "/todo", method = RequestMethod.GET) 27 | public ResponseEntity> getAllToDo() { 28 | logger.info("Returning all the ToDo´s"); 29 | return new ResponseEntity>(toDoService.getAllToDo(), HttpStatus.OK); 30 | } 31 | 32 | @RequestMapping(value = "/todo/{id}", method = RequestMethod.GET) 33 | public ResponseEntity getToDoById(@PathVariable("id") long id) throws ToDoException { 34 | logger.info("ToDo id to return " + id); 35 | Optional toDoOpt = toDoService.getToDoById(id); 36 | ToDo toDo = toDoOpt.get(); 37 | if (!toDoOpt.isPresent()) { 38 | throw new ToDoException("ToDo doesn´t exist"); 39 | } 40 | return new ResponseEntity(toDo, HttpStatus.OK); 41 | } 42 | 43 | @RequestMapping(value = "/todo/{id}", method = RequestMethod.DELETE) 44 | public ResponseEntity removeToDoById(@PathVariable("id") long id) throws ToDoException { 45 | logger.info("ToDo id to remove " + id); 46 | Optional toDoOpt = toDoService.getToDoById(id); 47 | ToDo toDo = toDoOpt.get(); 48 | if (!toDoOpt.isPresent()) { 49 | throw new ToDoException("ToDo to delete doesn´t exist"); 50 | } 51 | toDoService.removeToDo(toDo); 52 | return new ResponseEntity(new Response(HttpStatus.OK.value(), "ToDo has been deleted"), HttpStatus.OK); 53 | } 54 | 55 | @RequestMapping(value = "/todo", method = RequestMethod.POST) 56 | public ResponseEntity saveToDo(@RequestBody ToDo payload) throws ToDoException { 57 | logger.info("Payload to save " + payload); 58 | if (!PayloadValidator.validateCreatePayload(payload)) { 59 | throw new ToDoException("Payload malformed, id must not be defined"); 60 | } 61 | return new ResponseEntity(toDoService.saveToDo(payload), HttpStatus.OK); 62 | } 63 | 64 | @RequestMapping(value = "/todo", method = RequestMethod.PATCH) 65 | public ResponseEntity updateToDo(@RequestBody ToDo payload) throws ToDoException { 66 | logger.info("Payload to update " + payload); 67 | Optional toDoOpt = toDoService.getToDoById(payload.getId()); 68 | ToDo toDo = toDoOpt.get(); 69 | if (!toDoOpt.isPresent()) { 70 | throw new ToDoException("ToDo to update doesn´t exist"); 71 | } 72 | return new ResponseEntity(toDoService.saveToDo(payload), HttpStatus.OK); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hendisantika/spring-boot-unit-test/096a1ea139c469b0e5fafc944da297f251d1b4f8/src/main/resources/application.properties -------------------------------------------------------------------------------- /src/test/java/com/example/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class DemoApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/example/service/ToDoServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.example.service; 2 | 3 | import com.example.model.ToDo; 4 | import com.example.repository.ToDoRepository; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.mockito.InjectMocks; 9 | import org.mockito.Mock; 10 | import org.mockito.MockitoAnnotations; 11 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 12 | 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | import java.util.Optional; 16 | 17 | import static org.junit.Assert.assertEquals; 18 | import static org.mockito.Mockito.*; 19 | 20 | @RunWith(SpringJUnit4ClassRunner.class) 21 | public class ToDoServiceTest { 22 | 23 | @Mock 24 | private ToDoRepository toDoRepository; 25 | 26 | @InjectMocks 27 | private ToDoServiceImpl toDoService; 28 | 29 | @Before 30 | public void setup() { 31 | MockitoAnnotations.initMocks(this); 32 | } 33 | 34 | @Test 35 | public void testGetAllToDo() { 36 | List toDoList = new ArrayList(); 37 | toDoList.add(new ToDo(1, "Todo Sample 1", true)); 38 | toDoList.add(new ToDo(2, "Todo Sample 2", true)); 39 | toDoList.add(new ToDo(3, "Todo Sample 3", false)); 40 | when(toDoRepository.findAll()).thenReturn(toDoList); 41 | 42 | List result = toDoService.getAllToDo(); 43 | assertEquals(3, result.size()); 44 | } 45 | 46 | @Test 47 | public void testGetToDoById() { 48 | ToDo toDo = new ToDo(1, "Todo Sample 1", true); 49 | when(toDoRepository.findById(1L)).thenReturn(Optional.of(toDo)); 50 | Optional resultOpt = toDoService.getToDoById(1); 51 | ToDo result = resultOpt.get(); 52 | assertEquals(1, result.getId()); 53 | assertEquals("Todo Sample 1", result.getText()); 54 | assertEquals(true, result.isCompleted()); 55 | } 56 | 57 | @Test 58 | public void saveToDo() { 59 | ToDo toDo = new ToDo(8, "Todo Sample 8", true); 60 | when(toDoRepository.save(toDo)).thenReturn(toDo); 61 | ToDo result = toDoService.saveToDo(toDo); 62 | assertEquals(8, result.getId()); 63 | assertEquals("Todo Sample 8", result.getText()); 64 | assertEquals(true, result.isCompleted()); 65 | } 66 | 67 | @Test 68 | public void removeToDo() { 69 | ToDo toDo = new ToDo(8, "Todo Sample 8", true); 70 | toDoService.removeToDo(toDo); 71 | verify(toDoRepository, times(1)).delete(toDo); 72 | } 73 | 74 | 75 | } 76 | 77 | -------------------------------------------------------------------------------- /src/test/java/com/example/util/PayloadValidatorTest.java: -------------------------------------------------------------------------------- 1 | package com.example.util; 2 | 3 | import com.example.model.ToDo; 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.assertEquals; 7 | 8 | public class PayloadValidatorTest { 9 | 10 | @Test 11 | public void validatePayLoad() { 12 | ToDo toDo = new ToDo(1, "Sample ToDo 1", true); 13 | assertEquals(false, PayloadValidator.validateCreatePayload(toDo)); 14 | } 15 | 16 | @Test 17 | public void validateInvalidPayLoad() { 18 | ToDo toDo = new ToDo(0, "Sample ToDo 1", true); 19 | assertEquals(true, PayloadValidator.validateCreatePayload(toDo)); 20 | } 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/example/web/ToDoControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.example.web; 2 | 3 | import com.example.DemoApplication; 4 | import org.junit.Before; 5 | import org.junit.FixMethodOrder; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.junit.runners.MethodSorters; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.http.MediaType; 12 | import org.springframework.test.context.ContextConfiguration; 13 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 14 | import org.springframework.test.web.servlet.MockMvc; 15 | import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 16 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 17 | import org.springframework.web.context.WebApplicationContext; 18 | 19 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize; 20 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 21 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 22 | 23 | @RunWith(SpringJUnit4ClassRunner.class) 24 | @ContextConfiguration(classes = DemoApplication.class) 25 | @SpringBootTest 26 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 27 | public class ToDoControllerTest { 28 | 29 | private MockMvc mockMvc; 30 | 31 | @Autowired 32 | private WebApplicationContext wac; 33 | 34 | @Before 35 | public void setup() { 36 | this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); 37 | 38 | } 39 | 40 | @Test 41 | public void verifyAllToDoList() throws Exception { 42 | mockMvc.perform(MockMvcRequestBuilders.get("/todo").accept(MediaType.APPLICATION_JSON)) 43 | .andExpect(jsonPath("$", hasSize(4))).andDo(print()); 44 | } 45 | 46 | @Test 47 | public void verifyToDoById() throws Exception { 48 | mockMvc.perform(MockMvcRequestBuilders.get("/todo/3").accept(MediaType.APPLICATION_JSON)) 49 | .andExpect(jsonPath("$.id").exists()) 50 | .andExpect(jsonPath("$.text").exists()) 51 | .andExpect(jsonPath("$.completed").exists()) 52 | .andExpect(jsonPath("$.id").value(3)) 53 | .andExpect(jsonPath("$.text").value("Build the artifacts")) 54 | .andExpect(jsonPath("$.completed").value(false)) 55 | .andDo(print()); 56 | } 57 | 58 | @Test 59 | public void verifyInvalidToDoArgument() throws Exception { 60 | mockMvc.perform(MockMvcRequestBuilders.get("/todo/f").accept(MediaType.APPLICATION_JSON)) 61 | .andExpect(jsonPath("$.errorCode").value(400)) 62 | .andExpect(jsonPath("$.message").value("The request could not be understood by the server due to malformed syntax.")) 63 | .andDo(print()); 64 | } 65 | 66 | @Test 67 | public void verifyInvalidToDoId() throws Exception { 68 | mockMvc.perform(MockMvcRequestBuilders.get("/todo/0").accept(MediaType.APPLICATION_JSON)) 69 | .andExpect(jsonPath("$.errorCode").value(404)) 70 | .andExpect(jsonPath("$.message").value("ToDo doesn´t exist")) 71 | .andDo(print()); 72 | } 73 | 74 | @Test 75 | public void verifyNullToDo() throws Exception { 76 | mockMvc.perform(MockMvcRequestBuilders.get("/todo/6").accept(MediaType.APPLICATION_JSON)) 77 | .andExpect(jsonPath("$.errorCode").value(404)) 78 | .andExpect(jsonPath("$.message").value("ToDo doesn´t exist")) 79 | .andDo(print()); 80 | } 81 | 82 | @Test 83 | public void verifyDeleteToDo() throws Exception { 84 | mockMvc.perform(MockMvcRequestBuilders.delete("/todo/4").accept(MediaType.APPLICATION_JSON)) 85 | .andExpect(jsonPath("$.status").value(200)) 86 | .andExpect(jsonPath("$.message").value("ToDo has been deleted")) 87 | .andDo(print()); 88 | } 89 | 90 | @Test 91 | public void verifyInvalidToDoIdToDelete() throws Exception { 92 | mockMvc.perform(MockMvcRequestBuilders.delete("/todo/9").accept(MediaType.APPLICATION_JSON)) 93 | .andExpect(jsonPath("$.errorCode").value(404)) 94 | .andExpect(jsonPath("$.message").value("ToDo to delete doesn´t exist")) 95 | .andDo(print()); 96 | } 97 | 98 | 99 | @Test 100 | public void verifySaveToDo() throws Exception { 101 | mockMvc.perform(MockMvcRequestBuilders.post("/todo/") 102 | .contentType(MediaType.APPLICATION_JSON) 103 | .content("{\"text\" : \"New ToDo Sample\", \"completed\" : \"false\" }") 104 | .accept(MediaType.APPLICATION_JSON)) 105 | .andExpect(jsonPath("$.id").exists()) 106 | .andExpect(jsonPath("$.text").exists()) 107 | .andExpect(jsonPath("$.completed").exists()) 108 | .andExpect(jsonPath("$.text").value("New ToDo Sample")) 109 | .andExpect(jsonPath("$.completed").value(false)) 110 | .andDo(print()); 111 | } 112 | 113 | @Test 114 | public void verifyMalformedSaveToDo() throws Exception { 115 | mockMvc.perform(MockMvcRequestBuilders.post("/todo/") 116 | .contentType(MediaType.APPLICATION_JSON) 117 | .content("{ \"id\": \"8\", \"text\" : \"New ToDo Sample\", \"completed\" : \"false\" }") 118 | .accept(MediaType.APPLICATION_JSON)) 119 | .andExpect(jsonPath("$.errorCode").value(404)) 120 | .andExpect(jsonPath("$.message").value("Payload malformed, id must not be defined")) 121 | .andDo(print()); 122 | } 123 | 124 | @Test 125 | public void verifyUpdateToDo() throws Exception { 126 | mockMvc.perform(MockMvcRequestBuilders.patch("/todo/") 127 | .contentType(MediaType.APPLICATION_JSON) 128 | .content("{ \"id\": \"1\", \"text\" : \"New ToDo Text\", \"completed\" : \"false\" }") 129 | .accept(MediaType.APPLICATION_JSON)) 130 | .andExpect(jsonPath("$.id").exists()) 131 | .andExpect(jsonPath("$.text").exists()) 132 | .andExpect(jsonPath("$.completed").exists()) 133 | .andExpect(jsonPath("$.id").value(1)) 134 | .andExpect(jsonPath("$.text").value("New ToDo Text")) 135 | .andExpect(jsonPath("$.completed").value(false)) 136 | .andDo(print()); 137 | } 138 | 139 | @Test 140 | public void verifyInvalidToDoUpdate() throws Exception { 141 | mockMvc.perform(MockMvcRequestBuilders.patch("/todo/") 142 | .contentType(MediaType.APPLICATION_JSON) 143 | .content("{ \"idd\": \"8\", \"text\" : \"New ToDo Sample\", \"completed\" : \"false\" }") 144 | .accept(MediaType.APPLICATION_JSON)) 145 | .andExpect(jsonPath("$.errorCode").value(404)) 146 | .andExpect(jsonPath("$.message").value("ToDo to update doesn´t exist")) 147 | .andDo(print()); 148 | } 149 | 150 | } 151 | --------------------------------------------------------------------------------