编程语言
首页 > 编程语言> > java-如何在JMockit中使用通用对象模拟方法?

java-如何在JMockit中使用通用对象模拟方法?

作者:互联网

如果您知道如何使用JMockit,那么这个问题是不言自明的:如何模拟具有泛型的方法?我想模拟这个方法:public T save(T entity)但它总是抛出这样的异常:

mockit.RealMethodNotFoundForMockException: Corresponding real methods not found for the following mocks:
Object save(Object)
    at mockit.internal.RedefinitionEngine.modifyRealClass(RedefinitionEngine.java:130)
    at mockit.internal.RedefinitionEngine.modifyRealClass(RedefinitionEngine.java:88)
    at mockit.internal.RedefinitionEngine.redefineMethods(RedefinitionEngine.java:72)
    at mockit.Mockit.setUpMocks(Mockit.java:197)
    at com.mytest.MyTest.setUp(AdminManagerImplTest.java:83)

解决方法:

确实对我有用

package a;

import junit.framework.TestCase;
import mockit.Mockit;

public class JMockitCoreExampleTest extends TestCase {

    public class MockMe {
        public T save(T t) {
            return null;
        }
    }

    public void testDoOperationAbc() {
        Mockit.redefineMethods(MockMe.class, SayThatYouMockMe.class);
                MockMe mock = new MockMe();
        System.out.println(mock.save("aaa"));
    }

    public static class SayThatYouMockMe {
        public T save(T t) {
            return t;
        }
    }
}

输出

Loaded external tool: mockit.integration.junit3.JUnitTestCaseDecorator
Loaded external tool: mockit.integration.junit4.JUnit4ClassRunnerDecorator
aaa

也许您在嘲笑冬眠的保存方法?如果是这样,请尝试使用jmockit的hibernate3emul.jar

标签:mocking,generics,jmockit,java
来源: https://codeday.me/bug/20191210/2103631.html