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
}
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With