Search code examples
javaunit-testingjmockit

JMockit - Expectations vs MockUp<T> Why does one work and the other doesn't?


I'm attempting (still) to learn the ins and outs of JMockit. Here's yet another example of a JMockit oddity I just don't get. Running the test with NonStrictExpectations works just fine. However, running with MockUp does not. I'm not sure why. Any ideas? I'm running JMockit 1.5.

Method to test:

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;
}

Successful Expectations Test

@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);
}

Assertions Error (0 != 2) with 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);
}

Solution

  • You are using MockUp<?> incorrectly. MockUp<T? will tell JMockit to redefine a classes loaded to JVM so that instead of the real class initialization of FooStatement, it will replace them by the ones defined in the MockUp<FooStatement.

    So basically MockUp<FooStatement> will automatically replace calls of new FooStatement().

    Try something like:

    @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);
    }