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

时间:2010-02-18 12:02:56

标签: java testing junit mocking mockito

我是模拟测试的新手。

我想测试一下我的服务方法CorrectionService.correctPerson(Long personId)。 该实现尚未编写,但这就是它将要做的:

CorrectionService会调用AddressDAO的方法,该方法会删除Adress所拥有的Person部分内容。一个Person有多个Address es

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

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

谢谢

2 个答案:

答案 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);
    }
}