I'm trying to run Unit tests on a service class that has an auto wired dependency which is request scoped. When running the unit test, it seems like spring container is unable to find the bean to auto wire into the service class. What should I do to fix this?
Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
AppConfig.java
@Configuration
public class AppConfig {
@Bean
@Scope("request")
public ClassA classA(){
return new ClassA();
}
}
ServiceA.java
@Service
public class ServiceA {
@Autowired
private ClassA classA;
public void doSomething(){
String value = classA.getValue();
System.out.println(value);
}
}
ServiceTest.java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ServiceATest {
@Test
void contextLoads() {
}
}
Error message
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'serviceA': Unsatisfied dependency expressed through field 'classA'; nested exception is org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'classA': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.