Apologies, It may sound a duplicate question.
After googling it I tried to use: result = new Exception();
but had no luck.
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);
}
}
While running above test class i am getting below error
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**
I want to throw error on call of processMessage()
method, so that catch block gets executed.
You need to do 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);
}
Notice that we're passing the demoInstance
instance to the new Expectations
block.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.