Search code examples
javatestngtestng-dataprovider

TestNG with a constructor


I am new with testNG and don't know how to work to a test if my class has a constructor. Please Help me :)

So, this is my .java

public class User {
    static class UserInfo{
        public int age;
        public String address;
        public int points;
        //Constructor
        UserInformation(String Address, int age, int points){
            this.age = age;
            this.Address = Address;
            this.points = points;
        }
    public int getAge(){return age;}
    public String getAddress(){return clinicAddress;}
    public int getPoints(){return points;}

    public int addPoints(int newPoints){
        return points += newPoints;
    }
}

I don't know how to do the test. I read about @DataProvider but I can't understant exactly how it works

Thanks either way!


Solution

  • You don't need to unit test Constructor as it is just setting instance variables. You write unit tests to test your business logic.

    On a side note, you should make your instance variables private and only allow access through getters.

    And regarding @DataProvider, you use it when your whole unit test has the same lines of code but just differ in terms of input or output. In that case, you can pass data to your data provider and can run multiple test cases by executing the same test method with a different set of data and can avoid duplication of unit test code.

    For your addPoints() method,we can write test cases with @DataProvider as below :

    @DataProvider(name = "test1")
    public Object[][] createData1() {
     return new Object[][] {
       { "Test with zero", 0 },
       { "Test with negative value", -1},
       { "Test with positive value", 1},
     }
    

    And then you use dataProvider on your test method like below :

    @Test(dataProvider = "test1")
    public void verifyData1(String testCase, int number) {
       //call your method to being tested with input number
    }
    

    For more detail on DataProvider,read https://testng.org/doc/documentation-main.html#parameters-dataproviders