mardi 17 juillet 2018

JUnit test - how to check Scanner for various input mismatches

I'm trying to write JUnit tests for a program that converts Fahrenheit degrees to Celsius degrees (and opposite). So my class looks like:

package asdf;

import java.util.Scanner;

public class UnitTesting {

    public int returnInt()
    {
        Scanner scanner = new Scanner(System.in);
        int x = scanner.nextInt();
        return x;
    }

    public double returnDouble()
    {
        Scanner scanner = new Scanner(System.in);
        double x = scanner.nextDouble();
        return x;
    }

    public double convertCtoF(double c) {
        double result=0;
        //do the conversion
        return result;
    }

    public double convertFtoC(double f) {
        double result=0;
        //do the conversion
        return result;
    }

    public void menu()
    {
        int a;
        do {
            System.out.println("1 - convert C degrees to F degrees");
            System.out.println("2 - convert F degrees to C degrees");
            System.out.println("0 - exit");
            a = returnInt();
            switch(a)
            {
            case 1:
                convertCtoF(returnDouble());
                break;
            case 2:
                convertFtoC(returnDouble());
                break;
            case 0:
                System.out.println("Bye!");
                break;
            default:
                System.out.println("Choose 1, 2 or 0");
                break;
            }
        }
        while(a!=0);
    }

    public static void main(String [] args)
    {
        UnitTesting ut = new UnitTesting();
        ut.menu();
    }
}

Since I wanted to test the user input's for various mismatch exceptions (NumberFormat, InputMismatch etc.) but I have no idea if this approach is possible for current methods returnDouble() and returnInt(). I was thinking of changing scanner to read input as a string (nextLine) but then extra parsing method would be needed. What would be needed to alter the methods/class to check if input is a number at all, or has a good format given by the user - in an "elegant" way?

Thank you

Aucun commentaire:

Enregistrer un commentaire