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

猜你在找的Java相关文章