Files
hibernate-demo/src/test/java/com/ankurm/hibernatedemo/proxy/OsivDisabledExceptionTest.java
T

96 lines
4.6 KiB
Java
Executable File

package com.ankurm.hibernatedemo.proxy;
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.test.web.server.LocalServerPort;
/**
* Backs docs/11-proxies-and-lazy-initialization.md, chapter "OSIV: the default, its warning, and what it actually
* masks" -- the "off" half of {@link OsivDefaultWarningTest}. Same controller, same service,
* same entity graph; only {@code spring.jpa.open-in-view} changes: the base
* src/main/resources/application.yml already sets it to {@code false} explicitly, which this
* test relies on and additionally restates for clarity.
*
* <p>The exception surfaces server-side (visible in the application log, asserted here via
* {@link CapturedOutput}) even though the HTTP error body Boot's default
* {@code BasicErrorController} returns is a bare
* {@code {"timestamp":...,"status":500,"error":"Internal Server Error","path":...}} --
* {@code server.error.include-message=always} does not surface it in the JSON body for this
* failure mode, because the failure happens inside the {@code HttpMessageConverter} while
* writing the response, which Boot reports as a generic 500 rather than routing the original
* exception's message into the error attributes map. That gap is itself worth a line in the
* article: don't rely on the HTTP response body to tell you WHY a 500 happened here -- check
* the log.
*/
@ExtendWith(OutputCaptureExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
"spring.main.web-application-type=servlet",
"spring.jpa.open-in-view=false"
})
class OsivDisabledExceptionTest {
private static final Logger DEMO = LoggerFactory.getLogger("DEMO");
@Autowired
private EntityManagerFactory emf;
@LocalServerPort
private int port;
private Long seedBookWithReview() {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
ProxyPublisher publisher = new ProxyPublisher("OSIV Disabled Press");
em.persist(publisher);
ProxyBook book = new ProxyBook("OSIV Disabled Book", publisher);
em.persist(book);
ProxyReview review = new ProxyReview("Never rendered", book);
em.persist(review);
em.getTransaction().commit();
Long id = book.getId();
em.close();
return id;
}
@Test
void openInViewFalse_theSameControllerNowThrowsDuringSerialization(CapturedOutput output) throws Exception {
Long id = seedBookWithReview();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(
HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/osiv/books/" + id)).GET().build(),
HttpResponse.BodyHandlers.ofString());
DEMO.info("open-in-view=false: GET /osiv/books/{} -> status {}, body {}", id, response.statusCode(), response.body());
assertThat(response.statusCode())
.as("with OSIV off, the same request that worked in OsivDefaultWarningTest now fails")
.isEqualTo(500);
// Spring logs this as "Resolved [HttpMessageNotWritableException: Could not write
// JSON: Cannot lazily initialize collection of role '...' (no session)]" -- the
// OUTER exception is HttpMessageNotWritableException (thrown by the Jackson message
// converter while writing the response body); LazyInitializationException's own
// MESSAGE text is nested inside it, but the log line does not print
// LazyInitializationException's class name. Assert on the message text that is
// actually, verifiably there.
assertThat(output.toString())
.as("the real cause is visible server-side even though the HTTP error body is generic")
.contains("HttpMessageNotWritableException")
.contains("Cannot lazily initialize collection of role 'com.ankurm.hibernatedemo.proxy.ProxyBook.reviews'")
.contains("(no session)");
}
}