我错误地循环遍历FreeEvent对象列表,该列表由String和相应的Enum组成。
private List<FreeEvent> freeEvents = new ArrayList<FreeEvent>();
我的JUnit测试给出了以下错误,这是不言自明的:
org.junit.ComparisonFailure:预计:万圣节之夜[1:免费万圣节晚报2:免费万圣节晚会3:免费]但是:万圣节之夜[3:免费]
我理解错误是什么,但我不知道如何修复循环以使其记住它循环的所有值。
public String displayFreeEvents() {
String name = null;
EventType type = null;
for (int i = 0; i < freeEvents.size(); i++) {
name = freeEvents.get(i).getEventName();
type = freeEvents.get(i).getEventType();
}
String event = name + ": " + type;
return event;
}
测试用例
public void testDisplayFreeEvents() {
EventHistory eventHistory = new EventHistory();
FreeEvent event1 = new FreeEvent("Halloween Evening1",EventType.FREE);
FreeEvent event2 = new FreeEvent("Halloween Evening2",EventType.FREE);
FreeEvent event3 = new FreeEvent("Halloween Evening3",EventType.FREE);
eventHistory.addFreeEvent(event1);
eventHistory.addFreeEvent(event2);
eventHistory.addFreeEvent(event3);
assertEquals("Halloween Evening1: FREE"+"\n"+"Halloween Evening2: FREE"+"\n"+"Halloween Evening3: FREE"+"\n",eventHistory.displayFreeEvents());
}
答案 0 :(得分:1)
您必须使用StringBuilder类才能通过迭代构建字符串。
所以,你的方法应该是这样的:
public String displayFreeEvents() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < freeEvents.size(); i++) {
String name = "", type = "";
name = freeEvents.get(i).getEventName();
type = freeEvents.get(i).getEventType();
stringBuilder.append(name+ " " + type); // you can add also the \n character if you wish
}
return stringBuilder.toString();
}