Tesing: Sanity check
This commit is contained in:
parent
141ed6aa7f
commit
e77f67b0b7
37
README.md
37
README.md
@ -131,3 +131,40 @@ Let's add minimal interactivity to the page by introducing an input field and a
|
||||
</script>
|
||||
```
|
||||
|
||||
# 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.|
|
||||
|
19
src/test/java/djmil/hellomvc/SmokeTest.java
Normal file
19
src/test/java/djmil/hellomvc/SmokeTest.java
Normal file
@ -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();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user