Hi friends,

Being new in junit i have onw question that How to test local variable in method using junit test case?
Check that below is my method suppose,

public void methodToCheckStr(int testVar)
    {
        String str="";
        if(testVar==5)
        {
            str="Success";
        }
        else
        {
            str="fail";
        }
    }

How to create test case to check what is 'str' contains?

Kindly help me out here.

The idea of testing your code is to have some method that has a return and that is what you want to test. So to get testing going on above code you would have to change return type to String

public String methodToCheckStr(int testVar)
    {
        String str="";
        if(testVar==5)
        {
             return "Success";
        }
        else
        {
            return "fail";
        }
    }

And then you can have tests as

@Test
public void testSuccess() {
   StringChecker checker = new StringChecker();
   assertEquals("Success", checker.methodToCheckStr(5));
}

@Test
public void testFail() 
   StringChecker checker = new StringChecker();
   assertEquals("fail", checker.methodToCheckStr(4));
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.