Test method for swapping two variables with JUnit

I have a class with a method to exchange two variables. It returns nothing.

public void swap(int a, int b) {
    a ^= b;
    b = a ^ b;
    a = a ^ b;
}

      

How can I test it using JUnit? It doesn't even cause any side effects.

+3


source to share


3 answers


There is nothing to test.



The method does nothing: it returns void

and has no side effect (no mutation, ...).

+2


source


Your method doesn't just return anything, it does nothing, at least in terms of the side effects it observes.

If you want your method to be useful, you need to modify it to do something that you can observe. For example, you can modify it to accept singleton array arguments:



public void swap(int[] a, int[] b) {
    a[0] ^= b[0];
    b[0] = a[0] ^ b[0];
    a[0] = a[0] ^ b[0];
}

      

+1


source


The function you wrote does not perform any substitution for the values ​​"a" and "b", because in java, values ​​of primitive types are passed by value.

public void swap(int a, int b) {
    a ^= b;
    b = a ^ b;
    a = a ^ b;
}

      

The function offered by putting the values ​​into arrays of length 1 and then performing a swap operation will work since the arrays are passed by reference.

public void swap(int[] a, int[] b) {
    a[0] ^= b[0];
    b[0] = a[0] ^ b[0];
    a[0] = a[0] ^ b[0];
}

      

However, the function will fail if both arrays a and b refer to the same array. The above function will make the zero element equal to zero for the array that is passed as an argument for both arguments. Therefore, we need to change the above function as follows: -

public void swap(int[] a, int[] b) {
    if (a == b) { //do not swap 
        return;
    }

    if (a ==null) {
        return;
    }

    if (b ==null) {
        return;
    }

    a[0] ^= b[0];
    b[0] = a[0] ^ b[0];
    a[0] = a[0] ^ b[0];
}

      

I'll share some Junit benchmarks for the above code. You can use assertEquals () from the JUnit package to check the values ​​in [1] and b [1] if they have been replaced.

//both a[0] and b[0] are different values
int[] a = {4};
int[] b = {5};

int copy_a = a[0];
int copy_b = b[0];

swap(a, b);

assertEquals("copy_a should be b[0]", copy_a, b[0]);
assertEquals("copy_b should be a[0]", copy_b, a[0]);

//both a[0] and b[0] are same values
a[0] = 4;
b[0] = 4;

copy_a = a[0];
copy_b = b[0];

swap(a, b);

assertEquals("copy_a should be copy_b", copy_a == copy_b, a[0] == b[0]);

//case when you pass same array as both arguments.

a[0] = 9;
copy_a = a[0];
swap(a, a);
assertEquals("copy_a should be a[0]", copy_a, a[0]);

      

Besides the above test cases, you can also write test cases when either [] or b [] is null. Hope this helps.

0


source







All Articles