简体   繁体   中英

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

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM