Question

I am doing unit test on a class which contains a variable that is @Autowired by spring. However, when I run the test, I get a NullPointerException indicating object userDetailsLoader is null.

Following is what I have:

public class UserService {
    @Autowired
    UserDetailsLoader userDetailsLoader;

    public void doSomething (){...}

}

JUnit test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class UserServiceTest {

    UserService service = new UserService();

    @Test
    public void testDoSomething() {...}
}

UserServiceTest-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="userDetailsLoader" class="my.package.UserDetailsLoader" />

</beans>

The configuration file is properly named and there is no FileNotFoundException. Can anybody see the problem here?

Thank you in advance.

Was it helpful?

Solution

Well, I guess I am just being dumb on Monday, still recovering from ending of weekends.

The problem is simple and obvious. I am creating a bean that is not managed by Spring since I wrote UserService service = new UserService(); in the test calss. In order for a bean to be injected by spring, spring has to be aware of it and has relevant information of it. In my case, I have the config ready (relevant info), but the bean is not injected by Spring (not @Autowired).

In conclusion, changing UserService service = new UserService(); to

@Autowired UserService service; solved the problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top