# Master TestNG with these 5 hands-on coding exercises and solutions

TestNG is a powerful testing framework for Java applications. It provides a wide range of annotations that make it easier to write tests, manage test suites, and generate test reports. To become proficient in using TestNG, you need to practice using its annotations and features. This article provides you with five hands-on coding exercises that will help you master TestNG.

Here are 5 training exercises and the answers to them:

1. Write a TestNG test that tests a method that adds two numbers and returns the result.
`java`
``````import org.testng.Assert;
import org.testng.annotations.Test;

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

@Test
int expectedResult = 3;
Assert.assertEquals(result, expectedResult);
}
}
``````
1. Write a TestNG test that tests a method that calculates the factorial of a given number.
`java`
``````import org.testng.Assert;
import org.testng.annotations.Test;

public class TestFactorial {
public int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}

@Test
public void testFactorial() {
int expectedResult = 120;
int result = factorial(5);
Assert.assertEquals(result, expectedResult);
}
}
``````
1. Write a TestNG test that tests a method that checks if a given number is prime or not.
`java`
``````import org.testng.Assert;
import org.testng.annotations.Test;

public class TestIsPrime {
public boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}

@Test
public void testIsPrime() {
boolean expectedResult = true;
boolean result = isPrime(5);
Assert.assertEquals(result, expectedResult);
}
}
``````
1. Write a TestNG test that tests a method that reverses a string.
`typescript`
``````import org.testng.Assert;
import org.testng.annotations.Test;

public class TestReverseString {
public String reverse(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}

@Test
public void testReverseString() {
String expectedResult = "olleh";
String result = reverse("hello");
Assert.assertEquals(result, expectedResult);
}
}
``````
1. Write a TestNG test that tests a method that calculates the sum of an array of numbers.
`java`
``````import org.testng.Assert;
import org.testng.annotations.Test;

public class TestSumArray {
public int sum(int[] arr) {
int sum = 0;
for (int num : arr) {
sum += num;
}
return sum;
}

@Test
public void testSumArray() {
int expectedResult = 6;
int[] arr = new int[]{1, 2, 3};
int result = sum(arr);``````

In conclusion, these five exercises cover a range of test scenarios and help you understand how to use TestNG annotations effectively. By solving these exercises, you will have a solid foundation in TestNG and be able to write tests for your own applications with confidence. I hope that you have found these exercises helpful and that you will continue to practice and improve your TestNG skills.