Virat
Virat

Reputation: 581

Creating java.util.map.Entry instance to help unit testing

In my code, I have a for loop like,

for( final Entry<Object, Object> entry : fileTypeProperties.entrySet()) {
    saveFileTypeToCompany(registeredCompany,
             entry.getKey().toString(), 
             entry.getValue().toString());
}

So, while unit testing, how to create an instance of Entry (i.e., java.util.map.Entry) ?

Upvotes: 1

Views: 2355

Answers (2)

sprinter
sprinter

Reputation: 27976

  • You can't create a Map.Entry directly as it's an interface. You could create your own class that implements the interface if you want to.

  • I can't understand why you'd want to create an entry for the purpose of unit testing. If you are testing saveFileTypeToCompany then you pass it the key and value of the entry, not the entry itself. So to unit test you pass test values to the function. If you are testing the code you are showing then you need to populate the map to test it properly. I can't see any scenario in which you need to create an entry directly.

  • If you do need to unit test with a Map.Entry then use mocking. You can mock the interface and then define what is returned by getKey and getValue.

  • If you are using Java 8 then your code can be simplified to: fileTypeProperies.forEach((k, v) -> saveFileTypeToCompany(company, k, v));

Upvotes: 1

Vasu
Vasu

Reputation: 22442

What actually you need to do is to load your fileTypeProperties with some properties as shown below so that when you call fileTypeProperties.entrySet(), it will return the Entry objects.

Map<Object, Object> fileTypeProperties = new HashMap<>();
// add some dummy property values to fileTypeProperties

Upvotes: 0

Related Questions