tags:

views:

233

answers:

1

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?

+2  A: 

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);
Fried Hoeben
You were right. Thanx a lot!I have another question:My Service interface looks something like this:FAQ getFAQ(long id); List<FAQ> getAllOrderedDescByRating(); SearchResult<FAQ> getResults(SearchCriteria searchCriteria); void saveFAQ(FAQ faq); void deleteFAQ(FAQ faq);Do I need to test all the methods?
cc
I believe you should test all methods, even all lines and branches in them.
Fried Hoeben