Sunday, 8 March 2020

TestNG: @Test: Write test case

In testNG, we write the test cases in a method that is annotated with @Test annotation.

Example
@Test
public void add_10And20_30() {
 Calculator calculator = new Calculator();

 int result = calculator.add(10, 20);

 assertEquals(result, 30);
}

I give the method name as ‘add_10And20_30’. I just followed below convention.
methodNameToTest_input_expectedOutput

In the above example,
         methodNameToTest is add,
         input is 10, 20
         expectedOutput is 30

Find the below working application.

Calculator.java
package com.sample.app.arithmetic;

public class Calculator {
 public int add(int a, int b) {
  return a + b;
 }

 public int subtract(int a, int b) {
  return a - b;
 }

 public int mul(int a, int b) {
  return a * b;
 }

 public int div(int a, int b) {
  return a / b;
 }

 public int remainder(int a, int b) {
  return a % b;
 }
}

CalculatorTest.java
package com.sample.app.arithmetic;

import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class CalculatorTest {

 @Test
 public void add_10And20_30() {
  Calculator calculator = new Calculator();

  int result = calculator.add(10, 20);

  assertEquals(result, 30);
 }

}

Total project structure looks like below.


As you see the project structure, I put all the source files ins src/main/java folder, and all the test files are kept in src/test/java folder.

How to run CalculatorTest.java?
Right click on ‘CalculatorTest.java’, Run As -> TestNG Test.
You can see the test results in ‘Results of running CalculatorTest’



You can even write multiple test cases in single test class.

CalculatorTest.java

package com.sample.app.arithmetic;

import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class CalculatorTest {

 @Test
 public void add_10And20_30() {
  Calculator calculator = new Calculator();

  int result = calculator.add(10, 20);

  assertEquals(result, 30);
 }

 @Test
 public void subtract_10And20_30() {
  Calculator calculator = new Calculator();

  int result = calculator.subtract(10, 20);

  assertEquals(result, -10);
 }

 @Test
 public void mul_10And20_200() {
  Calculator calculator = new Calculator();

  int result = calculator.mul(10, 20);

  assertEquals(result, 200);
 }

}


Previous                                                    Next                                                    Home

No comments:

Post a Comment