Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: How to test my Service with mocking?

I'm new to mock testing.

I want to test my Service method CorrectionService.correctPerson(Long personId). The implementation is not yet written but this it what it will do:

CorrectionService will call a method of AddressDAO that will remove some of the Adress that a Person has. One Person has Many Addresses

I'm not sure what the basic structure must be of my CorrectionServiceTest.testCorrectPerson.

Also please do/not confirm that in this test i do not need to test if the adresses are actually deleted (should be done in a AddressDaoTest), Only that the DAO method was being called.

Thank you

like image 329
Michael Bavin Avatar asked Feb 18 '10 12:02

Michael Bavin


People also ask

Which method is used to mock the service methods response?

Mockito when() method It should be used when we want to mock to return specific values when particular methods are called. In simple terms, "When the XYZ() method is called, then return ABC." It is mostly used when there is some condition to execute.

How do you mock an external service?

To mock the external service, we can abstract all its logic within an interface which we can implement elsewhere and use it by our functional tests, returning the outcome we need to test the behavior of our application.


1 Answers

Cleaner version:

@RunWith(MockitoJUnitRunner.class)
public class CorrectionServiceTest {

    private static final Long VALID_ID = 123L;

    @Mock
    AddressDao addressDao;

    @InjectMocks
    private CorrectionService correctionService;

    @Test
    public void shouldCallDeleteAddress() { 
        //when
        correctionService.correct(VALID_ID);
        //then
        verify(addressDao).deleteAddress(VALID_ID);
    }
}
like image 71
MariuszS Avatar answered Sep 19 '22 14:09

MariuszS