Alessandro Argentieri
Alessandro Argentieri

Reputation: 3215

Reflection not working for Spring autowired parameters

I'm trying to generate an integration test without using @DataJpaTest in order to understand better the concepts. I've noticed that with Reflection I'm not able to get or set The Dao within my Service layer under test. So when it comes to access the Dao got with Reflection API it returns a NullPointerException. I've tested both Java Reflection API and ReflectionTestUtils of Spring Framework. Here is the snippet of code

UserService userService;

@Before
public void setUp(){
   userService = new UserServiceImpl();
   UserDao userDao = (UserDao) ReflectionTestUtils.getField(userService, "userDao");
   userDao.deleteAll(); //HERE RETURNS A NULLPOINTER
   ...
}

Consider that in UserServiceImpl.java I inject UserDao (Interface which extends JpaRepository using @Autowired annotation of Spring framework.

How can I access the Dao (implemented by Spring framework) from my Service? Thanks!

Upvotes: 0

Views: 1655

Answers (1)

Michael Peacock
Michael Peacock

Reputation: 2104

One handy trick is to make sure your test Spring configuration is working correctly by verifying your autowired dependencies are actually getting autowired. For example:

@Autowired
UserDao userDao;

@Autowired
UserServiceImpl userService;

@Test
public void verifySpringContext() {
    assertNotNull(userDao);
    assertNotNull(userService.getUserDao());
} 

I suspect that there's an issue with the Spring configuration in your test, preventing userDao from being autowired.

Upvotes: 1

Related Questions