diff --git a/README.md b/README.md index 1668e41..24a069a 100644 --- a/README.md +++ b/README.md @@ -131,3 +131,40 @@ Let's add minimal interactivity to the page by introducing an input field and a ``` +# Testing the Web Layer + +Let's test our simple app with JUnit. We will concentrate on using Spring Test and Spring Boot features to test the interactions between Spring and your code. + +## Sanity check + +The first thing you can do is write a simple sanity check test that will fail if the application context cannot start. + +From `src/test/java/djmil/hellomvc/SmokeTest.java` + +```java +package djmil.hellomvc; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +public class SmokeTest { + + @Autowired + private GreetingController controller; + + @Test + void contextLoads() throws Exception { + assertThat(controller).isNotNull(); + } +} +``` + +The `@SpringBootTest` annotation tells Spring Boot to look for a main configuration class (one with `@SpringBootApplication`, for instance) and use that to start a Spring application context. You can run this test in your IDE or on the command line (by running `./mvnw test` or `./gradlew test`), and it should pass. + +Spring interprets the `@Autowired` annotation, and the controller is injected before the test methods are run. We use [AssertJ](http://joel-costigliola.github.io/assertj/) (which provides `assertThat()` and other methods) to express the test assertions. + +> A nice feature of the Spring Test support is that the application context is cached between tests. That way, if you have multiple methods in a test case or multiple test cases with the same configuration, they incur the cost of starting the application only once. You can control the cache by using the @DirtiesContext annotation.| diff --git a/src/test/java/djmil/hellomvc/SmokeTest.java b/src/test/java/djmil/hellomvc/SmokeTest.java new file mode 100644 index 0000000..697894c --- /dev/null +++ b/src/test/java/djmil/hellomvc/SmokeTest.java @@ -0,0 +1,19 @@ +package djmil.hellomvc; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +public class SmokeTest { + + @Autowired + private GreetingController controller; + + @Test + void contextLoads() throws Exception { + assertThat(controller).isNotNull(); + } +}