使用 JMockit 模拟抽象类中的非公共静态方法?
我有以下课程:
public abstract class AbstractParent {
static String method() {
return "OriginalOutput";
}
}
我想模拟这个方法。 我决定使用 JMockit。 所以我创建了一个模拟类:
public class MockParent {
static String method() {
return "MOCK";
}
}
我的测试代码如下所示:
public class RealParentTest {
@Before
public void setUp() throws Exception {
Mockit.redefineMethods( AbstractParent.class, MockParent.class );
}
@Test
public void testMethod() {
assertEquals(MockParent.method(),AbstractParent.method());
}
}
不幸的是,这个测试表明 AbstractParent 返回“OriginalOutput”而不是“MOCK”。 有什么想法吗? 难道我做错了什么? 我也尝试将我的模拟类声明为抽象类,但无济于事。
编辑 请注意,公开方法会导致测试运行没有问题...这很奇怪,因为使用 JMockit 您应该能够模拟任何范围的方法。
回答 只有mock方法需要公开,你可以保留原来的方法。
I have the following class:
public abstract class AbstractParent {
static String method() {
return "OriginalOutput";
}
}
I want to mock this method. I decide to use JMockit. So I create a mock class:
public class MockParent {
static String method() {
return "MOCK";
}
}
And my test code looks like this:
public class RealParentTest {
@Before
public void setUp() throws Exception {
Mockit.redefineMethods( AbstractParent.class, MockParent.class );
}
@Test
public void testMethod() {
assertEquals(MockParent.method(),AbstractParent.method());
}
}
Unfortunately this test says that AbstractParent returns "OriginalOutput" instead of "MOCK". Any ideas why? Am I doing something wrong? I've tried declaring my mock class as abstract as well, to no avail.
Edit Note that making the method public causes the test to run without a problem... this is weird because with JMockit you are supposed to be able to mock methods of any scope.
Answer Only the mock method needs to be public, you can leave the original method as is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
找到了解决方案:您只需将模拟的方法公开(原始方法可以保持其原始可见性)。
我不知道为什么这种方法有效,而原始方法却行不通(非常欢迎这样做的人加入),但您所需要做的就是将上面示例中的模拟类更改为:
Found the solution: you simply need to make the mock's method public (the original method can stay in its original visibility).
I don't know why this works while the original way doesn't (someone who does is more than welcome to chime in), but all you need to do is simply change the mock class in the example above to:
显然,执行此操作的新方法是使用
MockUp
另一种替代方法显然是继续使用
MockParent
和@MockClass
注释。 我自己没有这样做,因为另一个内联版本可以完成这项工作。我已经在 github 上的项目的示例中实现了这一点。
Apparently the new way to do this is to use
MockUp<T>
Another alternative is apparently to continue with something like
MockParent
with a@MockClass
annonation. Haven't done this myself as the another inline version does the job.I've implemented this in an example project on github.