Issue
I'm using @MethodSource annotation on my Junit test case in order to receive from another method a Map<String, Object>.
Seems that @MethodSource cannot support "Map" object.
This is the error I received: org.junit.platform.commons.PreconditionViolationException: Cannot convert instance of java.util.HashMap into a Stream: {1=Obj1, 2=Obj2}
Do you know if there is a way to receive back a "Map" object like in this example?
@ParameterizedTest
@MethodSource("hashMapProvider")
void testMyMapObj(Map<String, Object> argument) {
assertNotNull(argument);
Object obj1 = argument.get("1");
}
static Map<String, Object> hashMapProvider() {
Map<String, Object> map = new HashMap<>();
map.put("1", "Obj1");
map.put("2", "Obj2");
return map;
}
Solution
If your argument in test method is Map<String, Object>
, use as return value Stream<Map<String, Object>>
in source method:
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.Map;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class SimpleTest {
@ParameterizedTest
@MethodSource("hashMapProvider")
void test(Map<String, Object> argument) {
System.out.println(argument);
assertNotNull(argument);
}
static Stream<Map<String, Object>> hashMapProvider() {
return Stream.of(
Map.of("1", "Obj1", "2", "Obj2"),
Map.of("3", "Obj3")
);
}
}
Answered By - Georgy Lvov
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)