Mockito: كيفية اختبار خدمتي مع السخرية؟
سؤال
أنا جديد في الاختبار الوهمي.
أريد اختبار طريقة خدمتي CorrectionService.correctPerson(Long personId)
. لم يتم كتابة التنفيذ بعد ولكن هذا ما سيفعله:
CorrectionService
سوف استدعاء طريقة AddressDAO
التي ستزيل بعض من Adress
انه Person
لديها. واحد Person
لديه الكثير Address
ES
لست متأكدًا من ما يجب أن يكون الهيكل الأساسي الخاص بي CorrectionServiceTest.testCorrectPerson
.
يرجى أيضًا القيام بذلك/عدم التأكد من أنه في هذا الاختبار لا أحتاج إلى اختبار ما إذا كان يتم حذف العدوى بالفعل (يجب القيام به في أ AddressDaoTest
) ، فقط أن طريقة DAO تم استدعاؤها.
شكرًا لك
المحلول
نسخة مبسطة من فئة 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);
}
}
نصائح أخرى
نسخة أنظف:
@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);
}
}
لا تنتمي إلى StackOverflow