Spring Boot Test unable to autowired MockMvc

Spring Boot integeration test, but unable to @Autowired MockMvc P.S Tested with Spring Boot 2.1.2.RELEASE BookControllerTest.java package com.mkyong; 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.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class BookControllerTest { @Autowired …

Read more

Spring REST Validation Example

In this article, we will enhance the previous Spring REST Hello World example, by adding bean validation and custom validator. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Maven 3 Java 8 1. Controller Review the previous REST Controller again : BookController.java package com.mkyong; import com.mkyong.error.BookNotFoundException; import com.mkyong.error.BookUnSupportedFieldPatchException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import …

Read more

Spring REST Hello World Example

In this article, we will show you how to develop a Spring Boot REST style web service to handle CRUD operations from a H2 In-memory database. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Spring Data JPA 2.1.4.RELEASE H2 In-memory Database 1.4.197 Tomcat Embed 9.0.14 JUnit 4.12 Maven 3 Java 8 1. Project Directory 2. …

Read more

Mockito – when() requires an argument which has to be ‘a method call on a mock’

Run the following Spring Boot + JUnit 5 + Mockito integration test. package com.mkyong.core.services; import com.mkyong.core.repository.HelloRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; @SpringBootTest public class HelloServiceMockTest { @Mock private HelloRepository helloRepository; @InjectMocks // auto inject helloRepository private HelloService helloService = new HelloServiceImpl(); @BeforeEach …

Read more

Spring Boot + JUnit 5 + Mockito

In this article, we will show you how to do Spring Boot 2 integration test with JUnit 5, and also Mockito. Spring Boot 2.1.2.RELEASE JUnit 5 Mockito 2 Maven 3 In short, exclude junit4 from spring-boot-starter-test, and include the JUnit 5 jupiter engine manually, done. Let see the following Spring boot MVC web application, and …

Read more

Spring Boot WebFlux + Server-sent events example

In this article, we will show you how to develop a reactive web application, using Server-sent events Spring Boot 2.1.2.RELEASE Spring WebFlux 5.1.4.RELEASE Thymeleaf 3.0.11.RELEASE JUnit 5.3.2 Maven 3 In Spring, returns JSON and header MediaType.TEXT_EVENT_STREAM_VALUE @RestController public class CommentController { @GetMapping(path = "/comment/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<Comment> feed() { //… } } In …

Read more

Spring Boot WebFlux + Thymeleaf reactive example

In this article, we will show you how to develop a reactive web application. Spring Boot 2.1.2.RELEASE Spring WebFlux 5.1.4.RELEASE Thymeleaf 3.0.11.RELEASE Maven 3 Spring Boot will configure everything, and the key is using the Thymeleaf ReactiveDataDriverContextVariable to enable the data-driven mode in Thymeleaf template. @RequestMapping("/") public String index(final Model model) { // data streaming, …

Read more

Spring WebFlux Test – Timeout on blocking read for 5000 MILLISECONDS

Test a Spring Webflux endpoint with the WebTestClient, and hits the following error messages. Is this possible to increase the timeout? java.lang.IllegalStateException: Timeout on blocking read for 5000 MILLISECONDS at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:117) at reactor.core.publisher.Mono.block(Mono.java:1524) at org.springframework.test.web.reactive.server.ExchangeResult.formatBody(ExchangeResult.java:247) at org.springframework.test.web.reactive.server.ExchangeResult.toString(ExchangeResult.java:216) at java.base/java.lang.String.valueOf(String.java:2788) at java.base/java.lang.StringBuilder.append(StringBuilder.java:135) at org.springframework.test.web.reactive.server.ExchangeResult.assertWithDiagnostics(ExchangeResult.java:200) Solution By default, the WebTestClient will be timeout after 5 seconds. We …

Read more

Spring Boot + Hibernate Search example

Here we will create a Spring Boot web application example with Hibernate Search + Thymeleaf template engine, and deploy it as a WAR to Wildfly 10.1. Technologies used: Spring Boot 1.5.6.RELEASE Java 8 Hibernate Search 5.6.1.Final Embedded Tomcat, Wildfly 8.1 Final & 10.1 Final 1. Project Structure A standard Maven project structure 1. Project Dependencies …

Read more

Spring Boot and Mustache – default value

In Spring Boot + Mustache template environment, if we didn’t assign a value to a {{variable}} on the Mustache’s page, the jmustache will throws the following error messages : com.samskivert.mustache.MustacheException$Context: No method or field with name ‘variable’ on line xx at com.samskivert.mustache.Template.checkForMissing(Template.java:316) ~[jmustache-1.13.jar:na] at com.samskivert.mustache.Template.getValue(Template.java:224) ~[jmustache-1.13.jar:na] at com.samskivert.mustache.Template.getValueOrDefault(Template.java:269) ~[jmustache-1.13.jar:na] P.S Tested with Spring Boot 1.5.2.RELEASE …

Read more

Spring Boot Hello World Example – Mustache

A Spring Boot web application example, using embedded Tomcat + Mustache template engine, and package as an executable JAR file. Technologies used : Spring Boot 1.5.2.RELEASE Spring 4.3.7.RELEASE jmustache 1.13 Thymeleaf 2.1.5.RELEASE Tomcat Embed 8.5.11 Maven 3 Java 8 Note Spring Boot uses jmustache to integrate Mustache as template engine. 1. Project Directory 2. Project …

Read more

Spring Boot + Spring Data + Elasticsearch example

In this article, we will discuss about “How to create a Spring Boot + Spring Data + Elasticsearch Example”. Tools used in this article : Spring Boot 1.5.1.RELEASE Spring Boot Starter Data Elasticsearch 1.5.1.RELEASE Spring Data Elasticsearch 2.10.RELEASE Elasticsearch 2.4.4 Maven Java 8 Note SpringBoot 1.5.1.RELEASE and Spring Data Elasticsearch 2.10.RELEASE supports only ElasticSearch 2.4.0. …

Read more

Spring Boot – Profile based properties and yaml example

In Spring Boot, it picks .properties or .yaml files in the following sequences : application-{profile}.properties and YAML variants application.properties and YAML variants Note For detail, sequence and order, please refer to this official Externalized Configuration documentation. Tested : Spring Boot 2.1.2.RELEASE Maven 3 1. Project Structure A standard Maven project structure. 2. @ConfigurationProperties Read the …

Read more

Spring Boot Profiles example

In this article, we will show you how to use @Profile in Spring Boot and also how to test it. Tested with : Spring Boot 2.1.2.RELEASE Maven 3 1. Project Structure A standard Maven project structure. 2. Project Dependency pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>spring-boot-profile</artifactId> <packaging>jar</packaging> <name>Spring Boot Profiles Example</name> …

Read more

Spring Boot Test – How to disable DEBUG and INFO logs

Run the Spring Boot integration test or unit test, many annoying DEBUG and INFO logs are displayed in the console. P.S Tested with Spring Boot 2 Console 2019-03-04 13:15:25.151 INFO — [ main] .b.t.c.SpringBootTestContextBootstrapper : 2019-03-04 13:15:25.157 INFO — [ main] o.s.t.c.support.AbstractContextLoader : 2019-03-04 13:15:25.158 INFO — [ main] t.c.s.AnnotationConfigContextLoaderUtils : 2019-03-04 13:15:25.298 INFO — …

Read more

Spring Boot + Spring Data JPA + Java 8 date and time (JSR310)

In Spring Boot + Spring Data JPA application, to support the JSR310 java.time.* APIs, we need to register this Jsr310JpaConverters manually. import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters; @EntityScan( basePackageClasses = {Application.class, Jsr310JpaConverters.class} ) @SpringBootApplication public class Application { //… } P.S Tested with Spring Boot 1.5.1.RELEASE, Spring Data JPA 1.11.0.RELEASE 1. Full Example 1.1 A model contains …

Read more

How to display all beans loaded by Spring Boot

In Spring Boot, you can use appContext.getBeanDefinitionNames() to get all the beans loaded by the Spring container. 1. CommandLineRunner as Interface Application.java package com.mkyong; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import java.util.Arrays; @SpringBootApplication public class Application implements CommandLineRunner { @Autowired private ApplicationContext appContext; public static void main(String[] args) throws Exception { …

Read more

Spring Boot + Spring Data MongoDB example

In this article, we will show you how to create a Spring Boot + Spring Data MongoDB application, using Gradle build tool. Spring Boot 1.5.1.RELEASE MongoDB Gradle Java 8 1. Project Structure A standard project structure. 2. Project Dependency 2.1 A Gradle build file. build.gradle buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.1.RELEASE") } …

Read more

Spring Boot – Show Hibernate SQL query

Add the following lines in application.properties to log the Hibernate SQL query. application.properties #show sql statement logging.level.org.hibernate.SQL=debug #show sql values logging.level.org.hibernate.type.descriptor.sql=trace 1. org.hibernate.SQL=debug application.properties logging.level.org.hibernate.SQL=debug 1.1 Select query. Console 2017-02-23 21:36:42 DEBUG org.hibernate.SQL – select customer0_.id as id1_0_, customer0_.created_date as created_date2_0_, customer0_.email as email3_0_, customer0_.name as name4_0_ from customer customer0_ 2. org.hibernate.type.descriptor.sql=trace application.properties logging.level.org.hibernate.SQL=debug logging.level.org.hibernate.type.descriptor.sql=trace …

Read more

Spring Boot + Spring Data JPA + Oracle example

In this article, we will show you how to create a Spring Boot + Spring Data JPA + Oracle + HikariCP connection pool example. Tools used in this article : Spring Boot 1.5.1.RELEASE Spring Data 1.13.0.RELEASE Hibernate 5 Oracle database 11g express Oracle JDBC driver ojdbc7.jar HikariCP 2.6 Maven Java 8 1. Project Structure A …

Read more

Spring Boot JDBC + Oracle database + Commons DBCP2 example

In this article, we will show you how to create a Spring Boot JDBC application + Oracle database + Commons DBCP2 connection pool. Tools used in this article : Spring Boot 1.5.1.RELEASE Oracle database 11g express Oracle JDBC driver ojdbc7.jar Commons DBCP2 2.1.1 Maven Java 8 Note Related – Spring Boot JDBC + MySQL + …

Read more

Spring Boot – How to know which connection pool is used?

In Spring Boot, @Autowired a javax.sql.DataSource, and you will know which database connection pool is using in the current running application. 1. Test Default Spring Boot example to print a javax.sql.DataSource Note Read this official Spring Boot doc – Connection to a production database, to understand the algorithm for choosing a DataSource implementations – Tomcat …

Read more

Spring Boot non-web application example

In Spring Boot, to create a non-web application, implements CommandLineRunner and override the run method, for example : import org.springframework.boot.CommandLineRunner; @SpringBootApplication public class SpringBootConsoleApplication implements CommandLineRunner { public static void main(String[] args) throws Exception { SpringApplication.run(SpringBootConsoleApplication.class, args); } //access command line arguments @Override public void run(String… args) throws Exception { //do something } } 1. …

Read more

Spring Boot JDBC + MySQL + HikariCP example

In this article, we will show you how to create a Spring Boot JDBC application + MySQL and HikariCP. Tools used in this article : Spring Boot 1.5.1.RELEASE MySQL 5.7.x HikariCP 2.6 Maven Java 8 Note Related – Spring Boot JDBC + Oracle database + Commons DBCP2 example 1. Project Structure A standard Maven project …

Read more

Spring Boot Ajax example

This article will show you how to use jQuery.ajax to send a HTML form request to a Spring REST API and return a JSON response. Tools used : Spring Boot 1.5.1.RELEASE Spring 4.3.6.RELEASE Maven 3 jQuery Bootstrap 3 Note You may interest at this classic Spring MVC Ajax example 1. Project Structure A standard Maven …

Read more

Spring Boot file upload example – Ajax and REST

This article shows you how to upload files in Spring Boot web application (REST structure), using Ajax requests. Tools used in this article : Spring Boot 1.4.3.RELEASE Spring 4.3.5.RELEASE Thymeleaf jQuery (webjars) Maven Embedded Tomcat 8.5.6 Google Chrome Browser (Network Inspect) 1. Project Structure A standard Maven project structure. 2. Project Dependency Declares an extra …

Read more

Spring Boot – Configure maxSwallowSize in embedded Tomcat

In Spring Boot, you can’t configure the embedded Tomcat maxSwallowSize via the common application properties, there is no option like server.tomcat.*.maxSwallowSize Solution To fix it, you need to declare a TomcatEmbeddedServletContainerFactory bean and configure the maxSwallowSize like this : //… import org.apache.coyote.http11.AbstractHttp11Protocol; import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; private int maxUploadSizeInMb = 10 * 1024 * 1024; …

Read more

Spring Boot file upload example

This article shows you how to upload a file in Spring Boot web application. Tools used : Spring Boot 1.4.3.RELEASE Spring 4.3.5.RELEASE Thymeleaf Maven Embedded Tomcat 8.5.6 1. Project Structure A standard project structure. 2. Project Dependency Spring boot dependencies, no need extra library for file upload. pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mkyong</groupId> …

Read more

Spring Boot – Deploy WAR file to Tomcat

In this article, we will show you how to create a Spring Boot traditional WAR file and deploy to a Tomcat servlet container. In Spring Boot, to create a WAR for deployment, we need 3 steps: Extends SpringBootServletInitializer Marked the embedded servlet container as provided. Update packaging to war Tested with Spring Boot 2.1.2.RELEASE Tomcat …

Read more

Spring Boot @ConfigurationProperties example

Spring Boot @ConfigurationProperties lets developers map or bind the entire external configuration values in .properties or .yml files to Java objects. Table of contents: 1. Access a single value using @Value 2. @ConfigurationProperties 3. Add JSR303 Validation 3.1 Add JSR 303 dependencies 3.2 @ConfigurationProperties and @Validated 4. Testing @ConfigurationProperties 5. Download Source Code 6. References …

Read more

Intellij IDEA – Spring boot reload static file is not working

In Eclipse, just include the Spring Boot Dev Tools dependency, then the hot swapping and static file reload will be enabled magically. For Intellij IDE, we need extra steps to enable it. 1. Spring Boot Dev Tools With Spring Boot Dev Tools enabled : Any changes to views or resources can be seen in the …

Read more

Spring Boot – Which main class to start

If Spring Boot project contains multiple main classes, Spring Boot will fail to start or packag for deployment. Terminal $ mvn package #or $ mvn spring-boot:run Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.4.2.RELEASE:run (default-cli) Execution default-cli of goal org.springframework.boot:spring-boot-maven-plugin:1.4.2.RELEASE:run failed: Unable to find a single main class from the following candidates [com.mkyong.Test, com.mkyong.SpringBootWebApplication] -> [Help 1] Maven …

Read more

Spring Boot – Jetty as embedded server

By default, Spring Boot use Tomcat as the default embedded server, to change it to Jetty, just exclude Tomcat and include Jetty like this : 1. spring-boot-starter-web pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency> 2. spring-boot-starter-thymeleaf pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> …

Read more

How to change the default port in Spring Boot

Default, Spring Boot web application starts embedded web server (Tomcat, Jetty, etc.) in port 8080. And we can configure or change the port using the server.port property. Table of contents 1. application.properties 2. application.yml 3. Command Line 4. Environment Variable 5. WebServerFactoryCustomizer 6. Download Source Code 7. References P.S Tested with Spring Boot 1, 2, …

Read more

Spring Boot – How to change Context Path

In Spring Boot, to change the context path, update server.contextPath properties. The following examples update the context path from / to /mkyong or http://localhost:8080/mkyong Note By default, the context path is “/”. P.S Tested with Spring Boot 1.4.2.RELEASE 1. Properties & Yaml 1.1 Update via a properties file. /src/main/resources/application.properties server.port=8080 server.contextPath=/mkyong 1.2 Update via a …

Read more

Spring Boot Hello World Example – Thymeleaf

In this article, we will show you how to develop a Spring Boot web application, using Thymeleaf view, embedded Tomcat and package it as an executable JAR file. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Thymeleaf 3.0.11.RELEASE Tomcat embed 9.0.14 JUnit 4.12 Maven 3 Java 8 1. Project Directory 2. Maven Put spring-boot-starter-web and …

Read more