Reputation: 3664
I'm writing unit test case using Junit, EasyMock and Spring. I'm trying to mock DAO layer call. I've used annotation to inject bean in my application
Service layer class:
public class CustomerService {
@Autowired
private CustomerDao customerDao;
........
public void findCustomerByAccountNumber(String accountNumber){
}
}
Test case for service method:
public class CustomerServiceTest extends AbstractContextConfigLoaderTest{
private CustomerDao mockCustomerDao;
private CustomerService customerService;
private String accountNumber="5247710009575432";
@Before
public void setUp(){
mockCustomerDao= EasyMock.createMock(CustomerDao.class);
customerService= new CustomerService();
}
if i would have used setter injection using Spring bean configuration, i would've set mocked dao object to customerService like below.
customerService.setCustomerDao(mockCustomerDao);
How can i do the same in case of Spring annotation ?
Upvotes: 0
Views: 226
Reputation: 21184
Why not expose this through the constructor and inject it that way? Your production code can use Spring and your test code can just instantiate the object directly.
At the moment you're at the mercy of your DI framework. Break that dependency.
Upvotes: 0
Reputation: 1
I suggest enabling spring in your test with something like @RunWith(SpringJUnit4ClassRunner.class) and @ContextConfiguration, in your spring context for the test make the mock as spring bean.
<bean class="org.easymock.EasyMock" factory-method="createMock">
<constructor-arg value="some.package.CustomerDao" />
</bean>
Now should be wired to the CustomerService, to record the expected behavior you will need to wire the mock in your test class:
@Autowired
private CustomerDao mockCustomerDao;
@Autowired
private CustomerService customerService;
Upvotes: 0
Reputation: 11
You can use still setup a method
protected void setCustomerDao(CustomerDao customerDao)
and only use it in your JUnit to set the mocked dependencies. The protected access will prevent any class that is not in the same package from using that method.
Upvotes: 1