JUnit test - 在类实例上调用的方法

时间:2014-02-27 08:40:42

标签: java junit mockito

我的方法

的JUnit测试有问题
@Transactional
@Override
public void deleteOffer(Offer offer) {
    List<String> offerPictures = this.getOfferPictures(offer);
    if (offerPictures != null) {
        System.out.println(offerPictures.size());
        for (String stringName : offerPictures) {
            this.deleteSinglePhoto(new File(hardDiscAddress + stringName));
            this.deleteSinglePhoto(new File(hardDiscAddress + "sm_" + stringName));
        }
    }
    offerDAO.delete(offer.getId());
}

我已经测试了空offerPcitures列表,但现在我需要为非空列表编写一个。问题是我不知道如何模拟getOfferPictures方法返回非空字符串列表

@Override
public List<String> getOfferPictures(Offer offer) {
    File dir = new File(hardDiscAddress);
    List<String> resultantlist = new ArrayList<String>();
    if (dir.isDirectory()) {
        for (final File f : dir.listFiles()) {
            if (f.getName().startsWith(offer.getPhotography())) {
                resultantlist.add(f.getName());
            }
        }
    }
    return resultantlist;
}

这是列表

的测试
@Test
public void testDeleteOffer() {
    // given
    testOfferServiceImpl = new OfferServiceImpl();
    testOfferServiceImpl.hardDiscAddress = "C:/";
    testOfferServiceImpl.offerDAO = offerDAOMock;
    when(offerMock.getId()).thenReturn(1);
    when(offerMock.getPhotography()).thenReturn("stringForTest");
    doNothing().when(offerDAOMock).delete(1);
    // when
    testOfferServiceImpl.deleteOffer(offerMock);
    // then
    Mockito.verify(offerDAOMock, times(1)).delete(1);
}

2 个答案:

答案 0 :(得分:0)

使用像Mockito这样的东西。你可以这样做:

Candidate candidate = mock(Candidate.class);
when(candidate.getFirstName()).thenReturn("Bob");

这是项目的一个例子,效果很好。您还必须使用以下命令注释您的测试类:

@RunWith(MockitoJUnitRunner.class)

然后你可以让方法返回你喜欢的任何东西。希望有所帮助:)

答案 1 :(得分:0)

您可以使用Mockito.spy部分模拟您正在测试的实例,并返回非空列表:

@Test
public void testNotEmptyOffer() {
    // Given
    testOfferServiceImpl = new OfferServiceImpl();
    testOfferServiceImpl.hardDiscAddress = "C:/";
    testOfferServiceImpl.offerDAO = offerDAOMock;

    // Spy (partially mock) the object
    testOfferServiceImpl = Mockito.spy(testOfferServiceImpl);
    doReturn(Arrays.asList("one", "two", "three")).
       when(testOfferServiceImpl).getOfferPictures(offerMock)

    // Test your logic here
}