[英]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)
. 我想测试我的服务方法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. CorrectionService
将调用AddressDAO
的方法,该方法将删除Person
具有的某些Adress
。 One Person
has Many Address
es 一个Person
有很多Address
I'm not sure what the basic structure must be of my CorrectionServiceTest.testCorrectPerson
. 我不确定我的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. 也请/不确认此测试中我不需要测试是否实际删除了地址(应在AddressDaoTest
完成),只需调用DAO方法即可。
Thank you 谢谢
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);
}
}
A simplified version of the CorrectionService class (visibility modifiers removed for simplicity). CorrectionService类的简化版本(为简单起见删除了可见性修饰符)。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.