方法中的 JUnit Mockito 对象初始化
JUnit Mockito object initialization in method
我正在使用 Mockito 的 when
和 thenReturn
函数,我想知道是否有办法在测试函数中初始化内部对象。例如,如果我有:
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());
}
}
显然上面的代码不起作用,因为它抛出了一个空指针异常,但我们的想法是在每个测试函数中初始化平面对象,并让 mockito 的 when
使用 that 对象。我想我可以在初始化和设置 Plane 对象后将 when
行放在每个函数中,但这会使代码看起来非常难看。有更简单的方法吗?
因为我不知道你的 Plane
或 Car
class,我将在 test
class 中做一些假设。
我不知道你想测试什么,如果你想 test
Car
,理想情况下你不应该 mock
你的 class 在 test
下。
您可以在 setUp
方法中以任何方式执行类似操作。
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());
}
}
我正在使用 Mockito 的 when
和 thenReturn
函数,我想知道是否有办法在测试函数中初始化内部对象。例如,如果我有:
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());
}
}
显然上面的代码不起作用,因为它抛出了一个空指针异常,但我们的想法是在每个测试函数中初始化平面对象,并让 mockito 的 when
使用 that 对象。我想我可以在初始化和设置 Plane 对象后将 when
行放在每个函数中,但这会使代码看起来非常难看。有更简单的方法吗?
因为我不知道你的 Plane
或 Car
class,我将在 test
class 中做一些假设。
我不知道你想测试什么,如果你想 test
Car
,理想情况下你不应该 mock
你的 class 在 test
下。
您可以在 setUp
方法中以任何方式执行类似操作。
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());
}
}