JUnit,Mockito和Powermock访问受保护的本地方法

时间:2017-08-24 13:19:57

标签: java junit mockito powermock powermockito

我必须在类中测试一个方法。但是类本身有一些内部属性和方法,这些属性和方法都是继承和保护的。

如果事实,我拥有的是:

public class MyActionTest {
    @Test
    public void goToSearchBaseTest() {
        MyAction myAction = new MyAction();
        myAction.search();
        assert (true);
    }

}

然后

public class MyAction extends BaseAction{

    ...

    public ActionForward search(){

        if(this.getLog().isDebugEnabled()) {
            this.getLog().debug("init --> search()");
        }
    }

}

最后

public class BaseAction{    

    ...

    protected Log log;

    ...

    public ActionForward execute( ActionMapping mapping, ActionForm form, 
            HttpServletRequest request, HttpServletResponse response ) 
                throws Exception {
        ...

        log = LogFactory.getLog( this.getClass() );

        ...
}

因此,我的小测试在第一行中断:尝试访问记录器,我无法访问它(也没有放一个模拟的记录器),因为它是在父类中创建的方式,我无法修改。< / p>

我常用的JUnit和Mockito技巧还不够,我不太了解powermock

有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:1)

试一试

@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);
        }

    }