I have an enumeration type which I used as a collection of factories for other objects that implement a common interface. A simplified version of the code is:
interface Operation {
void execute();
}
enum Factory {
TYPE1(Class1::new),
TYPE2(Class2::new);
private Supplier<Operation> constructor;
Factory(Supplier<Operation> constructor) {
this.constructor = constructor;
}
Operation build() {
return constructor.get();
}
}
A simplified version of the client code looks like:
class Client {
private void run(EnumSet<Factory> required) {
for (Factory x : required) {
x.build().execute();
}
}
// Some code that calls run() with the right EnumSet
}
This all appears to work as expected, so I want to write some Unit tests.
Testing the Factory
is easy, but the Client
is proving more difficult. The problem is that I don't want to start calling the Operation
(they do a lot of work). Instead I'd like to get x.build()
return a mock object.
I've tried using PowerMocks whenNew
to trap the creation of the Operation
objects, but this doesn't work (I don't actually have any 'new' operations). I've also tried to use a Powermock 'spy', but this fails because the enumeration constants are real objects.
Any ideas?