You’re Facing IllegalStateException in JUnit with Spring Boot and How to Resolve It
Spring Boot provides a robust environment for testing applications with its seamless integration with JUnit. However, as you dive deeper into testing your applications, you might encounter the notorious IllegalStateException. This exception often...

I am Tuanh.net. As of 2024, I have accumulated 8 years of experience in backend programming. I am delighted to connect and share my knowledge with everyone.
1. What is IllegalStateException in JUnit with Spring Boot?
- Misconfigured Application Context: Test classes may fail to load the Spring context due to missing or incompatible configuration.
- Bean Definition Issues: A bean may not be defined or annotated correctly in your test or application configuration.
- Multiple Spring Contexts: Multiple conflicting contexts being loaded during tests can trigger this error.
- Annotation Misuse: Misplacement or absence of annotations like @SpringBootTest, @ContextConfiguration, or @TestConfiguration.
2. Step-by-Step Guide to Resolving IllegalStateException
2.1 Correctly Using @SpringBootTest
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class ApplicationTests {
@Test
void contextLoads() {
// Test the application context
}
}
@SpringBootTest
@TestPropertySource(properties = {"spring.config.name=test-config"})
public class ApplicationTests {
// Test code
}
2.2 Leveraging @MockBean for External Dependencies
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public String getUserDetails(String userId) {
return userRepository.findById(userId).orElse("Default User");
}
}
@SpringBootTest
public class UserServiceTest {
@MockBean
private UserRepository userRepository;
@Autowired
private UserService userService;
@Test
void testGetUserDetails() {
Mockito.when(userRepository.findById("123")).thenReturn(Optional.of("John Doe"));
String result = userService.getUserDetails("123");
Assertions.assertEquals("John Doe", result);
}
}
3. Troubleshooting and Best Practices
@ContextConfiguration(classes = {CustomConfig.class})
@SpringBootTest
public class CustomConfigTests {
// Test code
}
- Use @ActiveProfiles to isolate configurations.
- Leverage logging by setting spring.main.log-startup-info=true.
4. Expanding Your Knowledge: Related Aspects
4.1 Testing Spring MVC Controllers
@WebMvcTest(controllers = UserController.class)
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
void testGetUser() throws Exception {
Mockito.when(userService.getUserDetails("123")).thenReturn("John Doe");
mockMvc.perform(get("/users/123"))
.andExpect(status().isOk())
.andExpect(content().string("John Doe"));
}
}
4.2 Testing with Database Integration
5. Conclusion
Read more at : You’re Facing IllegalStateException in JUnit with Spring Boot and How to Resolve It





