Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

后端 未结 5 1080
庸人自扰
庸人自扰 2020-12-12 16:01

I was learning mockito and I understood the basic usages of the above mentioned functions from the link.

But I would like to know whether it can be used for any othe

5条回答
  •  旧巷少年郎
    2020-12-12 16:51

    A very simple example is that if you have a UserService that has @Autowired jpa resposiroty UserRepository

    ...
    class UserService{
    
      @Autowired
      UserRepository userRepository;
    ...
    }
    

    then in the test class for UserService you will do

    ...
    class TestUserService{
      @Mock 
      UserRepository userRepository;
    
      @InjectMocks
      UserService userService;
    
    ...
    }
    

    @InjectMocks tells the framework that take the @Mock UserRepository userRespository; and inject that into userService so rather than auto wiring a real instance of UserRepository a Mock of UserRepository will be injected in userService.

提交回复
热议问题