代码之家  ›  专栏  ›  技术社区  ›  Michael Bavin

Mockito:如何用Mocking测试我的服务?

  •  5
  • Michael Bavin  · 技术社区  · 16 年前

    我刚开始模拟测试。

    我想测试一下我的服务方法 CorrectionService.correctPerson(Long personId) . 尚未编写实现,但它将做什么:

    CorrectionService 将调用的方法 AddressDAO 这将删除一些 Adress 那一 Person 有。一 有许多 Address

    我不知道我的基本结构是什么 CorrectionServiceTest.testCorrectPerson .

    另外,请不要/不要确认在这个测试中,我不需要测试是否实际删除了地址(应该在 AddressDaoTest ,只调用了DAO方法。

    谢谢你

    2 回复  |  直到 7 年前
        1
  •  5
  •   Daniel    16 年前

    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);
        }
    }  
    
        2
  •  13
  •   MariuszS    11 年前

    清洗器版本:

    @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);
        }
    }