>> 用于测试,java,spring-boot,junit,mockito"/>

首页 > 解决方案 > 将字符串转换为列表>> 用于测试

问题描述

我需要将 a 转换StringList<Map<String, String>>>通过 JUnit 测试。我有这个:

String userAttributes = "[{name=test, cp=458999, lastname=test2}]";

我想要的是在测试(Mockito)中更改对具有此值的服务器的调用,如下所示:

Mockito.when(template.search(Mockito.anyString, new AttributesMapper()).thenReturn(attributes);

我需List<Map<String, String>>>要这样做:

user.setUserName(attributes.get("name"));

标签: javaspring-bootjunitmockito

解决方案


尝试正则表达式或按特殊字符拆分。首先删除开头和结尾的括号。之后,您可以将其拆分,=收集要映射的字符串。

String userAttributes = "[{name=test, cp=458999, lastname=test2}]";

List<String> strings = Arrays.asList(userAttributes
      .replace("[{","").replace("}]","")
      .split(", "));
Map<String, String> collect = strings.stream()
      .map(s -> s.split("="))
      .collect(Collectors.toMap(s -> s[0], s -> s[1]));

System.out.println(collect.get("name"));

其他方法Pattern

Map<String, String> collect = Pattern.compile(",")
        .splitAsStream(userAttributes
                .replace("[{","").replace("}]",""))
        .map(s -> s.split("="))
        .collect(Collectors.toMap(s -> s[0], s -> s[1]));

或者,如果您真的想使用List<Map<String, String>>>. 但在那之后你不能这样做user.setUserName(attributes.get("name"));

List<Map<String, String>> maps = strings.stream()
      .map(s -> s.split("="))
      .map(s -> Map.of(s[0], s[1]))
      .collect(Collectors.toList());

System.out.println(maps);

推荐阅读