2015-04-28 91 views
0

我期待嘲笑支持類的靜態方法,爲了做到這一點,我需要嘲笑使用jMockit測試下的類的方法。在下面的例子中,我想模擬方法canContinue以便始終進入if條件。我也打算嘲笑靜態方法並驗證之後發生的所有事情。部分嘲笑類正在測試

public class UnitToTest { 

    public void execute() { 

     Foo foo = // 
     Bar bar = // 

     if (canContinue(foo, bar)) { 
      Support.runStaticMethod(f); 
      // Do other stuff here that I would like to verify 
     } 
    } 

    public boolean canContinue(Foo f, Bar b) { 
     //Logic which returns boolean 
    } 
} 

我的測試方法看起來是這樣的:

@Test 
public void testExecuteMethod() { 

    // I would expect any invocations of the canContinue method to 
    // always return true for the duration of the test 
    new NonStrictExpectations(classToTest) {{ 
     invoke(classToTest, "canContinue" , new Foo(), new Bar()); 
     result = true; 
    }}; 

    // I would assume that all invocations of the static method 
    // runStaticMethod return true for the duration of the test 
    new NonStrictExpectations(Support.class) {{ 
     Support.runStaticMethod(new Foo()); 
     result = true; 
    }}; 

    new UnitToTest().execute(); 

    //Verify change in state after running execute() method 
} 

我在做什麼錯在這裏?將canContinue方法的第一個期望更改爲返回false並不影響代碼的執行是否進入if條件。

回答

1

你正在嘲笑一個實例(classToTest),然後行使另一個(new UnitToTest().execute())這是而不是嘲笑;這是一件錯誤的事情。

另外,測試不應該使用invoke(..."canContinue"...),因爲canContinue方法是public。但是,真的,這種方法不應該被嘲笑;測試應準備任何需要的狀態,以便canContinue(foo, bar)返回所需的值。

+0

如果替代 新NonStrictExpectations(classToTest) 與 新NonStrictExpectations(UnitToTest.class) 應固定 – Jorgeejgonzalez