Issue
I'm not sure if I'm right with that. I have a normal function where I scan two numbers and add them together.
Now, I want to write a test where I can check if the function is right.
My function to add:
public class adding {
public static void main(String[] args) {
int number1;
int number2;
int sum;
Scanner scan;
scan = new Scanner(System.in);
scan.useDelimiter(System.lineSeparator());
System.out.println("Please give the first number: ");
number1 = scan.nextInt();
System.out.println("Please give the second number: ");
number2 = scan.nextInt();
sum = number1 + number2;
System.out.println("Sum of the two numbers: " + sum);
}
}
The test function:
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Before;
public class addingTest {
@Before
public void testing() throws Exception {
}
@Test
public void test() {
int sum = 4+5;
assertEquals(sum, 9);
}
}
Solution
Currently your test is doing nothing. Well, not nothing but it tests if 4+5
is 9
which is true, but this doesn't get you anywhere.
In the most basic form, unit tests are tests which verify the functionality of a "unit" of your class. That means a part of your code that has its own responsibility and that is tested in isolation from any other dependencies.
Right now you only have a main
method and nothing that can be tested. What you should do instead is to extract the "logic" into methods. You're trying to test if two numbers are added correctly, so extract that into a method:
public static int add(int number1, int number2) {
return number1 + number2;
}
Integrate the method into your code:
public class Rechenprogramm {
public static void main(String[] args) {
...
System.out.println("Please give the first number: ");
number1 = scan.nextInt();
System.out.println("Please give the second number: ");
number2 = scan.nextInt();
sum = add(number1, number2);
...
}
public static int add(int number1, int number2) {
return number1 + number2;
}
}
Now that you have extracted the functionality, it can be tested in isolation in the form of a unit test:
@Test
public void test() {
int number1 = 4;
int number2 = 5;
int actualSum = Rechenprogramm.add(number1, number2);
assertEquals(9, actualSum);
}
Answered By - QBrute
Answer Checked By - Terry (JavaFixing Volunteer)