Will Lovett
Will Lovett

Reputation: 1251

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

Upvotes: 8

Views: 14531

Answers (2)

Vadiraj S J
Vadiraj S J

Reputation: 717

MockUp is deprecated, use Expectations

Upvotes: -3

Crazyjavahacking
Crazyjavahacking

Reputation: 9707

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

Upvotes: 4

Related Questions