Doubts to check an array in JUnit

1

I have an Array class with two constructors and some methods like initialize or invert, the problem is that I have tried several things but I do not know how to compare the method with the expected result.

I tried this:

    package test;

    import static org.junit.Assert.*;

    import org.junit.Before;
    import org.junit.Test;

    import paquete1.Array;

    public class TestArray {
        Array array;

        @Before
        public void setUp() throws Exception {
            int[] miArray1= new int[] {4,1};
            array=new Array(miArray1);  
        }

        @Test
        public void test() {
            int[] miArray= new int[]{1,4};

            assertArrayEquals(miArray,miArray1);

        }

This is the class I want to try.

   package paquete1;

public class Array {
    private int longitud;
    private int[] array;

    public Array (int longitud){
        this.longitud=longitud;
        array=new int[longitud];        
    }

    public Array(int[]array){
        this.longitud=array.length;
        this.array=array;
    }

    public int getLongitud() {
        return longitud;
    }

    public void setLongitud(int longitud) {
        this.longitud = longitud;
    }

    public int[] getArray() {
        return array;
    }

    public void setArray(int[] array) {
        this.array = array;
    }

    public void inicializar (){
        for (int i = 0; i < array.length; i++) {
            array[i]=(int)(Math.random()*10);
        }
    }

    public int minimo(){
        int min=Integer.MAX_VALUE;
        for (int i = 0; i < array.length; i++) {
            if (array[i]<min)
                min=array[i];
        }
        return min;
    }

    public Array ordenar(){
        int [] arrayAux=this.getArray();
        int aux;
        for (int i=0; i<arrayAux.length-1; i++)
            for (int j=i+1; j<arrayAux.length; j++)
                if (arrayAux[i]>arrayAux[j]) // si la componente i es menor que la siguiente las intercambio 
                     {                      
                        aux=arrayAux[i]; //intercambio la componente i con la siguiente
                        arrayAux[i]=arrayAux[j]; //siempre se usa una variables auxiliar para no perder los valores durante el cambio
                        arrayAux[j]=aux;
                    }


        return (new Array(arrayAux));
    }

    public Array invertir(){ //este metodo genera un objeto Array que contiene un array invertido
        Array inverso=new Array(this.longitud);//creo un objeto de la clase Array 
        //con la misma longitud que el atributo longitud
        for (int i=0; i<array.length; i++){
            inverso.array[this.longitud-1-i]=this.array[i]; //
        }
        return inverso;

    }

    public boolean buscar(int n){
        boolean enc=false;
        for (int i = 0; i < array.length; i++) {
            if (this.array[i]==n){
                enc=true;
                break;
            }           
        }
        return enc;
    }

    public boolean equals (Array otro){

        if (otro.longitud!=this.longitud)
            return false;
        for (int i = 0; i < array.length; i++) {
            if(this.array[i]!=otro.array[i])
                return false;
        }
        return true;
    }

I have made progress but I still do not know if I do it correctly.

package test;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

import paquete1.Array;

public class TestArray {
    int[] miArray = new int[] {4,1,5,2};
    Array array; //guarda el array miarray1 en operacionesArray
    @Before
    public void setUp() throws Exception {

        array = new Array(miArray);
    }

    @Test
    public void testConstructor() {
        int[] nuevoArray= new int[]{4,1,5,2};
        assertArrayEquals(nuevoArray,miArray);  
    }

    @Test
    public void testOrdenar() {
        int[] esperado= new int[]{1,2,4,5};//resultado esperado
        array = array.ordenar();//guardo mi objeto consu atributo modificado
        int[] actual = array.getArray();//guardo en actual mi array modificado
        assertArrayEquals(esperado,actual);
    }

    @Test
    public void testInvertido() {
        int[] esperado= new int[]{2,5,1,4};//resultado esperado
        array = array.invertir();//guardo mi objeto consu atributo modificado
        int[] actual = array.getArray();//guardo en actual mi array modificado
        assertArrayEquals(esperado,actual);
    }



    @Test
    public void testMinimo() {
        int esperado= 1;//resultado esperado
        int actual = array.minimo();//guardo en actual mi array modificado
        assertTrue(esperado==actual);
    }

    @Test
    public void testBuscar() {
        boolean esperado= true;//resultado esperado
        boolean actual = array.buscar(1);//guardo en actual mi array modificado
        assertTrue(esperado==actual);
    }

    //Falta pasarle un objeto del tipo operaciones array creado por mi
    public void testEquals() { 
        boolean esperado= true;//resultado esperado
        boolean actual = array.equals(array);//guardo en actual mi array modificado 
        assertTrue(esperado==actual);
    }

    @Test
    public void testInicializar() {
        boolean esperado= true;//resultado esperado
        boolean actual = array.buscar(1);//guardo en actual mi array modificado
        assertTrue(esperado==actual);
    }

    ///no tengo que machacar las operaciones array por que es objeto de la clase Operaciones,
    //no tengo que sobrescribirlo o bien el local  no lo guardo dentro un objeto o bien creo otra variable de operacionesarray

}
    
asked by David Palanco 11.05.2018 в 03:26
source

1 answer

1

The idea behind the performance of the unit tests is that each test is independent and a specific functionality is verified in a unit .

1.- Try the independence of tests

You should ensure that there is no way for one test to modify the result of another, for example given the following setup:

int[] miArray = new int[] {4,1,5,2};
Array array; //guarda el array miarray1 en operacionesArray
@Before
public void setUp() throws Exception {
    array = new Array(miArray);
}

You could have the following non-independent tests:

@Test
public void testInvertido1() {
    miArray[0] = -4;
    int[] esperado= new int[]{2,5,1,4};//resultado esperado
    array = array.invertir();//guardo mi objeto consu atributo modificado
    int[] actual = array.getArray();//guardo en actual mi array modificado
    assertArrayEquals(esperado,actual);
}

@Test
public void testInvertido2() {
    miArray[0] = -4;
    int[] esperado= new int[]{2,5,1,4};//resultado esperado
    array = array.invertir();//guardo mi objeto consu atributo modificado
    int[] actual = array.getArray();//guardo en actual mi array modificado
    assertArrayEquals(esperado,actual);
}

Only the first test to be executed will pass correctly, since both tests inevitably modify the initial state of the next test.

The way to avoid that these situations are possible is to ensure that the initial data of each test is reliable:

Array array; //instancia nueva y equivalente para todas las pruebas
@Before
public void setUp() throws Exception {
    array = new Array(new int[] {4,1,5,2});
}

2.- Check functionality

To check the functionality of a method, you should first ask yourself what this is:

  • What should my method do?
  • What is your responsibility?

If we see for example the following method:

public Array ordenar(){
    int [] arrayAux=this.getArray();
    int aux;
    for (int i=0; i<arrayAux.length-1; i++)
        for (int j=i+1; j<arrayAux.length; j++)
            if (arrayAux[i]>arrayAux[j]) // si la componente i es menor que la siguiente las intercambio 
                 {                      
                    aux=arrayAux[i]; //intercambio la componente i con la siguiente
                    arrayAux[i]=arrayAux[j]; //siempre se usa una variables auxiliar para no perder los valores durante el cambio
                    arrayAux[j]=aux;
                }


    return (new Array(arrayAux));
}

It could be inferred that the intention is to return a new Array with its ordered content, leaving the original Array intact.

To test that behavior, then:

@Test
public void testOrdenar() {
    Array originalArray = array;
    int[] original = Arrays.copyOf(array.getArray(), array.getLongitud());

    int[] esperado= new int[]{1,2,4,5};

    Array ordenado = array.ordenar();
    int[] actual = ordenado.getArray();

    assertArrayEquals(esperado, actual);
    assertArrayEquals(original, array.getArray());
}

And then you will effectively notice the usefulness of performing the test: detect errors .

    
answered by 11.05.2018 в 21:48