Question

I am given with a java code and i have to write test cases so that 100% coverage can be obtained. But, the code given is written in such a way that one of the "if" statement will never be true. We cannot change the code, still we have to achieve 100% code coverage. How to do that. The tool is only helper, its mentioned in one of the post, but what if anyhow we need to do that.The code is-`

    public double getArea(int side1, int side2, int side3 ) {
    String type = determineTriangleType(side1+"", side2+".1", side3+"");
    double  area;

    //Different way of calculation for Equilateral
    if(type.equals("Equilateral"))
    {
        area =(Math.sqrt(3)/4)*side1 *side2;
    }`  else{.....}

I am not able to give the test case for which above "if" is true.

The determineTriangleType method ispublic String determineTriangleType(String side1, String side2, String side3 ) {......Some Processing.....}

Was it helpful?

Solution

The usual approach here is to make sure type is the desired value. To do that you would need to change determineTriangleType to return the required type.

This is where mock objects come in. The idea is to extend the Java class under test and override determineTriangleType to return the right value unconditionally in your derived implementation. Then you call the method you want to test on a instance of the derived class, and now the method's if statement will execute.

public class DerivedToCheckIf extends BaseClass {
  @Override
  public String determineTriangleType(String side1, String side2, String side3) {
    // call to super implementation may not be required
    // if the method does not change object state which affects the method under test
    super.determineTriangleType(side1, side2, side3);
    return "Equilateral";
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top