我是模拟测试的新手。
我想测试一下我的服务方法CorrectionService.correctPerson(Long personId)
。
该实现尚未编写,但这就是它将要做的:
CorrectionService
会调用AddressDAO
的方法,该方法会删除Adress
所拥有的Person
部分内容。一个Person
有多个Address
es
我不确定CorrectionServiceTest.testCorrectPerson
的基本结构是什么。
另外请确认/不确认在此测试中我不需要测试地址是否实际被删除(应该在AddressDaoTest
中完成),只是调用了DAO方法。
谢谢
答案 0 :(得分:13)
清洁版:
@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);
}
}
答案 1 :(得分:5)
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);
}
}