Mocked repository returns null
I believe you missed the whole idea of unit testing and mocking.
- When you are unit testing your
UserService
, you DO NOT want to use the realUserRepository
implementation. - You mocked a
UserRepository
, you do not expect the mock object to immediately behave as the real one. You need to make up its behavior (aka stubbing). - You should rarely need to use Spring Runner in unit test.
In order to decide the behavior of the mock object, you gotta know the expected interaction of your system-under-test (SUT, which is the UserService
in your case) and its dependencies (UserRepository
)
In your case, the test should looks like (haven't compiled, just show you the idea)
public class UserServiceTest {
@InjectMocks
UserService userService;
@Mock
UserDao mockUserRepository;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
}
@Test
public void testFindUser(){
// Given
User dummyUser = new User();
when(mockUserRepository.findByLoginAndPassword(anyString(), anyString()).thenReturn(dummyUser);
// When
User result = userService.findUser("first", "teste");
// Then
// you are expecting service to return whatever returned by repo
assertThat("result", result, is(sameInstance(dummUser)));
// you are expecting repo to be called once with correct param
verify(mockUserRepository).findByLoginAndPassword("first", "teste");
}
}
Also you can pass name parameter like ,
@MockBean(name="userRepository")
UserDao userRepository;
You need to revise your order of mocking first you should use @InjectMocks and then @Mock and before your test class name add @ExtendWith(MockitoExtension.class)
I was facing the same issue but after implementing the above steps it worked for me