Does the creation of object of Y in UserServiceImpl affect this?
In short, yes.
Basically, you've created a mock Y object and then not used it within the execution of the code. When you call xyz()
it is using the instance of Y that is created within the instance of UserServiceImpl
If you want to be able to use a mocked instance of Y, then you'll need to be able to set the instance of Y within the UserServiceImpl
class. You could do this using a setter method, like you've done for the userDao. Or it might be nicer to have a constructor for these dependencies. (Keep in mind though you may need the no-args constructor, so you'll have to add that in too)
Here's how I'd do it:
class UserServiceImpl {
private Y y = new y();
public UserServiceImpl() {
super();
}
public UserServiceImpl( final Y y, final UserDao userDao ) {
super();
this.y = y;
setUserDao(userDao); //Or however you would set this....
}
public User xyz() {
if( y.authenticateUser() ) {
//code
}
}
}
Then within your test, you would do this:
public void testxyz(){
User user1 = createUser("user1", "password", 1L);
final Y y = EasyMock.createMock(Y.class);
final UserDAO userDao = EasyMock.createMock(UserDAO.class);
final UserServiceImpl userService = new UserServiceImpl(y, userDao);
EasyMock.expect(y.authenticateUser(user1.getUsername(), user1.getPasswd())).andReturn(true);
EasyMock.expect(userDao.findByUserName(user1.getUsername())).andReturn(user1);
assertNotNull("User is null i.e not a valid user",user1);
EasyMock.replay(y, userDao );
assertEquals(userService.xyz(user1.getUsername(), user1.getPasswd()), user1);
EasyMock.verify(y, userDao );
}