2015-11-04 52 views
0

是否可以從junit測試中調用靜態方法而不指定它的類?來自JUnit測試的靜態方法調用沒有指定類

下面的代碼工作:

package lightsOut; 

import static org.junit.Assert.*; 
import org.junit.Test; 
import lightsOut.LightsOutModel; 

public class LightsOutModelTest { 

    @Test 
    public void testLightsOutModel1(){ 
     assertTrue(LightsOutModel.checkWin()); // Note here 
    } 

} 

但是,當我從下面的行刪除類它顯示了一個錯誤。

 assertTrue(checkWin()); // Note here 

的錯誤是:
方法checkWin()是未定義的類型LightsOutModelTest

難道我總是要指定的靜態方法調用的類?沒有辦法從班級中導入所有的方法,因爲我試圖做到這一點似乎並不奏效。

+0

你嘗試了嗎?你的答案也在這個環節。 [http://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito] –

+1

'import static lightsOut.LightsOutModel.checkWin;'。有趣的是,你的代碼已經做到了。這就是爲什麼你不需要指定類來調用'assertTrue'。 – ajb

+0

@ajb你的意思是代碼已經在爲JUnit做這件事了:-) –

回答

2

您需要使用方法的靜態導入:

import static lightsOut.LightsOutModel.checkWin; 

一旦導入,就可以直接使用它們,

checkWin(); 

Here is the official reference

+0

@Tim謝謝你的編輯:) –

相關問題