I have the following code snippets in my spring boot application:
@Service
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
public UserServiceImpl(UserRepository ...) {...}
@Override
public void saveOrUpdateUser(UserDAO user) {
userRepository.save(user);
}
}
Test case class:
class UserServiceImplUnitTest {
private UserRepository userRepository = mock(UserRepository.class);
private UserService userService;
@BeforeEach
void setup() {
userService = new UserServiceImpl(userRepository);
}
}
I am using mockito to write my test cases. However, for this void method should i write test case(s)? If yes, how can i write it?
CodePudding user response:
Yes. You should mainly focus on whether UserServiceImpl
interacts with UserRepository
in an expected way such as the things like if it invokes the correct method on the UserRepository
with the correct arguments etc.
By using Mockito to mock the UserRepository
, you may end up with a test something like as follows :
@ExtendWith(MockitoExtension.class)
public class UserServiceImplUnitTest {
@Mock
UserRepository userRepository ;
UserService userService;
@BeforeEach
void setup() {
userService = new UserServiceImpl(userRepository);
}
@Test
public void testSaveOrUpdateUser(){
UserDAO user = createDummyUser();
userService.saveOrUpdateUser(user);
verify(userRepository).save(same(user));
}
}