[英]JUnit, Mockito and Powermock to access protected, local method
I have to test a method inside a class. 我必须在一个类中测试一个方法。 But the class itself has some inside properties and methods that are inherited and protected. 但是类本身具有一些继承和保护的内部属性和方法。
if fact, what I have is: 如果有的话,我所拥有的是:
public class MyActionTest {
@Test
public void goToSearchBaseTest() {
MyAction myAction = new MyAction();
myAction.search();
assert (true);
}
}
Then 然后
public class MyAction extends BaseAction{
...
public ActionForward search(){
if(this.getLog().isDebugEnabled()) {
this.getLog().debug("init --> search()");
}
}
}
And finally 最后
public class BaseAction{
...
protected Log log;
...
public ActionForward execute( ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response )
throws Exception {
...
log = LogFactory.getLog( this.getClass() );
...
}
Thus, my little test breaks in the first line: Trying to access the logger, and I cannot access it (Nor put a mocked logger) since it's created way, way before in the parent class, which I cannot modify. 因此,我的小测试在第一行中断了:尝试访问记录器,但我无法访问它(也没有放置模拟记录器),因为它是在父类中创建的,之前是无法修改的。
My usual JUnit and Mockito tricks aren't enough, and I know not so much about powermock 我通常的JUnit和Mockito技巧还不够,而且我对powermock的了解不多
Can anybody help me with this one? 有人可以帮我吗?
Give it a try 试试看
@RunWith(PowerMockRunner.class)
@PrepareForTest(LogFactory.class)
public class MyActionTest {
@InjectMocks
MyAction myAction ;
@Mock
Log log
public void setUp() throws Exception {
PowerMockito.mockStatic(LogFactory.class);
PowerMockito.when(LogFactory.getLog(any(BaseAction.class))).thenReturn(log);
@Test
public void goToSearchBaseTest() {
myAction.search();
assert (true);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.