PowerMockito模拟静态方法

时间:2016-11-29 10:01:23

标签: java unit-testing mockito junit4 powermockito

我搜索了很多但找不到解决方案。

拳击我的版本: 我使用的是JUnit4.4,mockito-2.0.0-beta,powermock-module-junit4-1.6.6和powermock-mockito-1.6.6。

我尝试模拟静态方法来独立运行单元测试。

到目前为止,我的SUT保持非常简单:

    Player m_player;
    IView m_view;

    public void play(){
        m_player = PlayerDAO.jaxbXMLToObject();
        m_view.showMenu();
    }

我的静态方法是一个简单的XML-Parser,不应该被调用:

public class PlayerDAO {

    private static final String File = "src/main/resources/Player.xml";

    public static Player jaxbXMLToObject() {
        try {
            throw new Exception("Should not get invoked!!");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

我的实际测试类:

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;


import main.java.controller.GameController;
import main.java.dao.PlayerDAO;
import main.java.model.Player;
import main.java.view.ConsoleView;
import main.java.view.IView;

@RunWith(PowerMockRunner.class)
public class GameControllerTest {

    GameController sut;
    IView view;

    @Test
    public void shouldShowMenu() {
        IView view = mock(ConsoleView.class);
        sut = new GameController(view);
        sut.play();
        verify(view).showMenu();
    }

    @PrepareForTest(value = {PlayerDAO.class})
    @Test 
    public void shouldTryLoadPlayer(){
        // initialize system
        IView view = mock(ConsoleView.class);
        sut = new GameController(view);

        // stub static method
        PowerMockito.mockStatic(PlayerDAO.class);
        Mockito.when(PlayerDAO.jaxbXMLToObject()).thenReturn(new Player("OriginalTester"));

        //Run
        sut.play();

        //Verify static call
        PowerMockito.verifyStatic(times(1));
        PlayerDAO.jaxbXMLToObject();

        //PowerMockito.when(PlayerDAO.jaxbXMLToObject()).thenReturn(new Player("OriginalTester"));

    }

}

我也尝试过使用easymock。呼叫的实际验证有效,但仍然在真实实现上进行呼叫。我是否需要将模拟对象传递给我的SUT才能在存根上调用而不是真实调用?

我想这很简单,但我是PowerMockito的新手。

亲切的问候

0 个答案:

没有答案