I've often faced with something like this
public void methodToTest() {
Set<String> names = dependencyDao.getNamesFromExternalDataSource();
for (String name : names) {
externalService.doSomethingWithName(name);
//....
}
}
so on the end I need to mock the expected result from my dependencyDao
to verfiy my behaviour on my externalService
which is fine on generic values but what is the "cleanest" way to mock a Set or List like in my example above? Creating a HashSet<String>
with one value doesn't seem to be the right thing here.
Don't try to mock the set, or any other kind of collection for that matter. Mocking a collection is far more trouble than it's worth, when it's easy to make a collection, possibly with mocks inside.
You probably want to make sure that the method works correctly whether or not the returned collection is empty. If I were testing this, I would have a test methods for each of these cases.
But these will each be "real" collections, not mocks.