gpt4 book ai didi

testing - 使用 Mockito 模拟静态方法

转载 作者:行者123 更新时间:2023-11-28 20:55:12 24 4
gpt4 key购买 nike

我正在尝试使用 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 的 Controller 函数:

@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 is null”而不是模拟该方法,它正在执行该方法.任何想法?我还尝试取消注释这些行:

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

但还是一样的异常(exception)。谢谢

最佳答案

尝试取消注释:

//@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 .

关于testing - 使用 Mockito 模拟静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26233457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com