Project: Tests
Prove it works.
Our API works when we try it by hand. Now let's prove it, with tests that run on every build.
- It works by hand
- Prove it
- On every build
What to test
Test the rules that matter most. Anyone can read. Only admins can delete. And bad input is rejected. With Spring Security's test support, with user, pretends a user is logged in.
| key | value |
|---|---|
| Reads | open to everyone |
| Deletes | admins only |
| Input | rejected when bad |
| Login | with(user("sam")) |
Testing the rules
At Spring Boot Test starts the whole secured app. The first test reads book one, with no login. The second deletes as Sam, and expects four oh three. Then it deletes as Alex, and expects two oh four, no content. Run it. Both tests pass. The security rules are proven.
@SpringBootTest
@AutoConfigureMockMvc
class BookApiTest {
@Autowired MockMvc mvc;
@Test
void anyoneCanReadABook() throws Exception {
mvc.perform(get("/books/1")).andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Dune"));
}
@Test
void onlyAdminsCanDelete() throws Exception {
mvc.perform(delete("/books/2").with(user("sam").roles("USER")))
.andExpect(status().isForbidden());
mvc.perform(delete("/books/2").with(user("alex").roles("ADMIN")))
.andExpect(status().isNoContent());
}
}[INFO] Running BookApiTest [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
Also uses Book.java
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private double price;
protected Book() {}
public Book(String title, String author, double price) {
this.title = title; this.author = author; this.price = price;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public double getPrice() { return price; }
public void setTitle(String title) { this.title = title; }
public void setAuthor(String author) { this.author = author; }
public void setPrice(double price) { this.price = price; }
}Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {
List<Book> findByAuthorContainingIgnoreCase(String author);
}Also uses CreateBook.java
public record CreateBook(
@NotBlank String title,
@NotBlank String author,
@Positive double price
) {}Also uses BookResponse.java
public record BookResponse(Long id, String title, String author, double price) {
static BookResponse from(Book b) {
return new BookResponse(b.getId(), b.getTitle(), b.getAuthor(), b.getPrice());
}
}Also uses NewPrice.java
public record NewPrice(@Positive double price) {}Also uses BookNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(long id) { super("Book " + id + " was not found"); }
}Also uses data.sql
INSERT INTO book (title, author, price) VALUES
('Dune', 'Frank Herbert', 9.99),
('The Hobbit', 'J.R.R. Tolkien', 8.99),
('Circe', 'Madeline Miller', 10.99),
('Children of Dune', 'Frank Herbert', 8.49),
('Song of Achilles', 'Madeline Miller', 9.49),
('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
('Emma', 'Jane Austen', 6.99),
('Persuasion', 'Jane Austen', 7.49);Also uses application.properties
spring.jpa.defer-datasource-initialization=trueAlso uses BookService.java
@Service
@Transactional
public class BookService {
private final BookRepository books;
public BookService(BookRepository books) { this.books = books; }
@Transactional(readOnly = true)
public List<BookResponse> search(String author) {
List<Book> found = author == null ? books.findAll()
: books.findByAuthorContainingIgnoreCase(author);
return found.stream().map(BookResponse::from).toList();
}
@Transactional(readOnly = true)
public BookResponse byId(long id) { return BookResponse.from(find(id)); }
public BookResponse create(CreateBook req) {
Book saved = books.save(new Book(req.title(), req.author(), req.price()));
return BookResponse.from(saved);
}
public BookResponse changePrice(long id, double price) {
Book book = find(id);
book.setPrice(price);
return BookResponse.from(book);
}
public void delete(long id) { books.delete(find(id)); }
private Book find(long id) {
return books.findById(id).orElseThrow(() -> new BookNotFoundException(id));
}
}Also uses BookController.java
@RestController
@RequestMapping("/books")
public class BookController {
private final BookService service;
public BookController(BookService service) { this.service = service; }
@GetMapping
public List<BookResponse> list(@RequestParam(required = false) String author) {
return service.search(author);
}
@GetMapping("/{id}")
public BookResponse one(@PathVariable long id) { return service.byId(id); }
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public BookResponse add(@Valid @RequestBody CreateBook req) {
return service.create(req);
}
@PutMapping("/{id}/price")
public BookResponse price(@PathVariable long id, @Valid @RequestBody NewPrice p) {
return service.changePrice(id, p.price());
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable long id) { service.delete(id); }
}Also uses ApiErrors.java
@RestControllerAdvice
public class ApiErrors {
@ExceptionHandler(BookNotFoundException.class)
public ProblemDetail notFound(BookNotFoundException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail invalid(MethodArgumentNotValidException ex) {
var pd = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid input");
pd.setProperty("errors", ex.getFieldErrors().stream()
.map(e -> e.getField() + " " + e.getDefaultMessage()).sorted().toList());
return pd;
}
}Also uses SecurityConfig.java
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/books/**").permitAll()
.requestMatchers(HttpMethod.DELETE, "/books/**").hasRole("ADMIN")
.anyRequest().hasAnyRole("USER", "ADMIN"))
.httpBasic(Customizer.withDefaults()).csrf(csrf -> csrf.disable());
return http.build();
}
}Also uses UserConfig.java
@Configuration
public class UserConfig {
@Bean
PasswordEncoder encoder() { return new BCryptPasswordEncoder(); }
@Bean
UserDetailsService users(PasswordEncoder encoder) {
return new InMemoryUserDetailsManager(
User.withUsername("sam").password(encoder.encode("reader1"))
.roles("USER").build(),
User.withUsername("alex").password(encoder.encode("boss123"))
.roles("USER", "ADMIN").build());
}
}Also uses _mvn
testAlso uses _profile
securityTesting validation
Sam posts a book, with a blank title, and a negative price. We expect four hundred, and two errors in the list. Run it. The test passes.
@SpringBootTest
@AutoConfigureMockMvc
class ValidationTest {
@Autowired MockMvc mvc;
@Test
void rejectsABadBook() throws Exception {
String json = "{\"title\":\"\",\"author\":\"Ann\",\"price\":-1}";
mvc.perform(post("/books").with(user("sam")).contentType(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors.length()").value(2));
}
}[INFO] Running ValidationTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
Also uses Book.java
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private double price;
protected Book() {}
public Book(String title, String author, double price) {
this.title = title; this.author = author; this.price = price;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public double getPrice() { return price; }
public void setTitle(String title) { this.title = title; }
public void setAuthor(String author) { this.author = author; }
public void setPrice(double price) { this.price = price; }
}Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {
List<Book> findByAuthorContainingIgnoreCase(String author);
}Also uses CreateBook.java
public record CreateBook(
@NotBlank String title,
@NotBlank String author,
@Positive double price
) {}Also uses BookResponse.java
public record BookResponse(Long id, String title, String author, double price) {
static BookResponse from(Book b) {
return new BookResponse(b.getId(), b.getTitle(), b.getAuthor(), b.getPrice());
}
}Also uses NewPrice.java
public record NewPrice(@Positive double price) {}Also uses BookNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(long id) { super("Book " + id + " was not found"); }
}Also uses data.sql
INSERT INTO book (title, author, price) VALUES
('Dune', 'Frank Herbert', 9.99),
('The Hobbit', 'J.R.R. Tolkien', 8.99),
('Circe', 'Madeline Miller', 10.99),
('Children of Dune', 'Frank Herbert', 8.49),
('Song of Achilles', 'Madeline Miller', 9.49),
('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
('Emma', 'Jane Austen', 6.99),
('Persuasion', 'Jane Austen', 7.49);Also uses application.properties
spring.jpa.defer-datasource-initialization=trueAlso uses BookService.java
@Service
@Transactional
public class BookService {
private final BookRepository books;
public BookService(BookRepository books) { this.books = books; }
@Transactional(readOnly = true)
public List<BookResponse> search(String author) {
List<Book> found = author == null ? books.findAll()
: books.findByAuthorContainingIgnoreCase(author);
return found.stream().map(BookResponse::from).toList();
}
@Transactional(readOnly = true)
public BookResponse byId(long id) { return BookResponse.from(find(id)); }
public BookResponse create(CreateBook req) {
Book saved = books.save(new Book(req.title(), req.author(), req.price()));
return BookResponse.from(saved);
}
public BookResponse changePrice(long id, double price) {
Book book = find(id);
book.setPrice(price);
return BookResponse.from(book);
}
public void delete(long id) { books.delete(find(id)); }
private Book find(long id) {
return books.findById(id).orElseThrow(() -> new BookNotFoundException(id));
}
}Also uses BookController.java
@RestController
@RequestMapping("/books")
public class BookController {
private final BookService service;
public BookController(BookService service) { this.service = service; }
@GetMapping
public List<BookResponse> list(@RequestParam(required = false) String author) {
return service.search(author);
}
@GetMapping("/{id}")
public BookResponse one(@PathVariable long id) { return service.byId(id); }
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public BookResponse add(@Valid @RequestBody CreateBook req) {
return service.create(req);
}
@PutMapping("/{id}/price")
public BookResponse price(@PathVariable long id, @Valid @RequestBody NewPrice p) {
return service.changePrice(id, p.price());
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable long id) { service.delete(id); }
}Also uses ApiErrors.java
@RestControllerAdvice
public class ApiErrors {
@ExceptionHandler(BookNotFoundException.class)
public ProblemDetail notFound(BookNotFoundException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail invalid(MethodArgumentNotValidException ex) {
var pd = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid input");
pd.setProperty("errors", ex.getFieldErrors().stream()
.map(e -> e.getField() + " " + e.getDefaultMessage()).sorted().toList());
return pd;
}
}Also uses SecurityConfig.java
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/books/**").permitAll()
.requestMatchers(HttpMethod.DELETE, "/books/**").hasRole("ADMIN")
.anyRequest().hasAnyRole("USER", "ADMIN"))
.httpBasic(Customizer.withDefaults()).csrf(csrf -> csrf.disable());
return http.build();
}
}Also uses UserConfig.java
@Configuration
public class UserConfig {
@Bean
PasswordEncoder encoder() { return new BCryptPasswordEncoder(); }
@Bean
UserDetailsService users(PasswordEncoder encoder) {
return new InMemoryUserDetailsManager(
User.withUsername("sam").password(encoder.encode("reader1"))
.roles("USER").build(),
User.withUsername("alex").password(encoder.encode("boss123"))
.roles("USER", "ADMIN").build());
}
}Also uses _mvn
testAlso uses _profile
securitySummary
Integration tests prove the rules, reads, deletes, and validation, on every build. Our project is complete! Next, where to go from here.
Key takeaways- @SpringBootTest
- with(user(...))
- Rules proven