BAEL-3091: The Prototype Pattern in Java (changed code based on valid comments from a reader)

This commit is contained in:
Vivek Balasubramaniam
2019-10-29 22:27:15 +05:30
parent db85c8f275
commit d3d5b060e7
20517 changed files with 1642290 additions and 0 deletions
+195
View File
@@ -0,0 +1,195 @@
= RESTful Notes API Guide
Baeldung;
:doctype: book
:icons: font
:source-highlighter: highlightjs
:toc: left
:toclevels: 4
:sectlinks:
[[overview]]
= Overview
[[overview-http-verbs]]
== HTTP verbs
RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its
use of HTTP verbs.
|===
| Verb | Usage
| `GET`
| Used to retrieve a resource
| `POST`
| Used to create a new resource
| `PATCH`
| Used to update an existing resource, including partial updates
| `DELETE`
| Used to delete an existing resource
|===
RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its
use of HTTP status codes.
|===
| Status code | Usage
| `200 OK`
| The request completed successfully
| `201 Created`
| A new resource has been created successfully. The resource's URI is available from the response's
`Location` header
| `204 No Content`
| An update to an existing resource has been applied successfully
| `400 Bad Request`
| The request was malformed. The response body will include an error providing further information
| `404 Not Found`
| The requested resource did not exist
|===
[[overview-hypermedia]]
== Hypermedia
RESTful Notes uses hypermedia and resources include links to other resources in their
responses. Responses are in http://stateless.co/hal_specification.html[Hypertext Application
from resource to resource.
Language (HAL)] format. Links can be found beneath the `_links` key. Users of the API should
not create URIs themselves, instead they should use the above-described links to navigate
[[resources]]
= Resources
[[resources-index]]
== Index
The index provides the entry point into the service.
[[resources-index-access]]
=== Accessing the index
A `GET` request is used to access the index
==== Request structure
include::{snippets}/index-example/http-request.adoc[]
==== Example response
include::{snippets}/index-example/http-response.adoc[]
==== CURL request
include::{snippets}/index-example/curl-request.adoc[]
[[resources-index-links]]
==== Links
include::{snippets}/index-example/links.adoc[]
[[resources-CRUD]]
== CRUD REST Service
The CRUD provides the entry point into the service.
[[resources-crud-get]]
=== Accessing the crud GET
A `GET` request is used to access the CRUD read.
==== Request structure
include::{snippets}/crud-get-example/http-request.adoc[]
==== Example response
include::{snippets}/crud-get-example/http-response.adoc[]
==== CURL request
include::{snippets}/crud-get-example/curl-request.adoc[]
[[resources-crud-post]]
=== Accessing the crud POST
A `POST` request is used to access the CRUD create.
==== Request structure
include::{snippets}/crud-create-example/http-request.adoc[]
==== Example response
include::{snippets}/crud-create-example/http-response.adoc[]
==== CURL request
include::{snippets}/crud-create-example/curl-request.adoc[]
[[resources-crud-delete]]
=== Accessing the crud DELETE
A `DELETE` request is used to access the CRUD delete.
==== Request structure
include::{snippets}/crud-delete-example/http-request.adoc[]
==== Path Parameters
include::{snippets}/crud-delete-example/path-parameters.adoc[]
==== Example response
include::{snippets}/crud-delete-example/http-response.adoc[]
==== CURL request
include::{snippets}/crud-delete-example/curl-request.adoc[]
[[resources-crud-patch]]
=== Accessing the crud PATCH
A `PATCH` request is used to access the CRUD update.
==== Request structure
include::{snippets}/crud-patch-example/http-request.adoc[]
==== Example response
include::{snippets}/crud-patch-example/http-response.adoc[]
==== CURL request
include::{snippets}/crud-patch-example/curl-request.adoc[]
[[resources-crud-put]]
=== Accessing the crud PUT
A `PUT` request is used to access the CRUD update.
==== Request structure
include::{snippets}/crud-put-example/http-request.adoc[]
==== Example response
include::{snippets}/crud-put-example/http-response.adoc[]
==== CURL request
include::{snippets}/crud-put-example/curl-request.adoc[]
@@ -0,0 +1,13 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Spring5Application {
public static void main(String[] args) {
SpringApplication.run(Spring5Application.class, args);
}
}
@@ -0,0 +1,8 @@
package com.baeldung.annotationconfigvscomponentscan.components;
import org.springframework.stereotype.Component;
@Component
public class AccountService {
}
@@ -0,0 +1,16 @@
package com.baeldung.annotationconfigvscomponentscan.components;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class UserService {
@Autowired
private AccountService accountService;
public AccountService getAccountService() {
return accountService;
}
}
@@ -0,0 +1,124 @@
package com.baeldung.assertions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.util.Assert;
public class Car {
private String state = "stop";
public void drive(int speed) {
Assert.isTrue(speed > 0, "speed must be positive");
this.state = "drive";
// ...
if (!(speed > 0)) {
throw new IllegalArgumentException("speed must be >0");
}
}
public void stop() {
this.state = "stop";
}
public void fuel() {
Assert.state(this.state.equals("stop"), "car must be stopped");
// ...
}
public void fuelwithSupplier() {
Assert.state(this.state.equals("stop"), () -> "car must be stopped");
// ...
}
public void сhangeOil(String oil) {
Assert.notNull(oil, "oil mustn't be null");
// ...
}
public void replaceBattery(CarBattery carBattery) {
Assert.isNull(carBattery.getCharge(), "to replace battery the charge must be null");
// ...
}
public void сhangeEngine(Engine engine) {
Assert.isInstanceOf(ToyotaEngine.class, engine);
// ...
}
public void repairEngine(Engine engine) {
Assert.isAssignable(Engine.class, ToyotaEngine.class);
// ...
}
public void startWithHasLength(String key) {
Assert.hasLength(key, "key must not be null and must not the empty");
// ...
}
public void startWithHasText(String key) {
Assert.hasText(key, "key must not be null and must contain at least one non-whitespace character");
// ...
}
public void startWithNotContain(String key) {
Assert.doesNotContain(key, "123", "key must not contain 123");
// ...
}
public void repair(Collection<String> repairParts) {
Assert.notEmpty(repairParts, "collection of repairParts mustn't be empty");
// ...
}
public void repair(Map<String, String> repairParts) {
Assert.notEmpty(repairParts, "map of repairParts mustn't be empty");
// ...
}
public void repair(String[] repairParts) {
Assert.notEmpty(repairParts, "array of repairParts must not be empty");
// ...
}
public void repairWithNoNull(String[] repairParts) {
Assert.noNullElements(repairParts, "array of repairParts must not contain null elements");
// ...
}
public static void main(String[] args) {
Car car = new Car();
car.drive(50);
car.stop();
car.fuel();
car.сhangeOil("oil");
CarBattery carBattery = new CarBattery();
car.replaceBattery(carBattery);
car.сhangeEngine(new ToyotaEngine());
car.startWithHasLength(" ");
car.startWithHasText("t");
car.startWithNotContain("132");
List<String> repairPartsCollection = new ArrayList<String>();
repairPartsCollection.add("part");
car.repair(repairPartsCollection);
Map<String, String> repairPartsMap = new HashMap<String, String>();
repairPartsMap.put("1", "part");
car.repair(repairPartsMap);
String[] repairPartsArray = { "part" };
car.repair(repairPartsArray);
}
}
@@ -0,0 +1,13 @@
package com.baeldung.assertions;
public class CarBattery {
private String charge;
public String getCharge() {
return charge;
}
public void setCharge(String charge) {
this.charge = charge;
}
}
@@ -0,0 +1,4 @@
package com.baeldung.assertions;
public class Engine {
}
@@ -0,0 +1,5 @@
package com.baeldung.assertions;
public class ToyotaEngine extends Engine {
}
@@ -0,0 +1,12 @@
package com.baeldung.config;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories("com.baeldung.persistence")
@EntityScan("com.baeldung.web")
public class PersistenceConfig {
}
@@ -0,0 +1,41 @@
package com.baeldung.exception;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
@RestController
public class ActorController {
@Autowired
ActorService actorService;
@GetMapping("/actor/{id}")
public String getActorName(@PathVariable("id") int id) {
try {
return actorService.getActor(id);
} catch (ActorNotFoundException ex) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Actor Not Found", ex);
}
}
@DeleteMapping("/actor/{id}")
public String getActor(@PathVariable("id") int id) {
return actorService.removeActor(id);
}
@PutMapping("/actor/{id}/{name}")
public String updateActorName(@PathVariable("id") int id, @PathVariable("name") String name) {
try {
return actorService.updateActor(id, name);
} catch (ActorNotFoundException ex) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Provide correct Actor Id", ex);
}
}
}
@@ -0,0 +1,13 @@
package com.baeldung.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Actor Not Found")
public class ActorNotFoundException extends Exception {
private static final long serialVersionUID = 1L;
public ActorNotFoundException(String errorMessage) {
super(errorMessage);
}
}
@@ -0,0 +1,35 @@
package com.baeldung.exception;
import java.util.Arrays;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
@Service
public class ActorService {
List<String> actors = Arrays.asList("Jack Nicholson", "Marlon Brando", "Robert De Niro", "Al Pacino", "Tom Hanks");
public String getActor(int index) throws ActorNotFoundException {
if (index >= actors.size()) {
throw new ActorNotFoundException("Actor Not Found in Repsoitory");
}
return actors.get(index);
}
public String updateActor(int index, String actorName) throws ActorNotFoundException {
if (index >= actors.size()) {
throw new ActorNotFoundException("Actor Not Found in Repsoitory");
}
actors.set(index, actorName);
return actorName;
}
public String removeActor(int index) {
if (index >= actors.size()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Actor Not Found in Repsoitory");
}
return actors.remove(index);
}
}
@@ -0,0 +1,14 @@
package com.baeldung.exception;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
@ComponentScan(basePackages = { "com.baeldung.exception" })
public class SpringExceptionApplication {
public static void main(String[] args) {
SpringApplication.run(SpringExceptionApplication.class, args);
}
}
@@ -0,0 +1,23 @@
package com.baeldung.functional;
class Actor {
private String firstname;
private String lastname;
public Actor() {
}
public Actor(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
}
@@ -0,0 +1,11 @@
package com.baeldung.functional;
import java.util.Random;
public class MyService {
public int getRandomNumber() {
return (new Random().nextInt(10));
}
}
@@ -0,0 +1,38 @@
package com.baeldung.jdbc.autogenkey.repository;
import java.sql.PreparedStatement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
@Repository
public class MessageRepositoryJDBCTemplate {
@Autowired
JdbcTemplate jdbcTemplate;
final String INSERT_MESSAGE_SQL = "insert into sys_message (message) values(?) ";
public long insert(final String message) {
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(INSERT_MESSAGE_SQL);
ps.setString(1, message);
return ps;
}, keyHolder);
return (long) keyHolder.getKey();
}
final String SELECT_BY_ID = "select message from sys_message where id = ?";
public String getMessageById(long id) {
return this.jdbcTemplate.queryForObject(SELECT_BY_ID, String.class, new Object[] { id });
}
}
@@ -0,0 +1,29 @@
package com.baeldung.jdbc.autogenkey.repository;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;
@Repository
public class MessageRepositorySimpleJDBCInsert {
SimpleJdbcInsert messageInsert;
@Autowired
public MessageRepositorySimpleJDBCInsert(DataSource dataSource) {
messageInsert = new SimpleJdbcInsert(dataSource).withTableName("sys_message").usingGeneratedKeyColumns("id");
}
public long insert(String message) {
Map<String, Object> parameters = new HashMap<String, Object>(1);
parameters.put("message", message);
Number newId = messageInsert.executeAndReturnKey(parameters);
return (long) newId;
}
}
@@ -0,0 +1,127 @@
package com.baeldung.jsonb;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.json.bind.annotation.JsonbDateFormat;
import javax.json.bind.annotation.JsonbNumberFormat;
import javax.json.bind.annotation.JsonbProperty;
import javax.json.bind.annotation.JsonbTransient;
public class Person {
private int id;
@JsonbProperty("person-name")
private String name;
@JsonbProperty(nillable = true)
private String email;
@JsonbTransient
private int age;
@JsonbDateFormat("dd-MM-yyyy")
private LocalDate registeredDate;
private BigDecimal salary;
public Person() {
}
public Person(int id, String name, String email, int age, LocalDate registeredDate, BigDecimal salary) {
super();
this.id = id;
this.name = name;
this.email = email;
this.age = age;
this.registeredDate = registeredDate;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonbNumberFormat(locale = "en_US", value = "#0.0")
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public LocalDate getRegisteredDate() {
return registeredDate;
}
public void setRegisteredDate(LocalDate registeredDate) {
this.registeredDate = registeredDate;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [id=");
builder.append(id);
builder.append(", name=");
builder.append(name);
builder.append(", email=");
builder.append(email);
builder.append(", age=");
builder.append(age);
builder.append(", registeredDate=");
builder.append(registeredDate);
builder.append(", salary=");
builder.append(salary);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id != other.id)
return false;
return true;
}
}
@@ -0,0 +1,58 @@
package com.baeldung.jsonb;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController("/person")
public class PersonController {
List<Person> personRepository;
@PostConstruct
public void init() {
// @formatter:off
personRepository = new ArrayList<>(Arrays.asList(
new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
new Person(5, "Mark", "mark@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1200)),
new Person(6, "Julia", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000))));
// @formatter:on
}
@GetMapping("/person/{id}")
@ResponseBody
public Person findById(@PathVariable final int id) {
return personRepository.get(id);
}
@PostMapping("/person")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public boolean insertPerson(@RequestBody final Person person) {
return personRepository.add(person);
}
@GetMapping("/person")
@ResponseBody
public List<Person> findAll() {
return personRepository;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.jsonb;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.JsonbHttpMessageConverter;
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
@ComponentScan(basePackages = { "com.baeldung.jsonb" })
public class Spring5Application {
public static void main(String[] args) {
SpringApplication.run(Spring5Application.class, args);
}
@Bean
public HttpMessageConverters customConverters() {
Collection<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
JsonbHttpMessageConverter jsonbHttpMessageConverter = new JsonbHttpMessageConverter();
messageConverters.add(jsonbHttpMessageConverter);
return new HttpMessageConverters(true, messageConverters);
}
}
@@ -0,0 +1,46 @@
package com.baeldung.jupiter;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.util.Assert;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
abstract class MethodParameterFactory {
private MethodParameterFactory() {
}
public static MethodParameter createMethodParameter(Parameter parameter) {
Assert.notNull(parameter, "Parameter must not be null");
Executable executable = parameter.getDeclaringExecutable();
if (executable instanceof Method) {
return new MethodParameter((Method) executable, getIndex(parameter));
}
return new MethodParameter((Constructor<?>) executable, getIndex(parameter));
}
public static SynthesizingMethodParameter createSynthesizingMethodParameter(Parameter parameter) {
Assert.notNull(parameter, "Parameter must not be null");
Executable executable = parameter.getDeclaringExecutable();
if (executable instanceof Method) {
return new SynthesizingMethodParameter((Method) executable, getIndex(parameter));
}
throw new UnsupportedOperationException("Cannot create a SynthesizingMethodParameter for a constructor parameter: " + parameter);
}
private static int getIndex(Parameter parameter) {
Assert.notNull(parameter, "Parameter must not be null");
Executable executable = parameter.getDeclaringExecutable();
Parameter[] parameters = executable.getParameters();
for (int i = 0; i < parameters.length; i++) {
if (parameters[i] == parameter) {
return i;
}
}
throw new IllegalStateException(String.format("Failed to resolve index of parameter [%s] in executable [%s]", parameter, executable.toGenericString()));
}
}
@@ -0,0 +1,44 @@
package com.baeldung.jupiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.context.ApplicationContext;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Optional;
import static org.springframework.core.annotation.AnnotatedElementUtils.hasAnnotation;
abstract class ParameterAutowireUtils {
private ParameterAutowireUtils() {
}
public static boolean isAutowirable(Parameter parameter) {
return ApplicationContext.class.isAssignableFrom(parameter.getType()) || hasAnnotation(parameter, Autowired.class) || hasAnnotation(parameter, Qualifier.class) || hasAnnotation(parameter, Value.class);
}
public static Object resolveDependency(Parameter parameter, Class<?> containingClass, ApplicationContext applicationContext) {
boolean required = findMergedAnnotation(parameter, Autowired.class).map(Autowired::required)
.orElse(true);
MethodParameter methodParameter = (parameter.getDeclaringExecutable() instanceof Method ? MethodParameterFactory.createSynthesizingMethodParameter(parameter) : MethodParameterFactory.createMethodParameter(parameter));
DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required);
descriptor.setContainingClass(containingClass);
return applicationContext.getAutowireCapableBeanFactory()
.resolveDependency(descriptor, null);
}
private static <A extends Annotation> Optional<A> findMergedAnnotation(AnnotatedElement element, Class<A> annotationType) {
return Optional.ofNullable(AnnotatedElementUtils.findMergedAnnotation(element, annotationType));
}
}
@@ -0,0 +1,94 @@
package com.baeldung.jupiter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.TestInstancePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.test.context.TestContextManager;
import org.springframework.util.Assert;
public class SpringExtension implements BeforeAllCallback, AfterAllCallback, TestInstancePostProcessor, BeforeEachCallback, AfterEachCallback, ParameterResolver {
private static final ExtensionContext.Namespace namespace = ExtensionContext.Namespace.create(SpringExtension.class);
@Override
public void beforeAll(ExtensionContext context) throws Exception {
getTestContextManager(context).beforeTestClass();
}
@Override
public void afterAll(ExtensionContext context) throws Exception {
try {
getTestContextManager(context).afterTestClass();
} finally {
context.getStore(namespace)
.remove(context.getTestClass()
.get());
}
}
@Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception {
getTestContextManager(context).prepareTestInstance(testInstance);
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance();
Method testMethod = context.getTestMethod()
.get();
getTestContextManager(context).beforeTestMethod(testInstance, testMethod);
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance();
Method testMethod = context.getTestMethod()
.get();
Throwable testException = context.getExecutionException()
.orElse(null);
getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException);
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
Parameter parameter = parameterContext.getParameter();
Executable executable = parameter.getDeclaringExecutable();
return ((executable instanceof Constructor) && AnnotatedElementUtils.hasAnnotation(executable, Autowired.class)) || ParameterAutowireUtils.isAutowirable(parameter);
}
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
Parameter parameter = parameterContext.getParameter();
Class<?> testClass = extensionContext.getTestClass()
.get();
ApplicationContext applicationContext = getApplicationContext(extensionContext);
return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext);
}
private ApplicationContext getApplicationContext(ExtensionContext context) {
return getTestContextManager(context).getTestContext()
.getApplicationContext();
}
private TestContextManager getTestContextManager(ExtensionContext context) {
Assert.notNull(context, "ExtensionContext must not be null");
Class<?> testClass = context.getTestClass()
.get();
ExtensionContext.Store store = context.getStore(namespace);
return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);
}
}
@@ -0,0 +1,39 @@
package com.baeldung.jupiter;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.annotation.AliasFor;
import org.springframework.test.context.ContextConfiguration;
import java.lang.annotation.*;
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SpringJUnit5Config {
@AliasFor(annotation = ContextConfiguration.class, attribute = "classes")
Class<?>[] value() default {};
@AliasFor(annotation = ContextConfiguration.class)
Class<?>[] classes() default {};
@AliasFor(annotation = ContextConfiguration.class)
String[] locations() default {};
@AliasFor(annotation = ContextConfiguration.class)
Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>[] initializers() default {};
@AliasFor(annotation = ContextConfiguration.class)
boolean inheritLocations() default true;
@AliasFor(annotation = ContextConfiguration.class)
boolean inheritInitializers() default true;
@AliasFor(annotation = ContextConfiguration.class)
String name() default "";
}
@@ -0,0 +1,28 @@
package com.baeldung.jupiter;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Task {
private final String name;
private final int id;
public Task(@JsonProperty("name") String name, @JsonProperty("id") int id) {
this.name = name;
this.id = id;
}
public String getName() {
return this.name;
}
public int getId() {
return this.id;
}
@Override
public String toString() {
return "Task{" + "name='" + name + '\'' + ", id=" + id + '}';
}
}
@@ -0,0 +1,19 @@
package com.baeldung.jupiter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
public class TestConfig {
@Bean
static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
Task taskName() {
return new Task("taskName", 1);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.persistence;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import java.util.stream.IntStream;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.baeldung.web.Foo;
@Component
public class DataSetupBean implements InitializingBean {
@Autowired
private FooRepository repo;
//
@Override
public void afterPropertiesSet() throws Exception {
IntStream.range(1, 20)
.forEach(i -> repo.save(new Foo(randomAlphabetic(8))));
}
}
@@ -0,0 +1,9 @@
package com.baeldung.persistence;
import com.baeldung.web.Foo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface FooRepository extends JpaRepository<Foo, Long>, JpaSpecificationExecutor<Foo> {
}
@@ -0,0 +1,61 @@
package com.baeldung.restdocs;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/crud")
public class CRUDController {
@GetMapping
public List<CrudInput> read(@RequestBody @Valid CrudInput crudInput) {
List<CrudInput> returnList = new ArrayList<>();
returnList.add(crudInput);
return returnList;
}
@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public HttpHeaders save(@RequestBody @Valid CrudInput crudInput) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(linkTo(CRUDController.class).slash(crudInput.getId()).toUri());
return httpHeaders;
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
HttpHeaders delete(@PathVariable("id") long id) {
return new HttpHeaders();
}
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.ACCEPTED)
void put(@PathVariable("id") long id, @RequestBody CrudInput crudInput) {
}
@PatchMapping("/{id}")
public List<CrudInput> patch(@PathVariable("id") long id, @RequestBody CrudInput crudInput) {
List<CrudInput> returnList = new ArrayList<CrudInput>();
crudInput.setId(id);
returnList.add(crudInput);
return returnList;
}
}
@@ -0,0 +1,66 @@
package com.baeldung.restdocs;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CrudInput {
@NotNull
private long id;
@NotBlank
private String title;
private String body;
private List<URI> tagUris;
@JsonCreator
public CrudInput(@JsonProperty("id") long id, @JsonProperty("title") String title, @JsonProperty("body") String body, @JsonProperty("tags") List<URI> tagUris) {
this.id=id;
this.title = title;
this.body = body;
this.tagUris = tagUris == null ? Collections.<URI> emptyList() : tagUris;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setBody(String body) {
this.body = body;
}
public void setTagUris(List<URI> tagUris) {
this.tagUris = tagUris;
}
@JsonProperty("tags")
public List<URI> getTagUris() {
return this.tagUris;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.restdocs;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/")
public class IndexController {
@GetMapping
public ResourceSupport index() {
ResourceSupport index = new ResourceSupport();
index.add(linkTo(CRUDController.class).withRel("crud"));
return index;
}
}
@@ -0,0 +1,13 @@
package com.baeldung.restdocs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class SpringRestDocsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRestDocsApplication.class, args);
}
}
@@ -0,0 +1,84 @@
package com.baeldung.web;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Foo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
public Foo() {
super();
}
public Foo(final String name) {
super();
this.name = name;
}
public Foo(final long id, final String name) {
super();
this.id = id;
this.name = name;
}
// API
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Foo [name=" + name + "]";
}
}
@@ -0,0 +1,59 @@
package com.baeldung.web;
import com.baeldung.persistence.FooRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.PostConstruct;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.List;
@RestController("/foos")
public class FooController {
@PostConstruct
public void init(){
System.out.println("test");
}
@Autowired
private FooRepository repo;
// API - read
@GetMapping("/foos/{id}")
@ResponseBody
@Validated
public Foo findById(@PathVariable @Min(0) final long id) {
return repo.findById(id)
.orElse(null);
}
@GetMapping
@ResponseBody
public List<Foo> findAll() {
return repo.findAll();
}
@GetMapping(params = { "page", "size" })
@ResponseBody
@Validated
public List<Foo> findPaginated(@RequestParam("page") @Min(0) final int page, @Max(100) @RequestParam("size") final int size) {
return repo.findAll(PageRequest.of(page, size))
.getContent();
}
// API - write
@PutMapping("/foos/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Foo update(@PathVariable("id") final String id, @RequestBody final Foo foo) {
return foo;
}
}
@@ -0,0 +1,15 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<context:component-scan base-package="com.baeldung.annotationconfigvscomponentscan.components" />
<bean id="accountService" class="com.baeldung.annotationconfigvscomponentscan.components.AccountService"></bean>
<bean id="userService" class="com.baeldung.annotationconfigvscomponentscan.components.UserService">
<!-- If we have <context:annotation-config/> on top, then we don't need to set the properties(dependencies) in XML. -->
<!-- <property name="accountService" ref="accountService"></property> -->
</bean>
</beans>
@@ -0,0 +1,3 @@
server.port=8081
logging.level.root=INFO
@@ -0,0 +1,9 @@
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.datasource.initialize=true
spring.datasource.schema=classpath:autogenkey-schema.sql
@@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS sys_message (
id bigint(20) NOT NULL AUTO_INCREMENT,
message varchar(100) NOT NULL,
PRIMARY KEY (id)
);
@@ -0,0 +1 @@
hello
@@ -0,0 +1 @@
test
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
+21
View File
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Spring Functional Application</display-name>
<servlet>
<servlet-name>functional</servlet-name>
<servlet-class>com.baeldung.functional.RootServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>functional</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
@@ -0,0 +1,29 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Example1IntegrationTest {
@Test
public void test1a() {
block(3000);
}
@Test
public void test1b() {
block(3000);
}
public static void block(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
}
}
@@ -0,0 +1,29 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Example2IntegrationTest {
@Test
public void test1a() {
block(3000);
}
@Test
public void test1b() {
block(3000);
}
public static void block(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
System.out.println("Thread Interrupted");
}
}
}
@@ -0,0 +1,24 @@
package com.baeldung;
import org.junit.Test;
import org.junit.experimental.ParallelComputer;
import org.junit.runner.Computer;
import org.junit.runner.JUnitCore;
public class ParallelIntegrationTest {
@Test
public void runTests() {
final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
JUnitCore.runClasses(new Computer(), classes);
}
@Test
public void runTestsInParallel() {
final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
JUnitCore.runClasses(new ParallelComputer(true, true), classes);
}
}
@@ -0,0 +1,18 @@
package com.baeldung;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@Ignore
public class Spring5ApplicationIntegrationTest {
@Test
public void contextLoads() {
}
}
@@ -0,0 +1,52 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = Spring5JUnit4ConcurrentIntegrationTest.SimpleConfiguration.class)
public class Spring5JUnit4ConcurrentIntegrationTest implements ApplicationContextAware, InitializingBean {
@Configuration
public static class SimpleConfiguration {
}
private ApplicationContext applicationContext;
private boolean beanInitialized = false;
@Override
public final void afterPropertiesSet() throws Exception {
this.beanInitialized = true;
}
@Override
public final void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Test
public final void verifyApplicationContextSet() throws InterruptedException {
TimeUnit.SECONDS.sleep(2);
assertNotNull("The application context should have been set due to ApplicationContextAware semantics.", this.applicationContext);
}
@Test
public final void verifyBeanInitialized() throws InterruptedException {
TimeUnit.SECONDS.sleep(2);
assertTrue("This test bean should have been initialized due to InitializingBean semantics.", this.beanInitialized);
}
}
@@ -0,0 +1,23 @@
package com.baeldung;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baeldung.annotationconfigvscomponentscan.components.AccountService;
import com.baeldung.annotationconfigvscomponentscan.components.UserService;
public class SpringXMLConfigurationIntegrationTest {
@Test
public void givenContextAnnotationConfigOrContextComponentScan_whenDependenciesAndBeansAnnotated_thenNoXMLNeeded() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:annotationconfigvscomponentscan-beans.xml");
UserService userService = context.getBean(UserService.class);
AccountService accountService = context.getBean(AccountService.class);
Assert.assertNotNull(userService);
Assert.assertNotNull(accountService);
Assert.assertNotNull(userService.getAccountService());
}
}
@@ -0,0 +1,42 @@
package com.baeldung.functional;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.support.GenericWebApplicationContext;
import com.baeldung.Spring5Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Spring5Application.class)
public class BeanRegistrationIntegrationTest {
@Autowired
private GenericWebApplicationContext context;
@Test
public void whenRegisterBean_thenOk() {
context.registerBean(MyService.class, () -> new MyService());
MyService myService = (MyService) context.getBean("com.baeldung.functional.MyService");
assertTrue(myService.getRandomNumber() < 10);
}
@Test
public void whenRegisterBeanWithName_thenOk() {
context.registerBean("mySecondService", MyService.class, () -> new MyService());
MyService mySecondService = (MyService) context.getBean("mySecondService");
assertTrue(mySecondService.getRandomNumber() < 10);
}
@Test
public void whenRegisterBeanWithCallback_thenOk() {
context.registerBean("myCallbackService", MyService.class, () -> new MyService(), bd -> bd.setAutowireCandidate(false));
MyService myCallbackService = (MyService) context.getBean("myCallbackService");
assertTrue(myCallbackService.getRandomNumber() < 10);
}
}
@@ -0,0 +1,12 @@
package com.baeldung.hikari;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApplicationWithHikariConnectionPool {
public static void main(String[] args) {
SpringApplication.run(ApplicationWithHikariConnectionPool.class, args);
}
}
@@ -0,0 +1,26 @@
package com.baeldung.hikari;
import static org.junit.Assert.*;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class HikariIntegrationTest {
@Autowired
private DataSource dataSource;
@Test
public void hikariConnectionPoolIsConfigured() {
assertEquals("com.zaxxer.hikari.HikariDataSource", dataSource.getClass()
.getName());
}
}
@@ -0,0 +1,55 @@
package com.baeldung.jdbc.autogenkey;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate;
import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert;
@RunWith(SpringRunner.class)
@Ignore
public class GetAutoGenKeyByJDBCIntTest {
@Configuration
@EnableAutoConfiguration
@PropertySource("classpath:autogenkey-db.properties")
@ComponentScan(basePackages = { "com.baeldung.jdbc.autogenkey.repository" })
public static class SpringConfig {
}
@Autowired
MessageRepositorySimpleJDBCInsert messageRepositorySimpleJDBCInsert;
@Autowired
MessageRepositoryJDBCTemplate messageRepositoryJDBCTemplate;
final String MESSAGE_CONTENT = "Test";
@Test
public void insertJDBC_whenLoadMessageByKey_thenGetTheSameMessage() {
long key = messageRepositoryJDBCTemplate.insert(MESSAGE_CONTENT);
String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key);
assertEquals(MESSAGE_CONTENT, loadedMessage);
}
@Test
public void insertSimpleInsert_whenLoadMessageKey_thenGetTheSameMessage() {
long key = messageRepositorySimpleJDBCInsert.insert(MESSAGE_CONTENT);
String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key);
assertEquals(MESSAGE_CONTENT, loadedMessage);
}
}
@@ -0,0 +1,41 @@
package com.baeldung.jsonb;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.time.LocalDate;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Spring5Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Ignore
public class JsonbIntegrationTest {
@Autowired
private TestRestTemplate template;
@Test
public void givenId_whenUriIsPerson_thenGetPerson() {
ResponseEntity<Person> response = template
.getForEntity("/person/1", Person.class);
Person person = response.getBody();
assertTrue(person.equals(new Person(2, "Jhon", "jhon1@test.com", 0, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500.0))));
}
@Test
public void whenSendPostAPerson_thenGetOkStatus() {
ResponseEntity<Boolean> response = template.withBasicAuth("user","password").
postForEntity("/person", "{\"birthDate\":\"07-09-2017\",\"email\":\"jhon1@test.com\",\"person-name\":\"Jhon\",\"id\":10}", Boolean.class);
assertTrue(response.getBody());
}
}
@@ -0,0 +1,18 @@
package com.baeldung.jupiter;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.test.context.junit.jupiter.EnabledIf;
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@EnabledIf(
expression = "#{systemProperties['java.version'].startsWith('1.8')}",
reason = "Enabled on Java 8"
)
public @interface EnabledOnJava8 {
}
@@ -0,0 +1,50 @@
package com.baeldung.jupiter;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.DisabledIf;
import org.springframework.test.context.junit.jupiter.EnabledIf;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig(Spring5EnabledAnnotationIntegrationTest.Config.class)
@TestPropertySource(properties = { "tests.enabled=true" })
public class Spring5EnabledAnnotationIntegrationTest {
@Configuration
static class Config {
}
@EnabledIf("true")
@Test
void givenEnabledIfLiteral_WhenTrue_ThenTestExecuted() {
assertTrue(true);
}
@EnabledIf(expression = "${tests.enabled}", loadContext = true)
@Test
void givenEnabledIfExpression_WhenTrue_ThenTestExecuted() {
assertTrue(true);
}
@EnabledIf("#{systemProperties['java.version'].startsWith('1.8')}")
@Test
void givenEnabledIfSpel_WhenTrue_ThenTestExecuted() {
assertTrue(true);
}
@EnabledOnJava8
@Test
void givenEnabledOnJava8_WhenTrue_ThenTestExecuted() {
assertTrue(true);
}
@DisabledIf("#{systemProperties['java.version'].startsWith('1.7')}")
@Test
void givenDisabledIf_WhenTrue_ThenTestNotExecuted() {
assertTrue(true);
}
}
@@ -0,0 +1,37 @@
package com.baeldung.jupiter;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@SpringJUnit5Config(TestConfig.class)
@DisplayName("@SpringJUnit5Config Tests")
class Spring5JUnit5ComposedAnnotationIntegrationTest {
@Autowired
private Task task;
@Autowired
private List<Task> tasks;
@Test
@DisplayName("ApplicationContext injected into method")
void givenAMethodName_whenInjecting_thenApplicationContextInjectedIntoMethod(ApplicationContext applicationContext) {
assertNotNull(applicationContext, "ApplicationContext should have been injected into method by Spring");
assertEquals(this.task, applicationContext.getBean("taskName", Task.class));
}
@Test
@DisplayName("Spring @Beans injected into fields")
void givenAnObject_whenInjecting_thenSpringBeansInjected() {
assertNotNull(task, "Task should have been @Autowired by Spring");
assertEquals("taskName", task.getName(), "Task's name");
assertEquals(1, tasks.size(), "Number of Tasks in context");
}
}
@@ -0,0 +1,24 @@
package com.baeldung.jupiter;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = TestConfig.class)
class Spring5JUnit5IntegrationTest {
@Autowired
private Task task;
@Test
void givenAMethodName_whenInjecting_thenApplicationContextInjectedIntoMetho(ApplicationContext applicationContext) {
assertNotNull(applicationContext, "ApplicationContext should have been injected by Spring");
assertEquals(this.task, applicationContext.getBean("taskName", Task.class));
}
}
@@ -0,0 +1,25 @@
package com.baeldung.jupiter;
import com.baeldung.Example1IntegrationTest;
import com.baeldung.Example2IntegrationTest;
import org.junit.experimental.ParallelComputer;
import org.junit.jupiter.api.Test;
import org.junit.runner.Computer;
import org.junit.runner.JUnitCore;
class Spring5JUnit5ParallelIntegrationTest {
@Test
void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() {
final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
JUnitCore.runClasses(new ParallelComputer(true, true), classes);
}
@Test
void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() {
final Class<?>[] classes = { Example1IntegrationTest.class, Example2IntegrationTest.class };
JUnitCore.runClasses(new Computer(), classes);
}
}
@@ -0,0 +1,31 @@
package com.baeldung.jupiter;
import org.junit.jupiter.api.Test;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
class Spring5Java8NewFeaturesIntegrationTest {
@FunctionalInterface
public interface FunctionalInterfaceExample<Input, Result> {
Result reverseString(Input input);
}
public class StringUtils {
FunctionalInterfaceExample<String, String> functionLambdaString = s -> Pattern.compile(" +")
.splitAsStream(s)
.map(word -> new StringBuilder(word).reverse())
.collect(Collectors.joining(" "));
}
@Test
void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString() throws Exception {
Supplier<StringUtils> stringUtilsSupplier = StringUtils::new;
assertEquals(stringUtilsSupplier.get().functionLambdaString.reverseString("hello"), "olleh");
}
}
@@ -0,0 +1,33 @@
package com.baeldung.jupiter;
import static org.junit.Assert.assertNotNull;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @SpringJUnitConfig(SpringJUnitConfigTest.Config.class) is equivalent to:
*
* @ExtendWith(SpringExtension.class)
* @ContextConfiguration(classes = SpringJUnitConfigTest.Config.class )
*
*/
@SpringJUnitConfig(SpringJUnitConfigIntegrationTest.Config.class)
public class SpringJUnitConfigIntegrationTest {
@Configuration
static class Config {
}
@Autowired
private ApplicationContext applicationContext;
@Test
void givenAppContext_WhenInjected_ThenItShouldNotBeNull() {
assertNotNull(applicationContext);
}
}
@@ -0,0 +1,34 @@
package com.baeldung.jupiter;
import static org.junit.Assert.assertNotNull;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.web.context.WebApplicationContext;
/**
* @SpringJUnitWebConfig(SpringJUnitWebConfigTest.Config.class) is equivalent to:
*
* @ExtendWith(SpringExtension.class)
* @WebAppConfiguration
* @ContextConfiguration(classes = SpringJUnitWebConfigTest.Config.class )
*
*/
@SpringJUnitWebConfig(SpringJUnitWebConfigIntegrationTest.Config.class)
public class SpringJUnitWebConfigIntegrationTest {
@Configuration
static class Config {
}
@Autowired
private WebApplicationContext webAppContext;
@Test
void givenWebAppContext_WhenInjected_ThenItShouldNotBeNull() {
assertNotNull(webAppContext);
}
}
@@ -0,0 +1,180 @@
package com.baeldung.restdocs;
import com.baeldung.restdocs.CrudInput;
import com.baeldung.restdocs.SpringRestDocsApplication;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.hateoas.MediaTypes;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.restdocs.constraints.ConstraintDescriptions;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.util.HashMap;
import java.util.Map;
import static java.util.Collections.singletonList;
import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName;
import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.util.StringUtils.collectionToDelimitedString;
import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.pathParameters;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringRestDocsApplication.class)
public class ApiDocumentationJUnit4IntegrationTest {
@Rule
public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets");
@Autowired
private WebApplicationContext context;
@Autowired
private ObjectMapper objectMapper;
private MockMvc mockMvc;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation))
.alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())))
.build();
}
@Test
public void indexExample() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andDo(document("index-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links(linkWithRel("crud").description("The CRUD resource")), responseFields(subsectionWithPath("_links").description("Links to other resources")),
responseHeaders(headerWithName("Content-Type").description("The Content-Type of the payload, e.g. `application/hal+json`"))));
}
@Test
public void crudGetExample() throws Exception {
Map<String, Object> crud = new HashMap<>();
crud.put("id", 1L);
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getHeader("Location");
crud.put("tags", singletonList(tagLocation));
ConstraintDescriptions desc = new ConstraintDescriptions(CrudInput.class);
this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk())
.andDo(document("crud-get-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")),
fieldWithPath("title").description("The title of the input"), fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs"))));
}
@Test
public void crudCreateExample() throws Exception {
Map<String, Object> crud = new HashMap<>();
crud.put("id", 2L);
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
String tagLocation = this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getHeader("Location");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isCreated())
.andDo(document("crud-create-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input"), fieldWithPath("title").description("The title of the input"),
fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs"))));
}
@Test
public void crudDeleteExample() throws Exception {
this.mockMvc.perform(delete("/crud/{id}", 10))
.andExpect(status().isOk())
.andDo(document("crud-delete-example", pathParameters(parameterWithName("id").description("The id of the input to delete"))));
}
@Test
public void crudPatchExample() throws Exception {
Map<String, String> tag = new HashMap<>();
tag.put("name", "PATCH");
String tagLocation = this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(tag)))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getHeader("Location");
Map<String, Object> crud = new HashMap<>();
crud.put("title", "Sample Model Patch");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk());
}
@Test
public void crudPutExample() throws Exception {
Map<String, String> tag = new HashMap<>();
tag.put("name", "PUT");
String tagLocation = this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(tag)))
.andExpect(status().isAccepted())
.andReturn()
.getResponse()
.getHeader("Location");
Map<String, Object> crud = new HashMap<>();
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isAccepted());
}
@Test
public void contextLoads() {
}
}
@@ -0,0 +1,173 @@
package com.baeldung.restdocs;
import static java.util.Collections.singletonList;
import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName;
import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.restdocs.request.RequestDocumentation.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.util.StringUtils.collectionToDelimitedString;
import java.util.HashMap;
import java.util.Map;
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.hateoas.MediaTypes;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.restdocs.RestDocumentationExtension;
import org.springframework.restdocs.constraints.ConstraintDescriptions;
import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.restdocs.CrudInput;
import com.baeldung.restdocs.SpringRestDocsApplication;
import com.fasterxml.jackson.databind.ObjectMapper;
@ExtendWith({ RestDocumentationExtension.class, SpringExtension.class })
@SpringBootTest(classes = SpringRestDocsApplication.class)
public class ApiDocumentationJUnit5IntegrationTest {
@Autowired
private ObjectMapper objectMapper;
private MockMvc mockMvc;
@BeforeEach
public void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.apply(documentationConfiguration(restDocumentation))
.alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())))
.build();
}
@Test
public void indexExample() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andDo(document("index-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links(linkWithRel("crud").description("The CRUD resource")), responseFields(subsectionWithPath("_links").description("Links to other resources")),
responseHeaders(headerWithName("Content-Type").description("The Content-Type of the payload, e.g. `application/hal+json`"))));
}
@Test
public void crudGetExample() throws Exception {
Map<String, Object> crud = new HashMap<>();
crud.put("id", 1L);
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getHeader("Location");
crud.put("tags", singletonList(tagLocation));
ConstraintDescriptions desc = new ConstraintDescriptions(CrudInput.class);
this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk())
.andDo(document("crud-get-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")),
fieldWithPath("title").description("The title of the input"), fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs"))));
}
@Test
public void crudCreateExample() throws Exception {
Map<String, Object> crud = new HashMap<>();
crud.put("id", 2L);
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
String tagLocation = this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getHeader("Location");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isCreated())
.andDo(document("crud-create-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input"), fieldWithPath("title").description("The title of the input"),
fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs"))));
}
@Test
public void crudDeleteExample() throws Exception {
this.mockMvc.perform(delete("/crud/{id}", 10))
.andExpect(status().isOk())
.andDo(document("crud-delete-example", pathParameters(parameterWithName("id").description("The id of the input to delete"))));
}
@Test
public void crudPatchExample() throws Exception {
Map<String, String> tag = new HashMap<>();
tag.put("name", "PATCH");
String tagLocation = this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(tag)))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getHeader("Location");
Map<String, Object> crud = new HashMap<>();
crud.put("title", "Sample Model Patch");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk());
}
@Test
public void crudPutExample() throws Exception {
Map<String, String> tag = new HashMap<>();
tag.put("name", "PUT");
String tagLocation = this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(tag)))
.andExpect(status().isAccepted())
.andReturn()
.getResponse()
.getHeader("Location");
Map<String, Object> crud = new HashMap<>();
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isAccepted());
}
@Test
public void contextLoads() {
}
}
@@ -0,0 +1,17 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.Spring5Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Spring5Application.class)
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
@@ -0,0 +1,17 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.Spring5Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Spring5Application.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
# Pattern of log message for console appender
<Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</layout>
</appender>
<logger name="org.springframework" level="INFO" />
<root level="INFO">
<appender-ref ref="stdout" />
</root>
</configuration>