0

It seems like EasyMock tests tend to follow the following pattern:

@Test
public void testCreateHamburger()
{
  // set up the expectation
  EasyMock.expect(mockFoodFactory.createHamburger("Beef", "Swiss", "Tomato", "Green Peppers", "Ketchup"))
    .andReturn(mockHamburger);

  // replay the mock
  EasyMock.replay(mockFoodFactory);

  // perform the test
  mockAverager.average(chef.cookFood("Hamburger"));

  // verify the result
  EasyMock.verify(mockFoodFactory);
}

This works fine for one test, but what happens when I want to test the same logic again in a different method? My first thought is to do something like this:

@Before
public void setUp()
{
  // set up the expectation
  EasyMock.expect(mockFoodFactory.createHamburger("Beef", "Swiss", "Tomato", "Green Peppers", "Ketchup"))
    .andReturn(mockHamburger);

  // replay the mock
  EasyMock.replay(mockCalculator);
}

@After
public void tearDown()
{
  // verify the result
  EasyMock.verify(mockCalculator);
}

@Test
public void testCreateHamburger()
{
  // perform the test
  mockAverager.average(chef.cookFood("Hamburger"));
}

@Test
public void testCreateMeal()
{
  // perform the test
  mockAverager.average(chef.cookMeal("Hamburger"));
}

There's a few fundamental problems with this approach. The first is that I can't have any variation in my method calls. If I want to test person.cookFood("Turkey Burger"), my set up method wouldn't work. The second problem is that my set up method requires createHamburger to be called. If I call person.cookFood("Salad"), then this might not be applicable. I could use anyTimes() or stubReturn() with EasyMock to avoid this problem. However, these methods only verify if a method is called, it's called with certain parameters, not if the method was actually called.

The only solution that's worked so far is to copy and paste the expectations for every test and vary the parameters. Does anybody know any better ways to test with EasyMock which maintain the DRY principle?

ZnArK
  • 1,533
  • 1
  • 12
  • 23
LandonSchropp
  • 10,084
  • 22
  • 86
  • 149

1 Answers1

2

The problems you are running into are because Unit Tests should be DAMP not DRY. Unit tests will tend to repeat themselves. If you can remove the repetition in a safe way (so that it doesnt create unnecessarily coupled tests), then go for it. If not, then don't force it. Unit tests should be quick and easy...if they aren't then you are spending too much time testing instead of writing business value.

Just my two cents. BTW, the Art of Unit Testing by Roy Osherove is a great read on unit testing, and covers this topic.

Community
  • 1
  • 1
Justin Pihony
  • 66,056
  • 18
  • 147
  • 180