import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Write a description of class Discipline here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Discipline
{
private String disciplineName;
private HashMap <EliteSwimmer, Result> eliteResults;
/**
* Constructor for objects of class Discipline.
* @param disciplineName The discipline name.
*/
public Discipline(String disciplineName)
{
this.disciplineName = disciplineName;
eliteResults = new HashMap<EliteSwimmer, Result> () ;
}
/**
* Get the value of disciplineName.
* @return the value of disciplineName.
*/
public String getDisciplineName ()
{
return disciplineName;
}
/**
* Add the elite swimmer's best training result.
* @param elite The elite member.
* @param res The elite member's best training result.
*/
public void addEliteResults(EliteSwimmer elite, Result res)
{
if (res.getType() == 0) {
eliteResults.put(elite, res);
}
else {
System.out.println("Not a training result");
}
}
/**
* Print a list with the elite swimmers' best training results.
*/
public void printListofResults()
{
Set set = eliteResults.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.println("Elite Swimmer: "+ ((EliteSwimmer)mentry.getKey()).getName());
System.out.println("Result: " + ((Result) mentry.getValue()).getTime());
}
}
/**
* Print a list with the top 5 elite swimmers, based on their training results.
*/
public void Top5List()
{
Set<Entry<EliteSwimmer,Result>> set = eliteResults.entrySet();
List<Entry<EliteSwimmer,Result>> list = new ArrayList<Entry<EliteSwimmer,Result>>(set);
Collections.sort( list, new Comparator<Map.Entry<EliteSwimmer,Result>>()
{
@Override
public int compare( Map.Entry<EliteSwimmer,Result> o1, Map.Entry<EliteSwimmer,Result> o2 )
{ return Double.compare(o1.getValue().getTime(), o2.getValue().getTime() ); }
});
LinkedHashMap<EliteSwimmer,Result> sortedHashMap=new LinkedHashMap<EliteSwimmer,Result>();
for (Map.Entry<EliteSwimmer,Result> entry: list) {
sortedHashMap.put(entry.getKey(), entry.getValue());
}
int counter = 0;
for(Map.Entry<EliteSwimmer,Result> entry: list)
{counter ++;
System.out.println("Elite swimmer: " + entry.getKey().getName()+" Result: " +entry.getValue().getTime());
if (counter == 5)
break;
}
}
}
答案 0 :(得分:0)
快速浏览最简单的测试方法是将打印问题与业务行为分开。换句话说,有一个方法可以找到前5名游泳者,将它们作为方法签名的一部分返回,并测试该方法为特定场景返回正确的游泳者。它们的打印可以单独完成 - 可能完全由另一个类完成。
单元测试的支持者认为它可以产生更好的因子代码 - 混合的关注点更难以测试,而具有单一责任的代码更容易测试,并且在将来更容易理解,维护和发展。 / p>
答案 1 :(得分:0)
您想要测试代码真是太棒了,这是正确的方法。但是,对于当前的实现,很难做出特定的断言,因为你对 Top5List 的功能很多。 将其拆分为较小的逻辑部分,并对其进行测试。例如:
然后分别进行单元测试。
也是一般建议,尝试彼此旁边进行测试和编码, 那么,最难以测试这样的代码。