代码之家  ›  专栏  ›  技术社区  ›  Kris Pruden

使用匹配器和原始类型的jmockit期望

  •  4
  • Kris Pruden  · 技术社区  · 16 年前

    我正在使用jmockit进行单元测试(使用testng),并且在使用expectations类模拟使用matcher将基元类型(boolean)作为参数的方法时遇到了问题。下面是一些示例代码,说明了这个问题。

    /******************************************************/
    import static org.hamcrest.Matchers.is;
    
    import mockit.Expectations;
    
    import org.testng.annotations.Test;
    
    public class PrimitiveMatcherTest {
      private MyClass obj;
    
      @Test
      public void testPrimitiveMatcher() {
        new Expectations(true) {
          MyClass c;
          {
            obj = c;
            invokeReturning(c.getFoo(with(is(false))), "bas");
          }
        };
    
        assert "bas".equals(obj.getFoo(false));
    
        Expectations.assertSatisfied();
      }
    
      public static class MyClass {
        public String getFoo(boolean arg) {
          if (arg) {
            return "foo";
          } else {
            return "bar";
          }
        }
      }
    }
    /******************************************************/
    

    包含调用InvokereTurning(…)的行引发NullPointerException。

    如果我将此呼叫更改为不使用Matcher,如:

    invokeReturning(c.getFoo(false), "bas");
    

    它工作得很好。这对我没有好处,因为在我的实际代码中,我实际上在模拟一个多参数方法,我需要在另一个参数上使用匹配器。在这种情况下,期望类要求 全部的 参数使用匹配器。

    我很确定这是一个bug,或者可能不可能使用原始类型的匹配器(这会让我很难过)。有没有人遇到过这个问题,知道如何解决它?

    3 回复  |  直到 16 年前
        1
  •  1
  •   DJ.    16 年前

        2
  •  1
  •   Kris Pruden    16 年前

       protected final <T> T with(Matcher<T> argumentMatcher)
       {
          argMatchers.add(argumentMatcher);
    
          TypeVariable<?> typeVariable = argumentMatcher.getClass().getTypeParameters()[0];
    
          return (T) Utilities.defaultValueForType(typeVariable.getClass());
       }
    

    invokeReturning(withEqual(false)), "bas");
    

        3
  •  1
  •   Rogério    15 年前