Question

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.

Was it helpful?

Solution 2

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.

  • The returned collection is empty.
  • The returned collection has many elements - three is probably enough.
  • The returned collection is a singleton.

But these will each be "real" collections, not mocks.

OTHER TIPS

Creating a Set<String> with one value is exactly what I would do.

when(dependencyDao.getNamesFromExternalDataSource())
        .thenReturn(Collections.singleton("name"));

methodToTest();

verify(externalService).doSomethingWithName("name");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top