7

我是模拟测试的新手。

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

CorrectionService将调用一个方法,AddressDAO该方法将删除Adressa的一些内容Person。一个有Person很多Address

我不确定我的CorrectionServiceTest.testCorrectPerson.

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

谢谢

4

2 回答 2

16

更清洁的版本:

@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);
    }
}
于 2013-04-26T20:00:36.953 回答
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);
    }
}  
于 2010-02-18T12:31:10.423 回答