mardi 18 août 2015

Testing a main method

having a main method and all the logic in it how can I test (simulate) the input.txt in Junit should I divide the code in smaller parts so I can call it by methods? a file input should look like below

input.txt
add 2
add 2
apply 3
correct result 3 + 2 + 2 = 7




public class Main {

public static void main(String[] args) {


    List<Operation> listOperations = new ArrayList<Operation>();
    int size = listOperations.size()-1;
    int keepingCount = 0;

     try {
         File file = new File("input.txt");
         Scanner input = new Scanner(file);

         while(input.hasNextLine()){
             String line = input.nextLine();
             String[] parts = line.split(" ");
             String operationSign = parts[0];
             int numberFromLine = Integer.parseInt(parts[1]);
             Operation operation = new Operation();
             operation.setCalculation(operationSign);
             operation.setNumber(numberFromLine);

             if(!operation.getCalculation().equals("apply")){
                 listOperations.add(operation);
             }else{
                 listOperations.add(operation);
                 break;
             }                              
         }
         input.close();


         for(int x=0 ; x<size ; x++){


             if(listOperations.get(x).calculation.equals("add")){
                 if (keepingCount == 0) {
                     keepingCount = listOperations.get(x).number + listOperations.get(size).number;
                 } else {
                     keepingCount = listOperations.get(x).number + keepingCount; 
                 }
             }
             if(listOperations.get(x).calculation.equals("multiply")){
                 if (keepingCount == 0) {
                     keepingCount = listOperations.get(x).number * listOperations.get(size).number;
                 } else {
                     keepingCount = listOperations.get(x).number * keepingCount;
                 }
             }
             if(listOperations.get(x).calculation.equals("substract")){
                 if (keepingCount == 0) {
                     keepingCount = listOperations.get(x).number - listOperations.get(size).number;
                 } else {
                     keepingCount = keepingCount - listOperations.get(x).number;
                 }
             }
             if(listOperations.get(x).calculation.equals("divide")){
                 if (keepingCount == 0) {
                     keepingCount = listOperations.get(size).number/listOperations.get(x).number;
                 } else {
                     keepingCount = keepingCount/listOperations.get(x).number;
                 }
             }




          }
         System.out.println(keepingCount);


     } catch (Exception ex){
         ex.printStackTrace();
     }


}

}

Aucun commentaire:

Enregistrer un commentaire