Home > Blockchain >  How to mock a method in Service layer
How to mock a method in Service layer

Time:10-25

While doing unit tests on each method of the service layer, I have encountered the below scenario, that I couldn’t figure out how to test:

public class UserServiceImpl{

    @Autowired
    UserRepository userRepository;

    public void abc(){
        xyz(obj);
    }

    private void xyz(){
        userRepository.save(obj);
    }
}

What I want to test is the abc() method. Within that method, it invokes xyz() which is a PRIVATE method that uses the userRepository dependency. So, when I create a unit test for the abc() method, do I need to be concerned about the xyz() method since it is using a dependency? And if yes, what are the steps that I need to follow?

CodePudding user response:

As you wrote you need to deal with xyz() method and its call to userRepository. You need to mock userRepository as follows:

@ExtendWith(MockitoExtension.class)
public class UserServiceImplTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    public UserServiceImpl userService;

    @BeforeEach
    public void setUp() throws Exception {
        // Mock UserRepository behaviour
        doReturn(//return value).when(this.userRepository).save(any());
    }

    // Your tests here

}

CodePudding user response:

Since this is a void method, what you want to do is verify that the save method of the dependency has been called exactly once with the parameter obj. You could do this by using something like Mockito. Your unit test would look something like this:

    @Mock
    private UserRepository mockUserRepository;

    @InjectMocks
    private UserServiceImpl sut;

    @Test
    public void abc_savesObject() {
        // Arrange
        ...

        // Act
        sut.abc();

        // Assert
        verify(mockUserRepository,times(1)).save(obj);
    }

Some useful links:

  • Related