Reputation: 6126
I am using Mockito's when
and thenReturn
function and am wondering if there's a way for the object inside to be initialized in the test functions. So for example if I had:
public class fooTest {
private Plane plane;
private Car car;
@Before
public void setUp() throws Exception {
Mockito.when(Car.findById(eq(plane.getId()))).thenReturn(plane);
}
@Test
public void isBlue() {
plane = new Plane();
plane.setId(2);
Plane result = Car.findById(car);
assertEquals(Color.BLUE, result.getColor());
}
}
Obviously the above code doesn't work because it throws a null pointer exception but the idea is to initialize the plane object in every test function and have mockito's when
use that object. I suppose I could put the when
line in every function after the Plane object has been initialized and set but that makes the code look very ugly. Is there a simpler way to do it?
Upvotes: 0
Views: 3666
Reputation: 11487
Since I dont know your Plane
or Car
class, am going to make some assumptions in the test
class.
I dont know what you are trying to test, If you are trying to test
Car
, you shouldnt ideally mock
your class under test
.
Any way you can do something like this in your setUp
method.
public class fooTest {
private Plane plane;
@Mock
private Car car;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
plane = new Plane();
plane.setId(2);
plane.setColor(Color.BLUE);
Mockito.when(car.findById(eq(plane.getId()))).thenReturn(plane);
}
@Test
public void isBlue() {
// There is no point in testing car since the result is already mocked.
Plane result = car.findById(2);
assertEquals(Color.BLUE, result.getColor());
}
}
Upvotes: 1