vendredi 24 août 2018

Best way to test Java Program

I wanted to test the below java program.

package com.arrays;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Find all pairs in an array of non-negative unique numbers whose sum is equal to k
 * For Example. {1,3,4,5,6} and k=9, then {3,6} and {4,5}
 *
 */
public class FindAllPairsIfSumToK {

    public List<Pair> findAllPairsWhoseSumIsK(int[] inputArray, int k) {

        Set<Integer> tempSet = new HashSet<>();
        List<Pair> pairs = new ArrayList<>();

        for(int i=0;i<inputArray.length;i++) {
            tempSet.add(inputArray[i]);
        }

        for(int i=0;i<inputArray.length;i++) {
            if((2*inputArray[i] != k) && tempSet.contains(k-inputArray[i])) {
                pairs.add(new Pair(inputArray[i], k-inputArray[i]));
            }
        }

        return pairs;
    }

    public static void main(String[] args) {

        FindAllPairsIfSumToK findAllPairsIfSumToK = new FindAllPairsIfSumToK();

        //Test 1
        int[] inputArray1 = {1, 3, 5, 7, 9, 11};
        List<Pair> output1 = findAllPairsIfSumToK.findAllPairsWhoseSumIsK(inputArray1, 10);
        assert (output1.size() == 2) ;

        //Test 2
        int[] inputArray2 = {1, 2, 5, 6, 12, 15, 16};
        List<Pair> output2 = findAllPairsIfSumToK.findAllPairsWhoseSumIsK(inputArray2, 17);
        assert (output2.size() == 3) ;
    }

    class Pair{
        int value1,value2;

        public Pair(int value1, int value2) {
            this.value1 = value1;
            this.value2 = value2;
        }
    }
}

This is how I'm trying to test the program

//Test 1
            int[] inputArray1 = {1, 3, 5, 7, 9, 11};
            List<Pair> output1 = findAllPairsIfSumToK.findAllPairsWhoseSumIsK(inputArray1, 10);
            assert (output1.size() == 2) ;

I Googled it, But most of them are telling about testing the web application. Is it a proper way to test the program? Or Could you please guide?

Aucun commentaire:

Enregistrer un commentaire