2015-04-28 74 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