jakarta.servlet.ServletException: Request processing failed: java.lang.IllegalStateException: Produsul 99 nu există
În testul MockMvc, controllerul a aruncat o excepție pe care nimic nu a transformat-o într-un răspuns HTTP, iar MockMvc o aruncă mai departe, împachetată în ServletException. Tratează excepția în aplicație (@ResponseStatus, ResponseStatusException sau @ExceptionHandler), ca testul să primească un cod HTTP.
Explicat de Tudor Andrei Dumitrescu, Senior Software Developer, fondatorul Academiei ProgramatorilorActualizat la
Ce înseamnă
Într-un server real, o excepție neprinsă din controller devine un răspuns 500 (prin pagina de eroare a lui Spring Boot). MockMvc nu are acel mecanism: când excepția nu e tratată de un @ExceptionHandler, de @ResponseStatus sau de ResponseStatusException, o propagă direct în test, împachetată: jakarta.servlet.ServletException: Request processing failed: java.lang.IllegalStateException: Produsul 99 nu există. În Spring Boot 2 numele era NestedServletException.
Ce e după Request processing failed: e excepția reală, cu mesajul ei. Așa că testul îți arată de fapt o problemă a aplicației: un caz de eroare (produs inexistent, date greșite) nu are un răspuns HTTP definit.
Reparația corectă e în aplicație: excepția de business primește un status (404, 400, 409), iar testul verifică acel status. Nu prinde excepția în test: ai ascunde faptul că clienții reali primesc 500.
De ce apare: cauzele frecvente
1Excepție generică fără status
Produs p = produse.get(id);
if (p == null) throw new IllegalStateException("Produsul " + id + " nu există");if (p == null)
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Produsul " + id + " nu există");ResponseStatusException poartă codul HTTP, deci MockMvc primește un 404.
2Excepție proprie fără mapare
class ProdusNegasitException extends RuntimeException { }@ResponseStatus(HttpStatus.NOT_FOUND)
class ProdusNegasitException extends RuntimeException { }Cu @ResponseStatus, Spring transformă excepția în 404 oriunde e aruncată.
3Lipsește handler-ul global
// nicio clasă @RestControllerAdvice@RestControllerAdvice
class Erori {
@ExceptionHandler(ProdusNegasitException.class)
ResponseEntity<String> lipsa(ProdusNegasitException e) {
return ResponseEntity.status(404).body(e.getMessage());
}
}Un handler global dă tuturor excepțiilor de business un răspuns clar.
Repară eroarea, direct în pagină
Testul produsInexistent așteaptă 404, dar controllerul aruncă IllegalStateException, iar MockMvc o propagă ca ServletException: Request processing failed. Schimbă excepția din controller cu ResponseStatusException(HttpStatus.NOT_FOUND, ...), ca testul să treacă.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.stereotype.Service;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
record Produs(long id, String nume, int pret) { }
@Service
class CosService {
int total(List<Integer> preturi) {
int s = 0;
for (int p : preturi) {
s += p;
}
return s;
}
int reducere(int total, int procent) {
if (procent < 0 || procent > 100) {
throw new IllegalArgumentException("Procent invalid: " + procent);
}
return total - total * procent / 100;
}
}
@RestController
class ProdusController {
private final Map<Long, Produs> produse = new TreeMap<>(Map.of(
1L, new Produs(1, "Mouse", 89),
2L, new Produs(2, "Tastatură", 199)));
@GetMapping("/api/produse/{id}")
Produs unul(@PathVariable long id) {
Produs p = produse.get(id);
if (p == null) {
throw new IllegalStateException("Produsul " + id + " nu există");
}
return p;
}
@GetMapping("/api/salut")
String salut(@RequestParam String nume) {
return "Salut, " + nume + "!";
}
}
@SpringBootTest
@AutoConfigureMockMvc
class ProdusControllerTest {
@Autowired
MockMvc mvc;
@Test
void produsInexistent() throws Exception {
mvc.perform(get("/api/produse/99"))
.andExpect(status().isNotFound());
}
}Tomcat started on port 8080 (http) Started Application ProdusControllerTest OK produsInexistent() Teste: 1 trecute, 0 picate
Indiciu
O excepție care poartă cu ea codul HTTP 404.
Reparația
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.stereotype.Service;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
record Produs(long id, String nume, int pret) { }
@Service
class CosService {
int total(List<Integer> preturi) {
int s = 0;
for (int p : preturi) {
s += p;
}
return s;
}
int reducere(int total, int procent) {
if (procent < 0 || procent > 100) {
throw new IllegalArgumentException("Procent invalid: " + procent);
}
return total - total * procent / 100;
}
}
@RestController
class ProdusController {
private final Map<Long, Produs> produse = new TreeMap<>(Map.of(
1L, new Produs(1, "Mouse", 89),
2L, new Produs(2, "Tastatură", 199)));
@GetMapping("/api/produse/{id}")
Produs unul(@PathVariable long id) {
Produs p = produse.get(id);
if (p == null) {
throw new org.springframework.web.server.ResponseStatusException(org.springframework.http.HttpStatus.NOT_FOUND, "Produsul " + id + " nu există");
}
return p;
}
@GetMapping("/api/salut")
String salut(@RequestParam String nume) {
return "Salut, " + nume + "!";
}
}
@SpringBootTest
@AutoConfigureMockMvc
class ProdusControllerTest {
@Autowired
MockMvc mvc;
@Test
void produsInexistent() throws Exception {
mvc.perform(get("/api/produse/99"))
.andExpect(status().isNotFound());
}
}De ce merge
IllegalStateException nu are niciun cod HTTP asociat, deci MockMvc o arunca în test, iar clienții reali primeau 500. ResponseStatusException(HttpStatus.NOT_FOUND, ...) îi spune lui Spring exact ce răspuns să dea: 404 cu mesajul tău. Testul verifică acum contractul corect al API-ului.
Alte forme ale mesajului
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateExceptionRequest processing failed: java.lang.NullPointerException
Cum o eviți pe viitor
- Dă fiecărei excepții de business un status HTTP (
@ResponseStatus,ResponseStatusExceptionsau@RestControllerAdvice). - Scrie teste pentru cazurile de eroare, nu doar pentru drumul fericit.
- Dacă excepția din mesaj e
NullPointerException, ai un bug, nu un caz netratat: repară codul. - Nu prinde excepția în test doar ca să treacă.
Întrebări frecvente
De ce în aplicația pornită primesc 500, iar în test o excepție?
Serverul real are pagina de eroare a lui Spring Boot (/error), care transformă orice excepție în 500. MockMvc nu trece prin ea și îți arată direct excepția.
În laborator testul pică cu Status expected:<404> but was:<500>. E aceeași problemă?
Da. Simulatorul transformă excepția netratată în 500 și în teste; Spring real o aruncă în test ca ServletException. Reparația e identică.
Erori înrudite
java.lang.AssertionError: Status expected:<200> but was:<404> Testul MockMvc aștepta un cod HTTP, iar endpoint-ul a răspuns cu altul. Codul primit îți spune direcția: 404 = adresă sau resursă greșită, 400 = cerere invalidă, 405 = metodă HTTP greșită, 500 = excepție în server. Verifică URL-ul și datele din test, apoi codul controllerului. java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@1b2c3d4e testClass = ProdusControllerTest] Testul @SpringBootTest nu a putut porni contextul aplicației, deci toate testele clasei pică. Mesajul e doar ambalajul: cauza reală e mai jos, la ultimul „Caused by” (un bean lipsă, o proprietate nerezolvată, o eroare de JPA). Repar-o ca pe o eroare de pornire a aplicației. Învață Spring Boot de la zero, cu exerciții la fiecare lecție
Curs Spring Boot și REST API: lecții scurte, fiecare cu un exercițiu verificat automat, direct în browser. Primele 18 lecții sunt gratuite.
