简体   繁体   中英

How do i test my for-loops and arraylist with JUnit in java

hey i'm newbie when it comes to testing with JUnit and i dont know how to test for-loops/ Loops. In my code you can see some of the for-loops i have to test. I mostly want to test the top5 list method and the printListOfResults. Please help a friend in need

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;
        }
    }
}

At a quick glance the easiest way to test this is to separate the concern of printing from the business behavior. In other words, have a method that finds the top 5 swimmers, returning them as part of the method signature, and test that method returns the correct swimmers for a particular scenario. The printing of them can be done separately - potentially by another class entirely.

Proponents of unit testing will argue that it can result in better factored code - mixed concerns are harder to test, whereas code with a single responsibility is easier to test and also easier to understand, maintain, and evolve in the future.

It's great that you want to test your code, and it's the right way to go. However, with the current implementation, it's hard to do specific assertions, because you function Top5List does to many things. Split it up into smaller logical parts, and do tests on that. For example:

  1. List sortSwimmers(List<> unsorted)
  2. EliteSwimmer getBestSwimmer(List swimmers)
  3. String formattedPrint(EliteSwimmer swimmer)
  4. String formattedPrint(List swimmer)

Then do unit test separatly for each.

Also a general advice, try to do tests and coding beside each other, then, it's much harder to end up hard to test code like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM