Nisal Pubudu
Nisal Pubudu

Reputation: 23

How to mock a method in Service layer

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?

Upvotes: 2

Views: 2653

Answers (2)

Ivan Agrenich
Ivan Agrenich

Reputation: 2281

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:

Upvotes: 1

João Dias
João Dias

Reputation: 17460

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

}

Upvotes: 2

Related Questions