英文:
List<String> JUnit
问题
@Test
public void Test() {
Tester rd = new Tester();
Assert.assertSame(variable.getList(), "banana, apple, pineapple");
}
So variable.getList would return a List
how can I turn ("banana, apple, pineapple") into ["banana, apple, pineapple"]??
英文:
@Test
public void Test() {
Tester rd = new Tester();
Assert.assertSame(variable.getList(), ("banana, apple, pineapple"));
}
So variable.getList would return a List<String>, so when I run the test there's going to be an error because ["banana, apple, pineapple"] is differente from "banana, apple, pineapple" .
how can I turn ("banana, apple, pineapple") into ["banana, apple, pineapple"]??
答案1
得分: 3
首先,assertSame
断言两个参数引用同一对象(即相当于使用 ==
进行比较)。这几乎永远不是您想要断言的内容。更有可能您会想要使用 assertEquals()
。
其次,如果您想要检查结果是否等于包含三个字符串对象的列表,可以使用类似 List.of
的方式构造这样一个列表:
Assert.assertEquals(variable.getList(), List.of("banana", "apple", "pineapple"));
如果您受限于 Java 9 之前的版本,那么Arrays.asList()
在这种情况下是足够替代 List.of
的。
英文:
First of: assertSame
asserts that the two parameters reference the same object (i.e. it's equivalent to using ==
). This is almost never what you want to assert. It's much more likely you'll want to use assertEquals()
.
Second, if you want to check if the result is equal to a List with three string object, then construct such a list with something like List.of
:
Assert.assertEquals(variable.getList(), List.of("banana", "apple", "pineapple"));
If you are restricted to a Java version before Java 9, then Arrays.asList()
is a good enough replacement for List.of
in this case.
答案2
得分: 0
首先,我会使用assertEquals
进行相等性测试(即使用equals
方法),而不是使用asssertSame
进行身份测试(即使用==
操作符)。
其次,不同于你当前所拥有的字符串,你需要将它包装在一个List
中:
Assert.assertEquals(variable.getList(), Collections.singletonList("banana, apple, pineapple"));
英文:
First, I'd use assertEquals
that tests for equality (i.e., uses the equals
method) instead of asssertSame
, what tests for identity (i.e., uses the ==
operator).
Second, instead of a string like you currently have, you'll need to wrap it in a List
:
Assert.assertEquals(variable.getList(), Collections.singletonList("banana, apple, pineapple"));
答案3
得分: 0
可以使用列表代替固定字符串。
final String[] expectedResult = new String[] { "banana", "apple", "pineapple" };
Assert.assertEquals(variable.getList(), Arrays.asList(expectedResult));
英文:
You can use a list instead of a fixed string.
final String[] expectedResult = new String[] { "banana", "apple", "pineapple" };
Assert.assertEquals(variable.getList(), Arrays.asList(expectedResult));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论