diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..99b9d55 --- /dev/null +++ b/.gitignore @@ -0,0 +1,77 @@ +# Created by .ignore support plugin (hsz.mobi) +### Maven template +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +### Java template +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/workspace.xml +.idea/tasks.xml +.idea/dictionaries +.idea/vcs.xml +.idea/jsLibraryMappings.xml + +# Sensitive or high-churn files: +.idea/dataSources.ids +.idea/dataSources.xml +.idea/dataSources.local.xml +.idea/sqlDataSources.xml +.idea/dynamic.xml +.idea/uiDesigner.xml + +# Gradle: +.idea/gradle.xml +.idea/libraries + +# Mongo Explorer plugin: +.idea/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +.idea/ +*.iml + +/main/src/main/resources/doc/* + +*.project +*.classpath diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..4109dd3 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,71 @@ +//scripted jenkins file + +node('master') { + try { + properties([ + buildDiscarder(logRotator(daysToKeepStr: '3', numToKeepStr: '3', artifactDaysToKeepStr: '15', artifactNumToKeepStr: '5')), + disableConcurrentBuilds() + ]) + + stage("Checkout project") { + echo "Checking out the project" + try { + checkout scm + } catch (Exception e) { + throw e + } + } + + stage("Running testcases") { + echo "Running the testcases" + sh "mvn test" + } + + stage("Bundling project") { + echo "Bundling the project" + sh "mvn clean install" + } + + stage("Deploying to nexus") { + echo "Deploying the bundled jar to the nexus" + } + + stage("Sonar analyzer") { + echo "Running sonar analyzer" + } + + stage("Running vulnerability check") { + echo "Running the vulnerability step" + // sh "mvn dependency-check:aggregate -DsuppressionFile.path=suppressions.xml" + // sh "mvn dependency-check:aggregate" + } + + stage("Building docker image") { + echo "Performing docker setup" + } + + stage("Tag and publish to hub") { + echo "Tagging the docker image and pushing it to the hub" + } + + stage("Removing local image") { + echo "Clearing the work directory" + } + + stage("Performing deployment") { + echo "Performing the deployment" + } + + stage("Wipe out directory") { + echo "Wiping out the working directory" + } + + stage("Post action") { + echo "Performing the post action step. Setup email or slack notifications" + } + } + catch (Exception e) { + throw e + } +} + diff --git a/Jenkinsfile_declarative b/Jenkinsfile_declarative new file mode 100644 index 0000000..3bc2172 --- /dev/null +++ b/Jenkinsfile_declarative @@ -0,0 +1,24 @@ +pipeline { + agent any + + options { + buildDiscarder(logRotator(daysToKeepStr: '3', numToKeepStr: '3', artifactDaysToKeepStr: '15', artifactNumToKeepStr: '5')) + } + + triggers { + pollSCM 'H * * * *' + } + + stages { + stage('Running testcases') { + steps { + sh "mvn test" + } + } + stage('Bundling project') { + steps { + sh "mvn clean install" + } + } + } +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 6e67f52..09a00bc 100644 --- a/pom.xml +++ b/pom.xml @@ -1,59 +1,102 @@ - - 4.0.0 - - com.example - demo - 0.0.1-SNAPSHOT - jar - - demo - Demo project for Spring Boot - - - org.springframework.boot - spring-boot-starter-parent - 1.4.2.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-web - - - - com.h2database - h2 - runtime - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + 4.0.0 + com.example + demo + 0.0.1-SNAPSHOT + jar + demo + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.5.2 + + + + + UTF-8 + UTF-8 + 1.8 + ${java.version} + ${java.version} + 5.3.1 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.jupiter + junit-jupiter-api + ${junit-platform.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit-platform.version} + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.0 + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.0 + + + org.apache.maven.plugins + maven-failsafe-plugin + 2.22.0 + + + + + + + + + org.owasp + dependency-check-maven + + false + + + + + diff --git a/src/main/java/com/example/DemoApplication.java b/src/main/java/com/example/DemoApplication.java index 6a9650f..399ad65 100644 --- a/src/main/java/com/example/DemoApplication.java +++ b/src/main/java/com/example/DemoApplication.java @@ -1,5 +1,7 @@ package com.example; +import com.example.model.ToDo; +import com.example.repository.ToDoRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; @@ -7,26 +9,23 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; -import com.example.model.ToDo; -import com.example.repository.ToDoRepository; - @SpringBootApplication public class DemoApplication { - - private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class); - public static void main(String[] args) { - SpringApplication.run(DemoApplication.class, args); - } - - @Bean - public CommandLineRunner setup(ToDoRepository toDoRepository) { - return (args) -> { - toDoRepository.save(new ToDo("Remove unused imports", true)); - toDoRepository.save(new ToDo("Clean the code", true)); - toDoRepository.save(new ToDo("Build the artifacts", false)); - toDoRepository.save(new ToDo("Deploy the jar file", true)); - logger.info("The sample data has been generated"); - }; - } + private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class); + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } + + @Bean + public CommandLineRunner setup(ToDoRepository toDoRepository) { + return (args) -> { + toDoRepository.save(new ToDo("Remove unused imports", true)); + toDoRepository.save(new ToDo("Clean the code", true)); + toDoRepository.save(new ToDo("Build the artifacts", false)); + toDoRepository.save(new ToDo("Deploy the jar file", true)); + logger.info("The sample data has been generated"); + }; + } } diff --git a/src/main/java/com/example/exception/ErrorResponse.java b/src/main/java/com/example/exception/ErrorResponse.java index 7e42ea3..ff06504 100644 --- a/src/main/java/com/example/exception/ErrorResponse.java +++ b/src/main/java/com/example/exception/ErrorResponse.java @@ -1,23 +1,23 @@ package com.example.exception; public class ErrorResponse { - - private int errorCode; - private String message; - public int getErrorCode() { - return errorCode; - } + private int errorCode; + private String message; - public void setErrorCode(int errorCode) { - this.errorCode = errorCode; - } + public int getErrorCode() { + return errorCode; + } - public String getMessage() { - return message; - } + public void setErrorCode(int errorCode) { + this.errorCode = errorCode; + } - public void setMessage(String message) { - this.message = message; - } + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } } \ No newline at end of file diff --git a/src/main/java/com/example/exception/RestExceptionHandler.java b/src/main/java/com/example/exception/RestExceptionHandler.java index c03dfd5..43d8a5d 100644 --- a/src/main/java/com/example/exception/RestExceptionHandler.java +++ b/src/main/java/com/example/exception/RestExceptionHandler.java @@ -7,21 +7,21 @@ @ControllerAdvice public class RestExceptionHandler { - - @ExceptionHandler(ToDoException.class) - public ResponseEntity exceptionToDoHandler(Exception ex) { - ErrorResponse error = new ErrorResponse(); - error.setErrorCode(HttpStatus.NOT_FOUND.value()); - error.setMessage(ex.getMessage()); - return new ResponseEntity(error, HttpStatus.NOT_FOUND); - } - - @ExceptionHandler(Exception.class) - public ResponseEntity exceptionHandler(Exception ex) { - ErrorResponse error = new ErrorResponse(); - error.setErrorCode(HttpStatus.BAD_REQUEST.value()); - error.setMessage("The request could not be understood by the server due to malformed syntax."); - return new ResponseEntity(error, HttpStatus.BAD_REQUEST); - } + + @ExceptionHandler(ToDoException.class) + public ResponseEntity exceptionToDoHandler(Exception ex) { + ErrorResponse error = new ErrorResponse(); + error.setErrorCode(HttpStatus.NOT_FOUND.value()); + error.setMessage(ex.getMessage()); + return new ResponseEntity(error, HttpStatus.NOT_FOUND); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity exceptionHandler(Exception ex) { + ErrorResponse error = new ErrorResponse(); + error.setErrorCode(HttpStatus.BAD_REQUEST.value()); + error.setMessage("The request could not be understood by the server due to malformed syntax."); + return new ResponseEntity(error, HttpStatus.BAD_REQUEST); + } } diff --git a/src/main/java/com/example/exception/ToDoException.java b/src/main/java/com/example/exception/ToDoException.java index e2a2ac6..0f275df 100644 --- a/src/main/java/com/example/exception/ToDoException.java +++ b/src/main/java/com/example/exception/ToDoException.java @@ -1,20 +1,20 @@ package com.example.exception; public class ToDoException extends Exception { - - private static final long serialVersionUID = 1L; - private String errorMessage; - public String getErrorMessage() { - return errorMessage; - } + private static final long serialVersionUID = 1L; + private String errorMessage; - public ToDoException(String errorMessage) { - super(errorMessage); - this.errorMessage = errorMessage; - } + public ToDoException(String errorMessage) { + super(errorMessage); + this.errorMessage = errorMessage; + } - public ToDoException() { - super(); - } + public ToDoException() { + super(); + } + + public String getErrorMessage() { + return errorMessage; + } } diff --git a/src/main/java/com/example/model/Response.java b/src/main/java/com/example/model/Response.java index b8bca06..543fbb6 100644 --- a/src/main/java/com/example/model/Response.java +++ b/src/main/java/com/example/model/Response.java @@ -2,33 +2,33 @@ public class Response { - private int status; - private String message; - - public Response() { - super(); - } - - public Response(int status, String message) { - super(); - this.status = status; - this.message = message; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } + private int status; + private String message; + + public Response() { + super(); + } + + public Response(int status, String message) { + super(); + this.status = status; + this.message = message; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } } diff --git a/src/main/java/com/example/model/ToDo.java b/src/main/java/com/example/model/ToDo.java index 0820ed1..1a6342a 100644 --- a/src/main/java/com/example/model/ToDo.java +++ b/src/main/java/com/example/model/ToDo.java @@ -6,53 +6,55 @@ @Entity public class ToDo { - - @Id - @GeneratedValue - private long id; - private String text; - private boolean completed; - - public ToDo() { - super(); - } - - - public ToDo(long id, String text, boolean completed) { - super(); - this.id = id; - this.text = text; - this.completed = completed; - } - - - public ToDo(String text, boolean completed) { - super(); - this.text = text; - this.completed = completed; - } - public long getId() { - return id; - } - public void setId(long id) { - this.id = id; - } - - public String getText() { - return text; - } - public void setText(String text) { - this.text = text; - } - public boolean isCompleted() { - return completed; - } - public void setCompleted(boolean completed) { - this.completed = completed; - } - - - - + + @Id + @GeneratedValue + private long id; + private String text; + private boolean completed; + + public ToDo() { + super(); + } + + + public ToDo(long id, String text, boolean completed) { + super(); + this.id = id; + this.text = text; + this.completed = completed; + } + + + public ToDo(String text, boolean completed) { + super(); + this.text = text; + this.completed = completed; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public boolean isCompleted() { + return completed; + } + + public void setCompleted(boolean completed) { + this.completed = completed; + } + } diff --git a/src/main/java/com/example/repository/ToDoRepository.java b/src/main/java/com/example/repository/ToDoRepository.java index 4473b41..1e03409 100644 --- a/src/main/java/com/example/repository/ToDoRepository.java +++ b/src/main/java/com/example/repository/ToDoRepository.java @@ -1,11 +1,10 @@ package com.example.repository; +import com.example.model.ToDo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import com.example.model.ToDo; - @Repository("toDoRepository") -public interface ToDoRepository extends JpaRepository{ +public interface ToDoRepository extends JpaRepository { } diff --git a/src/main/java/com/example/service/ToDoService.java b/src/main/java/com/example/service/ToDoService.java index d92ad63..3d0fcc7 100644 --- a/src/main/java/com/example/service/ToDoService.java +++ b/src/main/java/com/example/service/ToDoService.java @@ -1,12 +1,16 @@ package com.example.service; -import java.util.List; - +import com.example.exception.ToDoException; import com.example.model.ToDo; +import java.util.List; + public interface ToDoService { - public List getAllToDo(); - public ToDo getToDoById(long id); - public ToDo saveToDo(ToDo todo); - public void removeToDo(ToDo todo); + List getAllToDo(); + + ToDo getToDoById(long id) throws ToDoException; + + ToDo saveToDo(ToDo todo); + + void removeToDo(ToDo todo); } diff --git a/src/main/java/com/example/service/ToDoServiceImpl.java b/src/main/java/com/example/service/ToDoServiceImpl.java index c7061e2..4e17182 100644 --- a/src/main/java/com/example/service/ToDoServiceImpl.java +++ b/src/main/java/com/example/service/ToDoServiceImpl.java @@ -1,38 +1,36 @@ package com.example.service; -import java.util.List; - +import com.example.exception.ToDoException; +import com.example.model.ToDo; +import com.example.repository.ToDoRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import com.example.model.ToDo; -import com.example.repository.ToDoRepository; +import java.util.List; @Service("toDoService") -public class ToDoServiceImpl implements ToDoService{ - - @Autowired - private ToDoRepository toDoRepository; - - @Override - public List getAllToDo() { - return toDoRepository.findAll(); - } - - @Override - public ToDo getToDoById(long id) { - return toDoRepository.findOne(id); - } - - @Override - public ToDo saveToDo(ToDo todo) { - return toDoRepository.save(todo); - } - - @Override - public void removeToDo(ToDo todo) { - toDoRepository.delete(todo); - } - - +public class ToDoServiceImpl implements ToDoService { + + @Autowired + private ToDoRepository toDoRepository; + + @Override + public List getAllToDo() { + return toDoRepository.findAll(); + } + + @Override + public ToDo getToDoById(long id) throws ToDoException { + return toDoRepository.findById(id).orElseThrow(() -> new ToDoException("Entity not found")); + } + + @Override + public ToDo saveToDo(ToDo todo) { + return toDoRepository.save(todo); + } + + @Override + public void removeToDo(ToDo todo) { + toDoRepository.delete(todo); + } } diff --git a/src/main/java/com/example/util/PayloadValidator.java b/src/main/java/com/example/util/PayloadValidator.java index c7b7814..50c47cd 100644 --- a/src/main/java/com/example/util/PayloadValidator.java +++ b/src/main/java/com/example/util/PayloadValidator.java @@ -3,12 +3,9 @@ import com.example.model.ToDo; public class PayloadValidator { - - public static boolean validateCreatePayload(ToDo toDo){ - if (toDo.getId() > 0){ - return false; - } - return true; + + public static boolean validateCreatePayload(ToDo toDo) { + return toDo.getId() <= 0; } } diff --git a/src/main/java/com/example/web/ToDoController.java b/src/main/java/com/example/web/ToDoController.java index 483a783..ac4a691 100644 --- a/src/main/java/com/example/web/ToDoController.java +++ b/src/main/java/com/example/web/ToDoController.java @@ -1,76 +1,71 @@ package com.example.web; -import java.util.List; - +import com.example.exception.ToDoException; +import com.example.model.Response; +import com.example.model.ToDo; +import com.example.service.ToDoService; +import com.example.util.PayloadValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; -import com.example.exception.ToDoException; -import com.example.model.Response; -import com.example.model.ToDo; -import com.example.service.ToDoService; -import com.example.util.PayloadValidator; +import java.util.List; @RestController public class ToDoController { - - private static final Logger logger = LoggerFactory.getLogger(ToDoController.class); - @Autowired - private ToDoService toDoService; - - @RequestMapping(value="/todo", method=RequestMethod.GET) - public ResponseEntity> getAllToDo(){ - logger.info("Returning all the ToDo´s"); - return new ResponseEntity>(toDoService.getAllToDo(), HttpStatus.OK); - } - + private static final Logger logger = LoggerFactory.getLogger(ToDoController.class); + + @Autowired + private ToDoService toDoService; + + // http://localhost:9800/todo + @RequestMapping(value = "/todo", method = RequestMethod.GET) + public ResponseEntity> getAllToDo() { + logger.info("Returning all the ToDo´s"); + return new ResponseEntity<>(toDoService.getAllToDo(), HttpStatus.OK); + } + @RequestMapping(value = "/todo/{id}", method = RequestMethod.GET) - public ResponseEntity getToDoById(@PathVariable("id") long id) throws ToDoException{ - logger.info("ToDo id to return " + id); - ToDo toDo = toDoService.getToDoById(id); - if (toDo == null || toDo.getId() <= 0){ + public ResponseEntity getToDoById(@PathVariable("id") long id) throws ToDoException { + logger.info("ToDo id to return " + id); + ToDo toDo = toDoService.getToDoById(id); + if (toDo == null || toDo.getId() <= 0) { throw new ToDoException("ToDo doesn´t exist"); - } - return new ResponseEntity(toDoService.getToDoById(id), HttpStatus.OK); - } + } + return new ResponseEntity<>(toDoService.getToDoById(id), HttpStatus.OK); + } @RequestMapping(value = "/todo/{id}", method = RequestMethod.DELETE) - public ResponseEntity removeToDoById(@PathVariable("id") long id) throws ToDoException{ - logger.info("ToDo id to remove " + id); - ToDo toDo = toDoService.getToDoById(id); - if (toDo == null || toDo.getId() <= 0){ + public ResponseEntity removeToDoById(@PathVariable("id") long id) throws ToDoException { + logger.info("ToDo id to remove " + id); + ToDo toDo = toDoService.getToDoById(id); + if (toDo == null || toDo.getId() <= 0) { throw new ToDoException("ToDo to delete doesn´t exist"); - } - toDoService.removeToDo(toDo); - return new ResponseEntity(new Response(HttpStatus.OK.value(), "ToDo has been deleted"), HttpStatus.OK); - } - + } + toDoService.removeToDo(toDo); + return new ResponseEntity<>(new Response(HttpStatus.OK.value(), "ToDo has been deleted"), HttpStatus.OK); + } + @RequestMapping(value = "/todo", method = RequestMethod.POST) - public ResponseEntity saveToDo(@RequestBody ToDo payload) throws ToDoException{ - logger.info("Payload to save " + payload); - if (!PayloadValidator.validateCreatePayload(payload)){ + public ResponseEntity saveToDo(@RequestBody ToDo payload) throws ToDoException { + logger.info("Payload to save " + payload); + if (!PayloadValidator.validateCreatePayload(payload)) { throw new ToDoException("Payload malformed, id must not be defined"); - } - return new ResponseEntity(toDoService.saveToDo(payload), HttpStatus.OK); - } - + } + return new ResponseEntity<>(toDoService.saveToDo(payload), HttpStatus.OK); + } + @RequestMapping(value = "/todo", method = RequestMethod.PATCH) - public ResponseEntity updateToDo(@RequestBody ToDo payload) throws ToDoException{ - logger.info("Payload to update " + payload); - ToDo toDo = toDoService.getToDoById(payload.getId()); - if (toDo == null || toDo.getId() <= 0){ + public ResponseEntity updateToDo(@RequestBody ToDo payload) throws ToDoException { + logger.info("Payload to update " + payload); + ToDo toDo = toDoService.getToDoById(payload.getId()); + if (toDo == null || toDo.getId() <= 0) { throw new ToDoException("ToDo to update doesn´t exist"); - } - return new ResponseEntity(toDoService.saveToDo(payload), HttpStatus.OK); - } - + } + return new ResponseEntity<>(toDoService.saveToDo(payload), HttpStatus.OK); + } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties deleted file mode 100644 index e69de29..0000000 diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..751dffa --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,23 @@ +server: + error: + include-stacktrace: never + port: 9800 +spring: + application: + name: versioning-restful-services + datasource: + driverClassName: org.h2.Driver + password: '' + url: 'jdbc:h2:mem:testdb' + username: sa + h2: + console: + enabled: true + path: /h2-console + jpa: + database-platform: org.hibernate.dialect.H2Dialect + hibernate: + ddl-auto: create-drop + properties: + hibernate: + show_sql: true diff --git a/src/test/java/com/example/DemoApplicationTests.java b/src/test/java/com/example/DemoApplicationTests.java index 5ad5ac2..1250511 100644 --- a/src/test/java/com/example/DemoApplicationTests.java +++ b/src/test/java/com/example/DemoApplicationTests.java @@ -1,16 +1,16 @@ package com.example; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest public class DemoApplicationTests { - @Test - public void contextLoads() { - } + @Test + public void contextLoads() { + } } diff --git a/src/test/java/com/example/service/ToDoServiceTest.java b/src/test/java/com/example/service/ToDoServiceTest.java index cd3348d..c16059b 100644 --- a/src/test/java/com/example/service/ToDoServiceTest.java +++ b/src/test/java/com/example/service/ToDoServiceTest.java @@ -1,78 +1,75 @@ package com.example.service; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.example.exception.ToDoException; +import com.example.model.ToDo; +import com.example.repository.ToDoRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; -import com.example.model.ToDo; -import com.example.repository.ToDoRepository; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; -@RunWith(SpringJUnit4ClassRunner.class) +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; + +@ExtendWith(SpringExtension.class) public class ToDoServiceTest { - - @Mock - private ToDoRepository toDoRepository; - - @InjectMocks - private ToDoServiceImpl toDoService; - - @Before - public void setup(){ - MockitoAnnotations.initMocks(this); - } - - @Test - public void testGetAllToDo(){ - List toDoList = new ArrayList(); - toDoList.add(new ToDo(1,"Todo Sample 1",true)); - toDoList.add(new ToDo(2,"Todo Sample 2",true)); - toDoList.add(new ToDo(3,"Todo Sample 3",false)); - when(toDoRepository.findAll()).thenReturn(toDoList); - - List result = toDoService.getAllToDo(); - assertEquals(3, result.size()); - } - - @Test - public void testGetToDoById(){ - ToDo toDo = new ToDo(1,"Todo Sample 1",true); - when(toDoRepository.findOne(1L)).thenReturn(toDo); - ToDo result = toDoService.getToDoById(1); - assertEquals(1, result.getId()); - assertEquals("Todo Sample 1", result.getText()); - assertEquals(true, result.isCompleted()); - } - - @Test - public void saveToDo(){ - ToDo toDo = new ToDo(8,"Todo Sample 8",true); - when(toDoRepository.save(toDo)).thenReturn(toDo); - ToDo result = toDoService.saveToDo(toDo); - assertEquals(8, result.getId()); - assertEquals("Todo Sample 8", result.getText()); - assertEquals(true, result.isCompleted()); - } - - @Test - public void removeToDo(){ - ToDo toDo = new ToDo(8,"Todo Sample 8",true); - toDoService.removeToDo(toDo); - verify(toDoRepository, times(1)).delete(toDo); - } - - + @Mock + private ToDoRepository toDoRepository; + + @InjectMocks + private ToDoServiceImpl toDoService; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testGetAllToDo() { + List toDoList = new ArrayList(); + toDoList.add(new ToDo(1, "Todo Sample 1", true)); + toDoList.add(new ToDo(2, "Todo Sample 2", true)); + toDoList.add(new ToDo(3, "Todo Sample 3", false)); + when(toDoRepository.findAll()).thenReturn(toDoList); + + List result = toDoService.getAllToDo(); + assertEquals(3, result.size()); + } + + @Test + public void testGetToDoById() throws ToDoException { + ToDo toDo = new ToDo(1, "Todo Sample 1", true); + when(toDoRepository.findById(1L)).thenReturn(Optional.of(toDo)); + ToDo result = toDoService.getToDoById(1); + assertEquals(1, result.getId()); + assertEquals("Todo Sample 1", result.getText()); + assertTrue(result.isCompleted()); + } + + @Test + public void saveToDo() { + ToDo toDo = new ToDo(8, "Todo Sample 8", true); + when(toDoRepository.save(toDo)).thenReturn(toDo); + ToDo result = toDoService.saveToDo(toDo); + assertEquals(8, result.getId()); + assertEquals("Todo Sample 8", result.getText()); + assertTrue(result.isCompleted()); + } + + @Test + public void removeToDo() { + ToDo toDo = new ToDo(8, "Todo Sample 8", true); + toDoService.removeToDo(toDo); + verify(toDoRepository, times(1)).delete(toDo); + } } diff --git a/src/test/java/com/example/util/PayloadValidatorTest.java b/src/test/java/com/example/util/PayloadValidatorTest.java index 8e35155..3edc9ca 100644 --- a/src/test/java/com/example/util/PayloadValidatorTest.java +++ b/src/test/java/com/example/util/PayloadValidatorTest.java @@ -1,25 +1,22 @@ package com.example.util; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - import com.example.model.ToDo; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class PayloadValidatorTest { - @Test - public void validatePayLoad() { - ToDo toDo = new ToDo(1, "Sample ToDo 1", true); - assertEquals(false, PayloadValidator.validateCreatePayload(toDo)); - } - - @Test - public void validateInvalidPayLoad() { - ToDo toDo = new ToDo(0, "Sample ToDo 1", true); - assertEquals(true, PayloadValidator.validateCreatePayload(toDo)); - } - - + @Test + public void validatePayLoad() { + ToDo toDo = new ToDo(1, "Sample ToDo 1", true); + assertFalse(PayloadValidator.validateCreatePayload(toDo)); + } + @Test + public void validateInvalidPayLoad() { + ToDo toDo = new ToDo(0, "Sample ToDo 1", true); + assertTrue(PayloadValidator.validateCreatePayload(toDo)); + } } diff --git a/src/test/java/com/example/web/ToDoControllerTest.java b/src/test/java/com/example/web/ToDoControllerTest.java index de868ee..07d4f4c 100644 --- a/src/test/java/com/example/web/ToDoControllerTest.java +++ b/src/test/java/com/example/web/ToDoControllerTest.java @@ -1,151 +1,147 @@ package com.example.web; -import static org.hamcrest.collection.IsCollectionWithSize.hasSize; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; - -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +import com.example.DemoApplication; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.example.DemoApplication; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -@RunWith(SpringJUnit4ClassRunner.class) +@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = DemoApplication.class) @SpringBootTest -@FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ToDoControllerTest { - private MockMvc mockMvc; - - @Autowired + private MockMvc mockMvc; + + @Autowired private WebApplicationContext wac; - @Before - public void setup() { + @BeforeEach + public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); - } - - @Test - public void verifyAllToDoList() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/todo").accept(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$", hasSize(4))).andDo(print()); - } - - @Test - public void verifyToDoById() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/todo/3").accept(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.id").exists()) - .andExpect(jsonPath("$.text").exists()) - .andExpect(jsonPath("$.completed").exists()) - .andExpect(jsonPath("$.id").value(3)) - .andExpect(jsonPath("$.text").value("Build the artifacts")) - .andExpect(jsonPath("$.completed").value(false)) - .andDo(print()); - } - - @Test - public void verifyInvalidToDoArgument() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/todo/f").accept(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.errorCode").value(400)) - .andExpect(jsonPath("$.message").value("The request could not be understood by the server due to malformed syntax.")) - .andDo(print()); - } - - @Test - public void verifyInvalidToDoId() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/todo/0").accept(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.errorCode").value(404)) - .andExpect(jsonPath("$.message").value("ToDo doesn´t exist")) - .andDo(print()); - } - - @Test - public void verifyNullToDo() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/todo/6").accept(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.errorCode").value(404)) - .andExpect(jsonPath("$.message").value("ToDo doesn´t exist")) - .andDo(print()); - } - - @Test - public void verifyDeleteToDo() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.delete("/todo/4").accept(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.status").value(200)) - .andExpect(jsonPath("$.message").value("ToDo has been deleted")) - .andDo(print()); - } - - @Test - public void verifyInvalidToDoIdToDelete() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.delete("/todo/9").accept(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.errorCode").value(404)) - .andExpect(jsonPath("$.message").value("ToDo to delete doesn´t exist")) - .andDo(print()); - } - - - @Test - public void verifySaveToDo() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.post("/todo/") - .contentType(MediaType.APPLICATION_JSON) - .content("{\"text\" : \"New ToDo Sample\", \"completed\" : \"false\" }") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.id").exists()) - .andExpect(jsonPath("$.text").exists()) - .andExpect(jsonPath("$.completed").exists()) - .andExpect(jsonPath("$.text").value("New ToDo Sample")) - .andExpect(jsonPath("$.completed").value(false)) - .andDo(print()); - } - - @Test - public void verifyMalformedSaveToDo() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.post("/todo/") - .contentType(MediaType.APPLICATION_JSON) - .content("{ \"id\": \"8\", \"text\" : \"New ToDo Sample\", \"completed\" : \"false\" }") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.errorCode").value(404)) - .andExpect(jsonPath("$.message").value("Payload malformed, id must not be defined")) - .andDo(print()); - } - - @Test - public void verifyUpdateToDo() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.patch("/todo/") - .contentType(MediaType.APPLICATION_JSON) - .content("{ \"id\": \"1\", \"text\" : \"New ToDo Text\", \"completed\" : \"false\" }") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.id").exists()) - .andExpect(jsonPath("$.text").exists()) - .andExpect(jsonPath("$.completed").exists()) - .andExpect(jsonPath("$.id").value(1)) - .andExpect(jsonPath("$.text").value("New ToDo Text")) - .andExpect(jsonPath("$.completed").value(false)) - .andDo(print()); - } - - @Test - public void verifyInvalidToDoUpdate() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.patch("/todo/") - .contentType(MediaType.APPLICATION_JSON) - .content("{ \"idd\": \"8\", \"text\" : \"New ToDo Sample\", \"completed\" : \"false\" }") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.errorCode").value(404)) - .andExpect(jsonPath("$.message").value("ToDo to update doesn´t exist")) - .andDo(print()); - } + } + + @Test + public void verifyAllToDoList() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/todo").accept(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$", hasSize(4))).andDo(print()); + } + + @Test + public void verifyToDoById() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/todo/3").accept(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.id").exists()) + .andExpect(jsonPath("$.text").exists()) + .andExpect(jsonPath("$.completed").exists()) + .andExpect(jsonPath("$.id").value(3)) + .andExpect(jsonPath("$.text").value("Build the artifacts")) + .andExpect(jsonPath("$.completed").value(false)) + .andDo(print()); + } + + @Test + public void verifyInvalidToDoArgument() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/todo/f").accept(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.errorCode").value(400)) + .andExpect(jsonPath("$.message").value("The request could not be understood by the server due to malformed syntax.")) + .andDo(print()); + } + + @Test + public void verifyInvalidToDoId() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/todo/0").accept(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.errorCode").value(404)) + .andExpect(jsonPath("$.message").value("Entity not found")) + .andDo(print()); + } + + @Test + public void verifyNullToDo() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/todo/6").accept(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.errorCode").value(404)) + .andExpect(jsonPath("$.message").value("Entity not found")) + .andDo(print()); + } + + @Test + public void verifyDeleteToDo() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.delete("/todo/4").accept(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.status").value(200)) + .andExpect(jsonPath("$.message").value("ToDo has been deleted")) + .andDo(print()); + } + + @Test + public void verifyInvalidToDoIdToDelete() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.delete("/todo/9").accept(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.errorCode").value(404)) + .andExpect(jsonPath("$.message").value("Entity not found")) + .andDo(print()); + } + + + @Test + public void verifySaveToDo() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post("/todo/") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"text\" : \"New ToDo Sample\", \"completed\" : \"false\" }") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.id").exists()) + .andExpect(jsonPath("$.text").exists()) + .andExpect(jsonPath("$.completed").exists()) + .andExpect(jsonPath("$.text").value("New ToDo Sample")) + .andExpect(jsonPath("$.completed").value(false)) + .andDo(print()); + } + + @Test + public void verifyMalformedSaveToDo() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post("/todo/") + .contentType(MediaType.APPLICATION_JSON) + .content("{ \"id\": \"8\", \"text\" : \"New ToDo Sample\", \"completed\" : \"false\" }") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.errorCode").value(404)) + .andExpect(jsonPath("$.message").value("Payload malformed, id must not be defined")) + .andDo(print()); + } + + @Test + public void verifyUpdateToDo() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.patch("/todo/") + .contentType(MediaType.APPLICATION_JSON) + .content("{ \"id\": \"1\", \"text\" : \"New ToDo Text\", \"completed\" : \"false\" }") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.id").exists()) + .andExpect(jsonPath("$.text").exists()) + .andExpect(jsonPath("$.completed").exists()) + .andExpect(jsonPath("$.id").value(1)) + .andExpect(jsonPath("$.text").value("New ToDo Text")) + .andExpect(jsonPath("$.completed").value(false)) + .andDo(print()); + } + + @Test + public void verifyInvalidToDoUpdate() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.patch("/todo/") + .contentType(MediaType.APPLICATION_JSON) + .content("{ \"idd\": \"8\", \"text\" : \"New ToDo Sample\", \"completed\" : \"false\" }") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.errorCode").value(404)) + .andExpect(jsonPath("$.message").value("Entity not found")) + .andDo(print()); + } }