Mockito:如何通过模拟测试我的服务?

Mic*_*vin 5 java testing junit mocking mockito

我是模拟测试的新手.

我想测试我的Service方法CorrectionService.correctPerson(Long personId).该实现尚未编写,但它将如何做:

CorrectionService将调用的方法AddressDAO,将删除一些的Adress一个Person了.其中Person有许多AddressES

我不确定我的基本结构是什么CorrectionServiceTest.testCorrectPerson.

另外请确认/不确认在此测试中我不需要测试地址是否实际被删除(应该在a中完成AddressDaoTest),只是调用了DAO方法.

谢谢

Mar*_*szS 14

清洁版:

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 5

CorrectionService类的简化版本(为简单起见,删除了可见性修饰符).

class CorrectionService {

   AddressDao addressDao;

   CorrectionService(AddressDao addressDao) {
       this.addressDao;
   }

   void correctPerson(Long personId) {
       //Do some stuff with the addressDao here...
   }

}
Run Code Online (Sandbox Code Playgroud)

在你的测试中:

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);
    }
}  
Run Code Online (Sandbox Code Playgroud)