How to mock local instance when using JMockit in c

2019-08-30 22:12发布

In my production code I create an instance (for specific reasons I cannot inject it), and call a method on that instance. In my test I want to verify the call to that method.

The unit under test:

public class DoSomethinger
{
    public void doSomething(int i)
    {
        MyClass myClass = new MyClass("...");
        myClass.myMethod(i);
    }
}

MyClass:

public class MyClass
{
    public MyClass(String s){}

    public void myMethod(int i){}
}

With JMockit and @Mocked I would write the following test which does what I want (the test fails if I change the constructor argument, the method argument, or the times called in either production code or test):

@Test
public void testDoSomething(@Mocked MyClass myClass)
{
    int i = 1;

    new Expectations()
    {{
        new MyClass("...");
        result = myClass;
    }};

    doSomethinger.doSomething(i);

    new Verifications()
    {{
        myClass.myMethod(1);
        times = 1;
    }};
}

Now I want to turn this into a parameterized test (using JUnit 4.12, JUnitParams 1.1.1, JMockit 1.41), so I cannot use @Mocked as a parameter, and using @Mocked private MyClass myClass messes up other tests. I have tried the following:

@Test
@Parameters({"1", "2"})
public void testDoSomething(int i)
{
    new MockUp<MyClass>()
    {
        @Mock
        public void $init(String s){}
    };

    new MockUp<MyClass>()
    {
        @Mock
        public void myMethod(int i){}
    };

    MyClass myClass = new MyClass("...");

    new Expectations()
    {{
        new MyClass("...");
        result = myClass;
    }};

    doSomethinger.doSomething(i);

    new Verifications()
    {{
        myClass.myMethod(1);
        times = 1;
    }};
}

but the test passes for whatever value in the Verifications for the method argument, constructor argument, or the times count. Is there a way to test this without using a global @Mocked instance of MyClass?

0条回答
登录 后发表回答