spring-test-slices: Spring Boot 4.1.2 test slices lab (@WebMvcTest, @JsonTest, @RestClientTest, @DataJpaTest vs @SpringBootTest)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b7Jbw5CxUQ13D7gn25
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
package lab.slices;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ProblemDetail;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
/** A @ControllerAdvice: @WebMvcTest loads it, so the 404 mapping is testable without a service layer. */
|
||||
@RestControllerAdvice
|
||||
public class ApiExceptionHandler {
|
||||
@ExceptionHandler(BookNotFoundException.class)
|
||||
ProblemDetail notFound(BookNotFoundException e) {
|
||||
ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
|
||||
p.setTitle("Book not found");
|
||||
return p;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package lab.slices;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* A plain @Component. No slice scans plain components, so this bean exists only in a full
|
||||
* @SpringBootTest. It is the canary the bean-presence table uses.
|
||||
*/
|
||||
@Component
|
||||
public class AuditLogger {
|
||||
public void audit(String message) {
|
||||
System.out.println("AUDIT " + message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package lab.slices;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.Id;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Entity
|
||||
public class Book {
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
private String isbn;
|
||||
private String title;
|
||||
private String author;
|
||||
private BigDecimal price;
|
||||
private LocalDate publishedOn;
|
||||
|
||||
protected Book() {
|
||||
}
|
||||
|
||||
public Book(String isbn, String title, String author, BigDecimal price, LocalDate publishedOn) {
|
||||
this.isbn = isbn;
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.price = price;
|
||||
this.publishedOn = publishedOn;
|
||||
}
|
||||
|
||||
public Long getId() { return id; }
|
||||
public String getIsbn() { return isbn; }
|
||||
public String getTitle() { return title; }
|
||||
public String getAuthor() { return author; }
|
||||
public BigDecimal getPrice() { return price; }
|
||||
public LocalDate getPublishedOn() { return publishedOn; }
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package lab.slices;
|
||||
|
||||
import java.util.List;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/books")
|
||||
public class BookController {
|
||||
private final BookService service;
|
||||
|
||||
public BookController(BookService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
BookView one(@PathVariable Long id) {
|
||||
return BookView.of(service.get(id));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
List<BookView> byAuthor(@RequestParam String author) {
|
||||
return service.byAuthor(author).stream().map(BookView::of).toList();
|
||||
}
|
||||
|
||||
@PostMapping("/import/{isbn}")
|
||||
ResponseEntity<BookView> importBook(@PathVariable String isbn) {
|
||||
return service.importByIsbn(isbn)
|
||||
.map(b -> ResponseEntity.ok(BookView.of(b)))
|
||||
.orElse(ResponseEntity.notFound().build());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package lab.slices;
|
||||
|
||||
public class BookNotFoundException extends RuntimeException {
|
||||
public BookNotFoundException(Long id) {
|
||||
super("No book with id " + id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package lab.slices;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface BookRepository extends JpaRepository<Book, Long> {
|
||||
List<Book> findByAuthorIgnoreCaseOrderByTitle(String author);
|
||||
|
||||
Optional<Book> findByIsbn(String isbn);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package lab.slices;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class BookService {
|
||||
private final BookRepository repository;
|
||||
private final IsbnLookupClient isbnClient;
|
||||
private final AuditLogger audit;
|
||||
|
||||
public BookService(BookRepository repository, IsbnLookupClient isbnClient, AuditLogger audit) {
|
||||
this.repository = repository;
|
||||
this.isbnClient = isbnClient;
|
||||
this.audit = audit;
|
||||
}
|
||||
|
||||
public Book get(Long id) {
|
||||
return repository.findById(id).orElseThrow(() -> new BookNotFoundException(id));
|
||||
}
|
||||
|
||||
public List<Book> byAuthor(String author) {
|
||||
return repository.findByAuthorIgnoreCaseOrderByTitle(author);
|
||||
}
|
||||
|
||||
/** Looks the ISBN up remotely and stores the result. Empty when the remote service has never heard of it. */
|
||||
public java.util.Optional<Book> importByIsbn(String isbn) {
|
||||
return isbnClient.lookup(isbn).map(info -> {
|
||||
audit.audit("import " + isbn);
|
||||
return repository.save(new Book(info.isbn(), info.title(), info.author(),
|
||||
BigDecimal.valueOf(499), LocalDate.of(2024, 1, 1)));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package lab.slices;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.time.LocalDate;
|
||||
|
||||
/** What the API returns for a book. The JSON shape is what the @JsonTest slice pins down. */
|
||||
public record BookView(
|
||||
String isbn,
|
||||
String title,
|
||||
String author,
|
||||
Price price,
|
||||
@JsonProperty("published_on") LocalDate publishedOn) {
|
||||
|
||||
static BookView of(Book b) {
|
||||
return new BookView(b.getIsbn(), b.getTitle(), b.getAuthor(),
|
||||
new Price("INR", b.getPrice()), b.getPublishedOn());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package lab.slices;
|
||||
|
||||
public record IsbnInfo(String isbn, String title, String author, int pages) {
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package lab.slices;
|
||||
|
||||
import java.util.Optional;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.client.RestClient;
|
||||
|
||||
/** Calls an external ISBN service. @RestClientTest replaces the HTTP server behind it. */
|
||||
@Component
|
||||
public class IsbnLookupClient {
|
||||
private final RestClient client;
|
||||
|
||||
public IsbnLookupClient(RestClient.Builder builder, @Value("${isbn.base-url}") String baseUrl) {
|
||||
this.client = builder.baseUrl(baseUrl).build();
|
||||
}
|
||||
|
||||
public Optional<IsbnInfo> lookup(String isbn) {
|
||||
try {
|
||||
return Optional.ofNullable(client.get().uri("/isbn/{isbn}", isbn).retrieve().body(IsbnInfo.class));
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package lab.slices;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/** A money amount. Its JSON form ("INR 499.00") comes from {@link PriceJson}, not from annotations. */
|
||||
public record Price(String currency, BigDecimal amount) {
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package lab.slices;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import org.springframework.boot.jackson.JacksonComponent;
|
||||
import tools.jackson.core.JsonGenerator;
|
||||
import tools.jackson.core.JsonParser;
|
||||
import tools.jackson.databind.DeserializationContext;
|
||||
import tools.jackson.databind.SerializationContext;
|
||||
import tools.jackson.databind.ValueDeserializer;
|
||||
import tools.jackson.databind.ValueSerializer;
|
||||
|
||||
/**
|
||||
* Writes a Price as "INR 499.00". @JacksonComponent is the Boot 4 name of @JsonComponent, and it is one of
|
||||
* the few things the @JsonTest slice picks up by scanning.
|
||||
*/
|
||||
@JacksonComponent
|
||||
public class PriceJson {
|
||||
public static class Serializer extends ValueSerializer<Price> {
|
||||
@Override
|
||||
public void serialize(Price value, JsonGenerator gen, SerializationContext ctxt) {
|
||||
gen.writeString(value.currency() + " " + value.amount().setScale(2).toPlainString());
|
||||
}
|
||||
}
|
||||
|
||||
public static class Deserializer extends ValueDeserializer<Price> {
|
||||
@Override
|
||||
public Price deserialize(JsonParser p, DeserializationContext ctxt) {
|
||||
String[] parts = p.getString().split(" ");
|
||||
return new Price(parts[0], new BigDecimal(parts[1]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package lab.slices;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* Keep this class free of extra annotations. Every slice test starts from the class carrying
|
||||
* @SpringBootApplication, so an @EnableJpaRepositories or @EnableJpaAuditing placed here is
|
||||
* applied to every slice, including the ones that have no database.
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class SlicesApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SlicesApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
isbn.base-url=https://isbn.example.test
|
||||
spring.jpa.open-in-view=false
|
||||
Reference in New Issue
Block a user