用Mockito模拟静态方法

时间:2014-10-07 10:03:36

标签: testing mockito powermock spring-test

我正在尝试使用powermock来模拟静态方法。 以下是我的代码:

public class Helper{

  public static User getLoggedInUser(HttpServletRequest request) throws NotFoundException {
    String access = request.getHeader("Authorization");
    if(access == null || access.isEmpty()) {
      throw new Exception("Access is null");
    }
    User user = new User();
    return user;

  }

}

这是我调用静态方法getUser的控制器函数:

@RequestMapping(value = "user/userInfo/{Id}", method = RequestMethod.GET, headers = "Accept=application/json")
    public @ResponseBody
    ResultDTO getUser(@PathVariable("Id") Integer Id, HttpServletRequest request) throws NotFoundException, UnauthorizedException {

        Integer userID = -1;

           User user = Helper.getLoggedInUser(request);
           if(user != null){
                userID = user.getUserId();
           }

        //do something
    }

这是我的测试课程:

//@RunWith(PowerMockRunner.class)
//@PrepareForTest(Helper.class)
public class CustomerControllerNGTest {

@InjectMocks
    private userController instance = new PaymentCustomerController();
    public PaymentCustomerControllerNGTest() {
    }

    @BeforeClass
    public void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @BeforeMethod
    public void setUpMethod() throws Exception {

        try{
            MockitoAnnotations.initMocks(this);
        }catch(Exception ex){
           System.out.println(ex.getMessage()); 
        }
        try{
        mockMvc = MockMvcBuilders.standaloneSetup(instance).build();
           // mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
        }catch(Exception ex){
            System.out.println(ex.getMessage());
        }
    }

    @AfterMethod
    public void tearDownMethod() throws Exception {
    }

    @Test
    public void testGetUserInfo() throws Exception {
        User user = new  User();
        user.setUserId(1234);
        HttpServletRequest request = mock(HttpServletRequest.class);

        //this is for the static method
        PowerMockito.mockStatic(Helper.class);
        **PowerMockito.when(Helper.getLoggedInUser(request)).thenReturn(user);**
        //do something


    }

}

现在每当我执行测试用例时,无论何时执行用粗体标记的孤立,它都会进入静态方法并抛出异常" Access为null"它正在执行该方法,而不是模拟该方法。任何的想法? 我还尝试取消注释这些行:

//@RunWith(PowerMockRunner.class)
//@PrepareForTest(Helper.class)

但仍然是同样的例外。 感谢

1 个答案:

答案 0 :(得分:0)

尝试取消注释:

//@RunWith(PowerMockRunner.class)
//@PrepareForTest(Helper.class) 

并使用

Mockito.when(Helper.getLoggedInUser(request)).thenReturn(user);

我写了博客post on topic,其中包含指向GitHub上工作示例的链接。这些使用TestNg代替JUnit,但这不重要。

修改

我建议始终使用最新的combination of Mockito and PowerMock available。较旧的组合通常是错误的错误。目前最新的组合是Mockito 1.9.5-rc1 +,PowerMock 1.5+。 Pre-1.5 versions of PowerMock wasn't Java7 compliant