Spring Boot Test if web server starts on a specific port

Below is a Spring Boot Test example to test whether the web server started on port 8181. P.S. Tested with Spring Boot 3 and JUnit 5. application.properties server.port = 8181 WebServerTests.java package com.mkyong; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class WebServerTests { @LocalServerPort private int port; @Test public …

Read more

How to pass a null value in JUnit 5 parameterized tests

How to pass a null for the below parameterized tests? @ParameterizedTest(name = "#{index} – Run test with args={0}") @ValueSource(strings = {"", " "}) // @ValueSource(strings = {"", " ", null}) // compile error void testBlankIncludeNull(String input) { assertTrue(StringUtils.isBlank(input)); } 1. Solution – @NullSource Since JUnit 5.4 and above, we can use the @NullSource to pass …

Read more

Gradle – How to run a single unit test class

In Gradle, we can pass an –tests option to run a single unit test class. Read this Gradle Test Filtering. Terminal gradle test –test TestClass P.S Tested with Gradle 6.7.1 1. Run a single test class Review a simple unit test. DummyTest.java package com.mkyong.security.db; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; public class DummyTest { @Test void …

Read more

JUnit 5 Tutorials

JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage P.S JUnit 5 requires Java 8 (or higher) at runtime 1. JUnit 5 + Maven See this full JUnit 5 + Maven examples. pom.xml <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.5.2</version> <scope>test</scope> </dependency> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M3</version> </plugin> </plugins> </build> P.S The maven-surefire-plugin must be …

Read more

JUnit 5 Conditional Test Examples

This article shows you how to use JUnit 5 to enable or disable tests based on conditions. P.S Tested with JUnit 5.5.2 1. Operating System 1.1 Enabled or disabled tests based on a particular operating system via @EnabledOnOs and @DisabledOnOs annotations. OperatingSystemTest.java package com.mkyong.conditional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.EnabledOnOs; import org.junit.jupiter.api.condition.OS; public class OperatingSystemTest …

Read more

JUnit 5 + Gradle examples

This article shows you how to add JUnit 5 in a Gradle project. Technologies used: Gradle 5.4.1 Java 8 JUnit 5.5.2 1. Gradle + JUnit 5 1. Add the JUni 5 jupiter engine, and define the useJUnitPlatform() like the following: gradle.build plugins { id ‘java’ id ‘eclipse’ // optional, for Eclipse project id ‘idea’ // …

Read more

JUnit 5 + Maven examples

This article shows you how to add JUnit 5 in a Maven project, nothing special, just add the JUnit 5 junit-jupiter-engine library and make sure the maven-surefire-plugin is at least version 2.22.0 Technologies used: Maven 3.6 Java 8 JUnit 5.5.2 1. Maven + JUnit 5 1. Add the JUni 5 jupiter engine. pom.xml <dependency> <groupId>org.junit.jupiter</groupId> …

Read more

Spring REST Integration Test Example

In this article, we will show you how to test the Spring Boot REST application. Normally, we use the MockMvc or TestRestTemplate for the integration test. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Maven 3 Java 8 pom.xml <!– spring integration test –> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!– spring integration test for security–> …

Read more

Spring Test – How to test a JSON Array in jsonPath

In Spring, we can use Hamcrest APIs like hasItem and hasSize to test a JSON Array. Review the following example : package com.mkyong; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.Matchers.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import …

Read more

Spring + Mockito – Unable to mock save method?

Try to mock a repository save() method, but it is always returning null? P.S Tested with Spring Boot 2 + Spring Data JPA @Test public void save_book_OK() throws Exception { Book newBook = new Book(1L, "Mockito Guide", "mkyong"); when(mockRepository.save(newBook)).thenReturn(newBook); mockMvc.perform(post("/books") .content("{json}") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()); } Solution 1. Mockito uses the equals for argument matching, try …

Read more

Spring Boot – How to init a Bean for testing?

In Spring Boot, we can create a @TestConfiguration class to initialize some beans for testing class only. P.S Tested with Spring Boot 2 1. @TestConfiguration + @Import This @TestConfiguration class will not pick up by the component scanning, we need to import it manually. TestConfig.java package com.mkyong; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import java.time.Duration; …

Read more

JSONAssert – How to unit test JSON data

In Java, we can use JSONAssert to unit test JSON data easily. 1. Maven pom.xml <dependency> <groupId>org.skyscreamer</groupId> <artifactId>jsonassert</artifactId> <version>1.5.0</version> </dependency> 2. JSON Object To test the JSON Object, Strict or not, fields order does not matter. If the extended fields are matter, enable the strict mode. 2.1 When the strictMode is off. JSONObject actual = …

Read more

Spring REST + Spring Security Example

In this article, we will enhance the previous Spring REST Validation Example, by adding Spring Security to perform authentication and authorization for the requested URLs (REST API endpoints) Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Spring Security 5.1.3.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 …

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 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 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

Logback – Disable logging in Unit Test

While the unit test is running in the IDE, the Logback is showing a lot of configuration or status like this : 21:16:59,569 |-INFO in ch.qos.logback.classic.LoggerContext[default] – Could NOT find resource [logback.groovy] 21:16:59,569 |-INFO in ch.qos.logback.classic.LoggerContext[default] – Could NOT find resource [logback-test.xml] 21:16:59,569 |-INFO in ch.qos.logback.classic.LoggerContext[default] – Found resource [logback.xml] at … //… omitted for …

Read more

Gradle – How to display test result in the console

By default, gradle test displays only the test summary. Terminal % gradle test BUILD SUCCESSFUL in 4s 6 actionable tasks: 3 executed, 3 up-to-date P.S Gradle test generates the detailed tests’ result at the build/reports/tests/test/index.html page. P.S Tested with Gradle 6.7.1 1. Display test result in the console. 1.1 We add the testLogging events to …

Read more

Ant and TestNG Task example

In this tutorial, we will show you how to run a TestNG test in Ant build. 1. Run by Classes build.xml <taskdef name="testng" classname="org.testng.TestNGAntTask"> <classpath location="lib/testng-6.8.14.jar" /> </taskdef> <target name="testng" depends="compile"> <!– Assume test.path contains the project library dependencies –> <testng classpathref="test.path" outputDir="${report.dir}" haltOnFailure="true"> <!– Extra project classpath, which is not included in above "test.path" …

Read more

Ant and jUnit Task example

In this tutorial, we will show you how to run a junit test in Ant build. 1. Run a unit test build.xml <target name="junit" depends="compile"> <junit printsummary="yes" haltonfailure="no"> <!– Project classpath, must include junit.jar –> <classpath refid="test.path" /> <!– test class –> <classpath location="${test.classes.dir}" /> <test name="com.mkyong.test.TestMessage" haltonfailure="no" todir="${report.dir}"> <formatter type="plain" /> <formatter type="xml" /> …

Read more

Must include junit.jar if not in Ant’s own classpath

Declares a junit task in Ant like this build.xml <!– Run jUnit –> <target name="junit" depends="resolve"> <junit printsummary="yes" haltonfailure="no"> <classpath refid="test.path" /> <classpath location="${build.dir}" /> <test name="com.mkyong.test.TestMessage" haltonfailure="no" todir="${report.dir}" outfile="result"> <formatter type="plain" /> <formatter type="xml" /> </test> </junit> </target> Run ant junit, but hits the following error message : BUILD FAILED build.xml:86: The <classpath> for …

Read more

Gradle – How to skip unit test

Be default, Gradle build is abort if any unit tests is failed. Oftentimes, we still need to build the project even the unit test is failed. To skip the entire unit tests in Gradle build, uses this option-x test gradle build -x test Review a sample output : 1. Default Gradle build : $ gradle …

Read more

Java Custom Annotations Example

In this tutorial, we will show you how to create two custom annotations – @Test and @TestInfo, to simulate a simple unit test framework. P.S This unit test example is inspired by this official Java annotation article. 1. @Test Annotation This @interface tells Java this is a custom annotation. Later, you can annotate it on …

Read more

NoSuchBeanDefinitionException : No qualifying bean of type JobLauncherTestUtils

Following the official Spring batch unit testing guide to create a standard unit test case. @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring/batch/jobs/job-abc.xml", "classpath:spring/batch/config/context.xml"}) public class AppTest { @Autowired private JobLauncherTestUtils jobLauncherTestUtils; @Test public void launchJob() throws Exception { JobExecution jobExecution = jobLauncherTestUtils.launchJob(); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); } } P.S spring-batch-test.jar is added to the classpath. Problem When launches above …

Read more

Spring Batch unit test example

In this tutorial, we will show you how to unit test Spring batch jobs with jUnit and TestNG frameworks. To unit test batch job, declares spring-batch-test.jar, @autowired the JobLauncherTestUtils, launch the job or step, and assert the execution status. 1. Unit Test Dependencies To unit test Spring batch, declares following dependencies : pom.xml <!– Spring …

Read more

TestNG Tutorial

TestNG tutorial with full example, introduce the TestNG basic usage, annotation support, and test case for expected exception test, ignore test, time test, suite test, parameterized test, dependency test and etc

JUnit 4 Vs TestNG – Comparison

JUnit 4 and TestNG are both very popular unit test framework in Java. Both frameworks look very similar in functionality. Which one is better? Which unit test framework should I use in Java project? Here I did a feature comparison between JUnit 4 and TestNG. 1. Annotation Support The annotation supports are implemented in both …

Read more

JUnit – Parameterized Test

In JUnit, you can pass the parameters into the unit test method via the following methods : Constructor Fields injection via @Parameter P.S Tested with JUnit 4.12 1. MatchUtils – Test with multiple parameters A simple add operation. MathUtils.java package com.mkyong.examples; public class MathUtils { public static int add(int a, int b) { return a …

Read more

JUnit – Timeout Test

If a test is taking longer than a defined “timeout” to finish, a TestTimedOutException will be thrown and the test marked failed. See the following example : P.S Tested with JUnit 4.12 1. Timeout Example This timeout example only applies to a single test method. And the timeout value is in milliseconds. TimeoutTest.java package com.mkyong; …

Read more

JUnit – Ignore a Test

In JUnit, to ignore a test, just add a @Ignore annotation before or after the @Test method. P.S Tested with JUnit 4.12 IgnoreTest.java package com.mkyong; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class IgnoreTest { @Test public void testMath1() { assertThat(1 + 1, is(2)); } @Ignore @Test public void testMath2() { …

Read more

JUnit – Expected Exceptions Test

In JUnit, there are 3 ways to test the expected exceptions : @Test, optional ‘expected’ attribute Try-catch and always fail() @Rule ExpectedException P.S Tested with JUnit 4.12 1. @Test expected attribute Use this if you only want to test the exception type, refer below : Exception1Test.java package com.mkyong; import org.junit.Test; import java.util.ArrayList; public class Exception1Test …

Read more

JUnit – Basic annotation examples

Here’re some basic JUnit annotations you should understand: @BeforeClass – Run once before any of the test methods in the class, public static void @AfterClass – Run once after all the tests in the class have been run, public static void @Before – Run before @Test, public void @After – Run after @Test, public void …

Read more

Maven – How to skip unit test

In Maven, you can define a system property -Dmaven.test.skip=true to skip the entire unit test. By default, when building project, Maven will run the entire unit tests automatically. If any unit tests is failed, it will force Maven to abort the building process. In real life, you may STILL need to build your project even …

Read more