我正在开发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/