Search code examples
javajunitjunit5

How to pass map key and value as separate parameters to Junit test


first of all, I'm a java beginner and new to stacktrace, so please have mercy ;).

I have a static map and my goal is to pass the key / value pairings as separate parameters into my test.

That's my simple map:

Map<String, String> myMap=Map.ofEntries(
          entry("foo1", "bar1"),
          entry("foo2", "bar2"));

I thought of something like this:

@ParameterizedTest
@MethodSource("provideNamespaceGroupIdMapping")
void my_test(String key, String value) {

prepareFile(key);
prepareOtherStuff(value);
...
}

with a method that provides every entry as separate arguments. So probably something like this:

private static Stream<Arguments> provideNamespaceGroupIdMapping() {
  return Stream.of(
    Arguments.of(
      myMap.keySet().stream().toString(), 
      myMap.values().stream().toString()));
  }

This results in a IndexOutOfBoundsException

java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1

As I said, I'm a beginner. I tried some other ideas I had but without any success :(.

Is there even a solution for what I want to achive?


Solution

  • You are not passing actual values. You need to collect the stream objects and then pass the list to Argument.of()

    private static Stream<Arguments> provideNamespaceGroupIdMapping() {
        List<String> keys = new ArrayList<>(myMap.keySet());
        List<String> values = new ArrayList<>(myMap.values());
        return IntStream.range(0, myMap.size())
                .mapToObj(i -> Arguments.of(keys.get(i), values.get(i)));
    }
    

    When you run a parameterized test with the provideNamespaceGroupIdMapping() method as the source, each key value pair from the map should be passed as separate arguments to the my_test() method.