2015-10-15 110 views
0

我正在使用Mockito的whenthenReturn函数,我想知道是否有方法让对象内部在测试函数中初始化。因此,举例来说,如果我有:JUnit Mockito对象初始化方法

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使用目的。我想我可以在Plane对象初始化并设置后,将when行放在每个函数中,但这会使代码看起来非常难看。有没有更简单的方法来做到这一点?

+0

你能提供'Plane'和'Car'代码吗? –

回答

1

因为我不知道你的PlaneCar班,我打算在test班做一些假设。 我不知道你想要测试什么,如果你想testCar,你不应该理想mock你的课下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()); 
    } 
}