Home > Enterprise >  Want to mock a dependency that belongs to another class
Want to mock a dependency that belongs to another class

Time:10-28

What I want to test is abc() method from UserServiceImpl class. Within that method it invokes xyz(), which is belongs to UserDao dependency. In UserDao class it has a dependency of UserRepository and xyz() method uses it. So how can I mock UserRepository dependency when I test abc() method? Really appreciate any kind of help.

    public class UserServiceImpl{

    @Autowired
    UserDao userDao;

    public void abc(){
        userDao.xyz("a");
    }
    }

    public class UserDao{

    @Autowired
    UserRepository userRepository;

    public void xyz(String a){
        Optional<User> userOptional = userRepository.findByName("mike");
    }
    }

CodePudding user response:

If you want to test UserServiceImpl.abc() then mock UserDao and define a return value for UserDao.xyz() I see you have void method without parameter but for the example have String as param and return with a User.

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes={UserServiceImpl.class})
public class UserServiceImplTest{

    @Autowired
    UserServiceImpl userSvc;

    @MockBean
    UserDao userDao;
    
    @Test
    public void abcTest(){
        //define User to return and the mock
        User userToReturn = new User("Mike");

        when(userDao.xyz("mike")).thenReturn(userToReturn);
        User retUser=userSvc.abc("mike");

        //do some assertion...

    }
}

If you want to test UserDao then do this in its own Test class.

CodePudding user response:

If you mock UserDao you don't need to mock UserRepository because only the real UserDao needs it.

And if you move your @Autowired annotation to the constructor it will be easier to inject in your test.

public class UserServiceImpl{


    private final UserDao userDao;

    @Autowired
    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    public void abc(){
        userDao.xyz("a");
    }

}

Test:

UserDao userDao = mock(UserDao.class);

UserServiceImpl subject = new UserServiceImpl(userDao);
subject.abc();
[...]
  • Related