简体   繁体   中英

EasyMock: What I'm doing wrong?

So, I need to test the Service Layer for an application (I need to test some methods - this is my first contact with the testing section)

public void testGetAllOrderedDescByRating() {

    FAQ faq1 = initFAQ(new FAQ(), 5, 1L);
    FAQ faq2 = initFAQ(new FAQ(), 3, 2L);
    FAQ faq3 = initFAQ(new FAQ(), 11, 3L);

    EasyMock.expect(faqDao.getAllOrderedDescByRating()).andReturn(
            new ArrayList<FAQ>());
    EasyMock.expect(faqDao.makePersistent((FAQ) EasyMock.anyObject()))
            .andReturn(new FAQ());

    EasyMock.replay(faqDao);

    FAQService.saveFAQ(faq1);
    FAQService.saveFAQ(faq2);
    FAQService.saveFAQ(faq3);

    List<FAQ> list = FAQService.getAllOrderedDescByRating();

    Assert.assertEquals(list.get(0).getRating(), 11.0);
    Assert.assertEquals(list.get(1).getRating(), 5.0);
    Assert.assertEquals(list.get(2).getRating(), 3.0);
    EasyMock.verify(faqDao);
}

The method from the interface:

List getAllOrderedDescByRating();

I receive:

java.lang.AssertionError:
Unexpected method call makePersistent(faq.FAQ@3461d1): getAllOrderedDescByRating(): expected: 1, actual: 0 makePersistent(): expected: 1, actual: 1 (+1)

What I'm doing wrong?

It looks like your doing 3 saveFAQ calls that EasyMock sees but that you have not told it about. Any chance the FAQService you call is wired to your faqDao?

I would expect you would have added the 3 FAQ items to an ArrayList you return instead of returning an empty one, and that there would be no need to call the saveFAQ() method at all (so remove the three calls to it).

List<FAQ> l = new ArrayList<FAQ>();
FAQ faq1 = initFAQ(new FAQ(), 5, 1L);
l.add(faq1);
FAQ faq2 = initFAQ(new FAQ(), 3, 2L);
l.add(faq2);
FAQ faq3 = initFAQ(new FAQ(), 11, 3L);
l.add(faq3);

EasyMock.expect(faqDao.getAllOrderedDescByRating()).andReturn(l);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM