tags:

views:

45

answers:

1

I have the following code:

public void someMethod() {
     Set<Foo> fooSet = bar.getFoos();

     for(Foo foo: fooSet) {
         foo.doSomething();
     }
}

and I want to test this using JMockit but am unsure how to get to return a collection of a certain type and size.

The following test for my code throws a null pointer exception for hashcode when trying to add foo to the set of foos.

@Test
public void someTestMethod()
{
     new Expectations()
     {
         @Mocked Bar bar;
         @Mocked Foo foo;


         Set<Foo> foos = new HashSet<Foo>();
         foos.add(foo);

         bar.getFoos(); returns(foos);
         foo.doSomething();
     };

     new SomeClass().someMethod();
}

How should this be done?

+1  A: 

I'm not exactly sure how to answer your question because I don't understand what you are trying to test, but I believe you want something like this:

@Test
public void someTestMethod(@Mocked(methods="getFoos")final Bar mockedBar
                           @Mocked(methods="doSomething")final Foo mockedFoo {

   final Set<Foo> foos = new HashSet<Foo>();
   foos.add(new Foo()); 

   new Expectations() {
      {
         mockedBar.getFoos(); returns(foos);
         mockedFoo.doSomething();
      }
   };

   new SomeClass().someMethod();
}

Using this, JMockit will mock the call to getFoos and return the Set foos. If you look at the parameters I am passing in, I am doing a partial mock of the Bar and Foo classes (I am only mocking the calls to the getFoos and doSomething method). I also noticed you are missing a set of braces in your new Expectations block, so that could definitely cause you some problems. One other issue you have to keep in mind is that using Expectations as opposed to NonStrictExpectations will cause an error if you put more than one object in the Set foos because it is only expecting one call to doSomething. If you make a test case where foos has more than one object in it you could either use NonStrictExpectations or use the minTimes and maxTimes to specify invocation count constraints

chanes