java - 在Spring中测试RestController时HttpServletRequest为null

标签 java spring testing

我正在开发Spring Web服务,我需要读取数据并将其设置为拦截器中的Session属性。
当我使用外部客户端测试端点时,一切正常。但是,当我尝试以下代码时,我得到一个NullPointerException

@RunWith(SpringRunner.class)
@WebMvcTest(AccountController.class)
public class AccountControllerTest {

private MockMvc mockMvc;

@InjectMocks
private AccountController accountController;

@MockBean
private IncomingInterceptor incomingInterceptor;

@MockBean
private AccountService accountService;

@MockBean
private FileStoreService fileStoreService;

private Gson gson;

@Before
public void setup() {
    gson = new Gson();
    mockMvc = MockMvcBuilders.standaloneSetup(accountController).addInterceptors(incomingInterceptor).build();
}

@Test
public void testAddAccount() throws Exception {
    JsonObject root = new JsonObject();
    root.add("body", gson.toJsonTree(account));

    Mockito.when(accountController.addAccount()).thenReturn(new ResponseEntity<>(1L, HttpStatus.OK));

    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/account/register")
            .content(root.toString())
            .characterEncoding("utf-8")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn();

    String contentAsString = mvcResult.getResponse().getContentAsString();
    System.out.println("contentAsString = " + contentAsString);
}
}


当在拦截器中设置属性时,一切按预期进行,但是当我尝试在AccountController中访问它们时,将引发异常。我已经尝试过使用MockMvcRequestBuilders,但是它也不起作用。

访问属性的代码:

 JsonObject body = (JsonObject) request.getSession().getAttribute("body");           


提前致谢!

最佳答案

您将数据作为RequestBody而不是会话的一部分发送。要访问RequestBody,您应该尝试这样的操作。

String requestBody= IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);


以后,您可以将字符串转换为JsonObject

JsonObject jsonObject = new JsonParser().parse(requestBody).getAsJsonObject();


现在,如果看到@WebMvcTest,它将自动配置mockMvc。因此,您可以简单地自动接线,而不是手动覆盖它。

  @Autowired
  private MockMvc mockMvc;


并删除覆盖模拟MVC的行。

我希望这有帮助。

关于java - 在Spring中测试RestController时HttpServletRequest为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56398634/

相关文章:

Java:返回语句的其他可能形式

java - 客户端和服务器端规则引擎?

java - webflow评估表达式不调用方法

ruby - 在 Ruby 测试中验证大哈希的有效方法

testing - CRUD Web App 自动化测试最佳实践

java - 动态读取Excel并存储在 map 中

java - 如何更改生成的工件的依赖关系?

java - Coinbase API 测试买卖 API

java - 我对配置的假设是否正确?

ios - 建议在不使用 MacOS 或 Xcode 的情况下在 iOS(最好是 9 及更高版本)上启用开发人员选项的任何解决方法?