Reputation: 331
Here is the code that I need to create JUnit tests to achieve branch coverage,
public String toString(int p, int q) {
if (p > 3 && q < 25) {
if (p > 50) {
System.out.println("p/q=" + (p / q));
} else {
System.out.println("p+q=" + (p + q));
}
if (q < 12) {
System.out.println("p*q=" + (p * q));
} else {
System.out.println("sqrt(p*q)=" + Math.sqrt(p * q));
}
} else {
System.out.println("p-q=" + (p - q));
}
return toString();
}
}
Here is my attempt,
@Test
public void QB2test() {
Assert.assertEquals(35, toString(15, 20));
}
However, it shows these actual result that I do not understand.
java.lang.AssertionError:
Expected :35 Actual :QB2@61e4705b
How should I modify to achieve the passed result? Thanks
Upvotes: 0
Views: 1248
Reputation: 1127
In your example, you are asserting the return value of the method call - toString(15, 20) with 35 and you are getting QB2@61e4705b as return value causing your test case to fail.
Reason is, as part of your toString method you are calling toString() method of Object class. toString() method of Object class always returns string representation of the current object. Here in your case it is returning object reference of your class which you are currently running.
To elaborate on this, every class in java is child of Object class either directly or indirectly. Object class contains toString() method. Whenever we try to print the Object reference then internally toString() method is invoked. Instead of calling Object class's toString() method have a variable to store the result of your operations and return that variable value back to the caller of the method.
Please go through the below java api link to get more clarity https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#toString--
Finally to pass your test case, change your toString(int x, int y) like below:
public double toString(int p, int q) {
double result = 0;
if (p > 3 && q < 25) {
if (p > 50) {
result = p / q;
System.out.println("p/q=" + result);
} else {
result = p + q;
System.out.println("p+q=" + result);
}
if (q < 12) {
result = p * q;
System.out.println("p*q=" + result);
} else {
result = Math.sqrt(p * q);
System.out.println("sqrt(p*q)=" + result);
}
} else {
result = p - q;
System.out.println("p-q=" + result);
}
return result;
}
I hope this answers your question
Upvotes: 1
Reputation: 111
Actual :QB2@61e4705b is object reference . You are comparing object refernce. Convert object reference into value and then try it.
Upvotes: 0