在JMockit中抛出一个方法的异常

时间:2018-02-06 12:52:40

标签: java jmockit

道歉,这可能听起来是一个重复的问题。

谷歌搜索后,我尝试使用: result = new Exception(); 但没有运气。

MainClass

public class DemoClass
{
    public void processMessage(String message)
    {
        System.out.println("Inside process method. processing message: " + message);
        if (message.isEmpty())
        {
            new IllegalArgumentException();
        }
    }

    public void retry(String message)
    {
        try
        {
            processMessage(message);
        }
        catch (IllegalArgumentException e)
        {
            System.out.println("Reprocessing of process method failed");
            finalMessage(message);
        }
    }

    public void finalMessage(String message)
    {
        System.out.println("Inside finalMessage method. " + message);
    }
}

识别TestClass

import mockit.Expectations;
import mockit.integration.junit4.JMockit;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(JMockit.class)
public class DemoClassTest
{
    @Test
    public void test() {
        DemoClass demoClass = new DemoClass();
        String message = "Hello World";
        new Expectations() {{

           demoClass.processMessage(message);
           result = new IllegalArgumentException();
           times = 1;

            demoClass.finalMessage(message);
            times = 1;
        }};

        demoClass.retry(message);

    }
}

在测试课程上方运行时,我遇到错误

Inside process method. processing message: Hello World
java.lang.IllegalStateException: **Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter**

我想在调用processMessage()方法时抛出错误,以便执行catch块。

1 个答案:

答案 0 :(得分:0)

您需要执行Partial Mocking

@Test
public void test() {
    DemoClass demoInstance = new DemoClass();

    String message = "Hello World";

    new Expectations(demoInstance) {{
        demoInstance.processMessage(message);
        result = new IllegalArgumentException();
        times = 1;

        demoInstance.finalMessage(message);
        times = 1;
    }};

    demoInstance.retry(message);
}

请注意,我们已将demoInstance实例传递给new Expectations块。