Reputation: 1258
Hi, I have a class that I want to test. This class has an autowired DAO object this object is been used in a @PostConstruct
method, but I want to use the mock and not the real object is there a way. Here is an example:
@Autowired
PersonDao personDao;
//Constructor
public Person()
{
//Do stuff
}
@PostConstruct
void init()
{
//I need it to be a mock
personDao.add(new Person());
}
Upvotes: 0
Views: 1611
Reputation: 340708
If you want to use mocked PersonDao
you have several choices:
defines PersonDao
mock as a Spring bean with primary="true"
attribute so that it will have precedence over normal bean
move autowiring to constructor and create Person
manually by providing a mock:
PersonDao personDao;
@Autowired
public Person(PersonDao personDao)
{
this.personDao = personDao;
}
then:
new Person(personDaoMock)
and don't rely on Spring.
you can modify private field using ReflectionTestUtils
:
ReflectionTestUtils.setField(person, "personDao", mock);
Upvotes: 1