Mockito: How to test my Service with mocking?
43,639
Solution 1
A simplified version of the CorrectionService class (visibility modifiers removed for simplicity).
class CorrectionService {
AddressDao addressDao;
CorrectionService(AddressDao addressDao) {
this.addressDao;
}
void correctPerson(Long personId) {
//Do some stuff with the addressDao here...
}
}
In your test:
import static org.mockito.Mockito.*;
public class CorrectionServiceTest {
@Before
public void setUp() {
addressDao = mock(AddressDao.class);
correctionService = new CorrectionService(addressDao);
}
@Test
public void shouldCallDeleteAddress() {
correctionService.correct(VALID_ID);
verify(addressDao).deleteAddress(VALID_ID);
}
}
Solution 2
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);
}
}
Author by
Michael Bavin
Updated on July 15, 2020Comments
-
Michael Bavin almost 4 years
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 ofAddressDAO
that will remove some of theAdress
that aPerson
has. OnePerson
has ManyAddress
esI'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