JMockit - 期望与MockUp <t>为什么一个工作而另一个不工作?</t>

时间:2015-02-24 17:27:51

标签: java unit-testing jmockit

我正在尝试(仍然)学习JMockit的细节。这是JMockit奇怪的另一个例子,我不知道。使用NonStrictExpectations运行测试工作正常。但是,使用MockUp运行却没有。我不确定为什么。有任何想法吗?我正在运行JMockit 1.5。

测试方法:

private List<Foo> getFooList(List<FooStatement> fooStatements){
    List<Foo> FooList = new ArrayList<Foo>();

    for(FooStatement at: fooStatements){
        List<Foo> aList = at.getFoos();
        FooList.addAll(aList);
    }

    return FooList;
}

成功的期望测试

@Test
public void getFooListWithExpectationsTest(
        @Mocked final FooStatement mockFooStatement,
        @Mocked final Foo mockFoo
){

    List<FooStatement> fooStatementList = new ArrayList<>(Arrays.asList(
            mockFooStatement,
            mockFooStatement
    ));

    new NonStrictExpectations(){{
        mockFooStatement.getFoos();
        result = new ArrayList<Foo>(Arrays.asList(mockFoo));
    }};

    List<Foo> fooList = Deencapsulation.invoke(handler, "getFooList", fooStatementList);
    Assert.assertTrue(fooList.size() == 2);
}

断言错误(0!= 2)与MockUp

@Test
public void getFooListWithMockUpTest(
        @Mocked final FooStatement mockFooStatement,
        @Mocked final Foo mockFoo
){

    new MockUp<FooStatement>(){
        @Mock
        public List<Foo> getFoos(){
            return new ArrayList<Foo>(Arrays.asList(mockFoo));
        }
    };

    List<FooStatement> fooStatementList = new ArrayList<>(Arrays.asList(
            mockFooStatement,
            mockFooStatement
    ));

    List<Foo> fooList = Deencapsulation.invoke(handler, "getFooList", fooStatementList);
    Assert.assertTrue(fooList.size() == 2);
}

2 个答案:

答案 0 :(得分:3)

您错误地使用了MockUp<?>MockUp<T?将告诉JMockit重新定义加载到JVM的类,以便代替FooStatement的实际类初始化,它将用MockUp<FooStatement中定义的类替换它们。

所以基本上MockUp<FooStatement>会自动替换new FooStatement()的来电。

尝试类似:

@Test
public void getFooListWithMockUpTest(@Mocked final Foo mockFoo){

    new MockUp<FooStatement>(){
        @Mock
        public List<Foo> getFoos(){
            return new ArrayList<Foo>(Arrays.asList(mockFoo));
        }
    };

    List<FooStatement> fooStatementList = new ArrayList<>(Arrays.asList(
            new FooStatement(),
            new FooStatement()
    ));

    List<Foo> fooList = Deencapsulation.invoke(handler, "getFooList",     fooStatementList);
    Assert.assertTrue(fooList.size() == 2);
}

答案 1 :(得分:0)

不建议使用模型,请使用期望