Friday, March 28, 2014

Set a private field on a class you need to Unit Test

Well, of course, you could make your field with default access, or you can add some boilerplate setter, or you could fancy whipping up a utility using reflection, but spring-test has already thought of that.

Let's say you want to test your DonkeyController:

import org.springframework.test.util.ReflectionTestUtils;
public class DonkeyControllerTest {
DonkeyController donkeyController;
DonkeyDAO donkeyDAO;
@Before
public void setUp() throws Exception {
donkeyController = new DonkeyController();
donkeyDAO = new DonkeyDAO();
ReflectionTestUtils.setField(donkeyController, "donkeyDAO", donkeyDAO);
}
This is how you can easily set the private field donkeyDAO, without changes in the class under test:

import org.springframework.test.util.ReflectionTestUtils;
public class DonkeyControllerTest {
DonkeyController donkeyController;
DonkeyDAO donkeyDAO;
@Before
public void setUp() throws Exception {
donkeyController = new DonkeyController();
donkeyDAO = new DonkeyDAO();
ReflectionTestUtils.setField(donkeyController, "donkeyDAO", donkeyDAO);
}
ReflectionTestUtils is in spring-test:

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
Cheers!

No comments:

Post a Comment