如何解决如何模拟返回值的超类方法
我是 junit 框架的新手,在 stackoverflow 上阅读了许多问题,但没有得到任何针对我的问题的具体答案。
//can not change this class logic as its coming from jar file
public class Parent
{
public boolean hasAccess(String userId)
{
boolean access = false;
//logic to check user access and set value as True or False in variable "access"
return access;
}
}
public class Child extends Parent
{
@Override
public boolean hasAccess(String userId)
{
//some logic before super method call
if(!super.hasAccess(userId)) //#checkpoint_1
{
return false;
}
//some logic after super method call
}
}
现在每次当我尝试模拟 Parent 的 hasAccess 方法并返回 false Mockito 时,实际上都认为我在模拟孩子的 hasAccess。
@RunWith(MockitoJunitRunner.class)
public class ChildTest
{
@Test
public void testHasNoAccess() // this is for negative testing of #Checkpoint_1
{
Child childMock = Mockito.mock(Child.class); // I tried with Mockito.spy as well
Mockito.doReturn(false).when((Parent)child).hasAccess(Mockito.anyString()); //expectation is to mock parent's hasAccess,and return false without actually calling parent method.
assertFalse(childMock.hasAccess("Test_123")); //with above mock,it always returns what I set in doReturn.
}
}
有没有一种方法可以模拟超级方法并返回特定的布尔值。 我也试过研究 PowerMockito,但据我所知,当我们处理超类的静态和非公共方法时它很有帮助,但如果 PowerMockito 也可能的话,那么一段代码将不胜感激。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。