2015-10-15 74 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()); 
    } 
}