2017-04-06 107 views
-2

我想爲下面的類編寫單元測試。 使用可變參數調用方法。任何一個幫助我如何爲可變參數方法編寫測試用例?如何在方法中編寫可變參數的測試用例

class WCfg { 

    private void setAddr(MCfg mCfg, String... arg) 
      throws Exception { 
    try { 

    } catch (Exception e) { 
     throw new Exception("Invalid IP address.", e); 
    } 
    } 

    public String process(String... arg) throws Exception { 
    MCfg mCfg = new MCfg(); 

    try {  

     setAddr(mCfg, arg); 

    } catch (Exception e) { 
     return "Wrong argument format."; 
    } 

    mCfg.write(); 

    return "success"; 
    } 
} 

測試代碼:

import org.junit.Test; 

    public class MCfgTest { 

    @Test 
    public void Success() throws Exception { 
     WCfg wmc = new WCfg(); 
     wmc.process(String... arg); 
    } 
} 

-Thanks,

+0

要測試一個方法,你需要調用它並檢查結果。您可以像調用其他方法一樣調用具有可變參數的方法。你能否澄清這個問題是什麼? –

+0

這裏我想寫下單元測試的一些東西。如何在觸發「process」函數之前填充「arg」變量。 測試代碼: ** **大膽 進口org.junit.Test; 公共類WriteMapCfgTest { @Test 公共無效processSuccess()拋出異常{ WriteMapCfg WMC =新WriteMapCfg(); wmc.process(String ... arg); } } – mrs

回答

3

簡單;要測試所有可能的選擇是如何「可變參數」可用於:

WriteMapCfg underTest = ... 

@Test 
public void testProcessWithNoArgs() { 
    underTest.process(); 

@Test 
public void testProcessWithNullArray() { 
    underTest.process((String []) null); 
    ... 

@Test 
public void testProcessWithNullString() { 
    underTest.process((String) null); 
    ... 

@Test 
public void testProcessWithOneString() { 
    underTest.process("whatever"); 
    ... 

@Test 
public void testProcessWithMultipleStrings() { 
    underTest.process("whatever", "whocares"); 
    ... 

的一點是:這5個病例是可能的;你至少需要一個測試用例。

+0

好的,謝謝你的建議。讓我試試這個。 – mrs

+0

'testProcessWithNoArgs'是另一個可能的測試用例。 –

相關問題