如何迭代并填充writeFields()的参数,使用哈希映射。

huangapple go评论61阅读模式
英文:

how can iterate and populate the writeFields() arguments, with a hashmap

问题

你可以尝试使用HashMap来更好地填充setUp方法中的writeField()。以下是一个示例:

public class testing {

    @InjectMocks
    private Test test;

    @Before
    public void setUp() throws IllegalAccessException {
        HashMap<String, String> fieldValues = new HashMap<>();
        fieldValues.put("x1", "a");
        fieldValues.put("x2", "b");
        fieldValues.put("x3", "/c");
        fieldValues.put("x4", "d");
        fieldValues.put("x5", "e");
        fieldValues.put("x6", "f");

        for (Map.Entry<String, String> entry : fieldValues.entrySet()) {
            FieldUtils.writeField(test, entry.getKey(), entry.getValue(), true);
        }
    }
}

这样,你可以使用循环遍历HashMap来填充writeField(),使代码更简洁和可维护。

英文:

I have this code, it is a junit test class. I want to come up with a better way to populate writeField() inside the setUP method.

Can i use a hashmap? any examples

public class testing {

    @InjectMocks
    private Test test;

    @Before
    public void setUp() throws IllegalAccessException {

        FieldUtils.writeField(test, &quot;x1&quot;, &quot;a&quot;, true);
        FieldUtils.writeField(test, &quot;x2&quot;, &quot;b&quot;, true);
        FieldUtils.writeField(test, &quot;x3&quot;, &quot;/c&quot;, true);
        FieldUtils.writeField(test, &quot;x4&quot;, &quot;d&quot;, true);
        FieldUtils.writeField(test, &quot;x5&quot;, &quot;e&quot;, true);
        FieldUtils.writeField(test, &quot;x6&quot;, &quot;f&quot;, true);
    }

  
}

basically having FieldUtils.writeField inside a for loop and have populate.

答案1

得分: 1

err, um.. yes?

Map<String, String> myStuff = new HashMap<String, String>();
map.put("subNavLabel", "Marketing");
// ... more map put statements
for (var entry : map.entySet()) {
FieldUtils.writeField(test, entry.getKey(), entry.getValue(), true);
}


这似乎对我来说是非常基础的Java,毫无疑问,这个简单的答案回应了您的问题,如所述。如果不足够,请考虑更新您的问题或提出一个更详细的问题。
英文:

err, um.. yes?

Map&lt;String, String&gt; myStuff = new HashMap&lt;String, String&gt;();
map.put(&quot;subNavLabel&quot;, &quot;Marketing&quot;);
// ... more map put statements
for (var entry : map.entySet()) {
    FieldUtils.writeField(test, entry.getKey(), entry.getValue(), true);
}

This seems extremely first steps java to me, surely this trivial answer isn't what you want, but it answers the question as stated. If it doesn't suffice, consider updating your question or asking a new one with (a lot) more detail.

huangapple
  • 本文由 发表于 2020年7月29日 01:11:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63139382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定