I have a TestClass
and I am writing unit test cases for calculate()
method of TestClass
. Please refer to the code below.
public class TestClass {
public int calculate() {
System.out.println("calculating area");
String shape = getShape(1);
int radius = 10;
int result = findArea(shape, radius);
return result;
}
public String getShape(int index) {
if(index == 1) {
return "circle";
}
else {
return "square";
}
}
public int findArea(String shape, int radius) {
if(shape == "circle") {
return 3 * radius * radius;
}
else {
return radius * radius;
}
}
}
While mocking getShape() function, I want the mock to return "square" when I pass the value 1. Please refer to the unit test below.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
public class TestClassTest {
//TestClass testClass;
@Before
public void init() {
TestClass testClass = new TestClass();
System.out.println("Inside before");
}
@Test
public void calculateTest() {
int expected = 100;
TestClass testClass = new TestClass();
TestClass testClassMock = Mockito.mock(TestClass.class);
Mockito.when(testClassMock.getShape(1)).thenReturn("square");
int actual = testClass.calculate();
assertEquals(expected, actual);
}
}
The test is failing with error, expected 100, but was 300. So it's clear that the getShape(1)
returns value circle, instead of the value I provided using Mockito.when()
. Please let me know what mistake I'm making.