[英]Mockito: How to test my Service with mocking?
我是模拟测试的新手。
我想测试我的服务方法CorrectionService.correctPerson(Long personId)
。 该实现尚未编写,但是它将执行以下操作:
CorrectionService
将调用AddressDAO
的方法,该方法将删除Person
具有的某些Adress
。 一个Person
有很多Address
我不确定我的CorrectionServiceTest.testCorrectPerson
的基本结构是什么。
也请/不确认此测试中我不需要测试是否实际删除了地址(应在AddressDaoTest
完成),只需调用DAO方法即可。
谢谢
清洁版:
@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);
}
}
CorrectionService类的简化版本(为简单起见删除了可见性修饰符)。
class CorrectionService {
AddressDao addressDao;
CorrectionService(AddressDao addressDao) {
this.addressDao;
}
void correctPerson(Long personId) {
//Do some stuff with the addressDao here...
}
}
在您的测试中:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.