org.opentest4j.AssertionFailedError: Unexpected exception type thrown, expected: <java.lang.IllegalStateException> but was: <java.lang.IllegalArgumentException>
assertThrows aștepta un tip de excepție, dar codul a aruncat altul. Decide care e tipul corect pentru acea situație: dacă testul are dreptate, schimbă excepția din cod; dacă codul are dreptate, corectează testul.
Explicat de Tudor Andrei Dumitrescu, Senior Software Developer, fondatorul Academiei ProgramatorilorActualizat la
Ce înseamnă
Când lambda din assertThrows aruncă o excepție, JUnit verifică tipul ei: trebuie să fie clasa cerută sau o subclasă. Dacă e alt tip, primești Unexpected exception type thrown, expected: <java.lang.IllegalStateException> but was: <java.lang.IllegalArgumentException>, iar excepția reală apare ca cause, cu stiva ei.
De obicei e o neînțelegere între test și cod despre ce excepție semnalează problema. Convenția Java: IllegalArgumentException pentru un argument invalid primit de metodă, IllegalStateException când obiectul nu e în starea potrivită pentru operație (o comandă deja livrată), excepții proprii (ProdusNegasitException) pentru situațiile de business.
Atenție și la cazul în care excepția reală e NullPointerException sau ArithmeticException: atunci codul pică înainte să ajungă la validarea ta, iar testul a descoperit un bug.
De ce apare: cauzele frecvente
1Testul așteaptă alt tip decât cel aruncat
assertThrows(IllegalStateException.class,
() -> cos.reducere(100, -5));assertThrows(IllegalArgumentException.class,
() -> cos.reducere(100, -5));Un procent negativ e un argument invalid; metoda aruncă, corect, IllegalArgumentException.
2Codul pică înainte de validare
int medie(List<Integer> note) {
int s = 0;
for (int n : note) s += n;
return s / note.size(); // ArithmeticException
}int medie(List<Integer> note) {
if (note.isEmpty()) throw new IllegalArgumentException("Lista e goală");
...
}Validarea explicită aruncă excepția pe care o așteaptă testul.
Repară eroarea, direct în pagină
Testul pică cu Unexpected exception type thrown, expected: <java.lang.IllegalStateException> but was: <java.lang.IllegalArgumentException>. Un procent negativ e un argument invalid, deci codul aruncă tipul corect: corectează testul.
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);
}
return p;
}
@GetMapping("/api/salut")
String salut(@RequestParam String nume) {
return "Salut, " + nume + "!";
}
}
@SpringBootTest
class CosServiceTest {
@Autowired
CosService cos;
@Test
void procentNegativEsteRespins() {
assertThrows(IllegalStateException.class, () -> cos.reducere(200, -5));
}
}Tomcat started on port 8080 (http) Started Application CosServiceTest OK procentNegativEsteRespins() Teste: 1 trecute, 0 picate
Indiciu
Ce tip de excepție aruncă CosService.reducere pentru un procent invalid?
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);
}
return p;
}
@GetMapping("/api/salut")
String salut(@RequestParam String nume) {
return "Salut, " + nume + "!";
}
}
@SpringBootTest
class CosServiceTest {
@Autowired
CosService cos;
@Test
void procentNegativEsteRespins() {
assertThrows(IllegalArgumentException.class, () -> cos.reducere(200, -5));
}
}De ce merge
Metoda validează argumentul procent și aruncă IllegalArgumentException, tipul folosit în Java pentru argumente invalide. Testul aștepta IllegalStateException, folosit pentru o stare greșită a obiectului. Aici avea dreptate codul, așa că s-a corectat testul; în alte cazuri decizia poate fi inversă.
Alte forme ale mesajului
Unexpected exception type thrown, expected: <ProdusNegasitException> but was: <java.lang.NullPointerException>
Cum o eviți pe viitor
- Alege tipul excepției după convenție și documentează-l în metodă.
- Folosește excepții proprii pentru erorile de business, ca testele și handler-ele să le recunoască ușor.
- Când vezi
NullPointerExceptionca tip real, caută bug-ul, nu schimba testul. - Verifică și mesajul excepției, nu doar tipul.
Întrebări frecvente
assertThrows acceptă și subclase?
Da. assertThrows(RuntimeException.class, ...) trece și pentru IllegalArgumentException. Dacă vrei tipul exact, folosește assertThrowsExactly (JUnit 5.8+).
Unde văd excepția reală?
În raportul testului, la Caused by: are tipul, mesajul și linia unde a fost aruncată.
Erori înrudite
org.opentest4j.AssertionFailedError: Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown. assertThrows aștepta ca lambda să arunce excepția indicată, dar codul s-a terminat normal. Fie metoda testată nu validează cazul respectiv (bug), fie testul trimite date care sunt de fapt valide. Verifică datele din test și condiția din cod. org.opentest4j.AssertionFailedError: expected: <288> but was: <199> O aserțiune assertEquals din JUnit 5 a comparat valoarea așteptată (primul argument) cu cea reală (al doilea) și au ieșit diferite. Fie codul testat are un bug, fie așteptarea din test e greșită. Recalculează de mână rezultatul corect și verifică ordinea argumentelor. Î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.
