Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access method variable in jUnit test

Tags:

java

junit

How can I use 2 variable from method below in jUnit test, but Eclipse tells me that I cannot access this variable. How can I make it accesible in any way? Or I need to define tests in other class?

import org.junit.Assert;
import org.junit.*;

public class Sequence {

    public void MissingNumber() {  
        int[] arr = {1, 2, 3, 5, 6, 7, 8};  
        int length = arr.length;  

        int indexes = 8;
        int values = 0;  

        for (int i = 0; i < length; i++) {  
            indexes += i+1;  
            values += arr[i];  

            int result = indexes - values;  

            System.out.println("Indexes:" + indexes);
            System.out.println("Values:" + values);
            System.out.println("Missing number is: "+ result);  
        }
    }

    @Test
    public void testCase1() {
        Assert.assertEquals("4", result); //need to use result
    }

    @Test
    public void testCase2() {
        Assert.assertEquals("10", values); //need to use values
    }
}
like image 994
user3166813 Avatar asked Sep 10 '25 14:09

user3166813


1 Answers

The idea of unit testing is that you have a method that takes given parameters and should produce some expected output. Rewriting your program to make it work that way, for example:

public int missingNumber(int[] arr) {
    int length = arr.length;

    int indexes = 8;
    int values = 0;

    for (int i = 0; i < length; i++) {
        indexes += i + 1;
        values += arr[i];
    }

    return indexes - values;
}

@Test
public void testResultFor_1_2_3_5_6_7_8() {
    int result = missingNumber(new int[]{1, 2, 3, 5, 6, 7, 8});
    Assert.assertEquals(4, result);
}
like image 93
janos Avatar answered Sep 13 '25 03:09

janos