私はRestController
を持っており、Spring MVC Testでテストしようとしています。それはそれで、次のModelAttribute
がありますSpring Test - 模擬@ModelAttribute
@ModelAttribute("authUser")
public User authUser(@AuthenticationPrincipal SpringAuthUser springAuthUser) throws Exception {
User user = ConstantsHome.userprofileMgr.getUserByUserId(springAuthUser.getUsername(), true, true);
user.updateRights(null);
request.getSession().setAttribute(ConstantsHome.USEROBJECT_KEY, user);
return user;
}
私はこのRestController
に対してテストを実行すると、私はこのauthUser
メソッド内NullPointerException
を取得しています。
mockedメソッドがこのメソッドの代わりにテストに使用されるように、このメソッドをモックする方法はありますか?私はこれについて他の記事を読んだが、私はテストで "authUser"パラメータを渡すことができると思ったが、それは動作していない。最終的に私は私のauthUser
は、以下のテスト構成クラスを経由して仕事を得ることができました...この「AUTHUSERは」NPEをスローしない...ここに私のテストがあることを確認するために
@Test
public void testGetAllUsers() throws Exception {
String userJson = AvadaObjectMapper.getMapper().writeValueAsString(new User());
System.out.println("userJson=" + userJson);
MvcResult result = this.mockMvc.perform(get("/").param("authUser", userJson).accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andDo(print())
.andReturn();
String content = result.getResponse().getContentAsString();
assertTrue(content.contains("Hello"));
}
私は 'ConstantsHome.userprofileMgr'があるかわからないが、それはおそらく、代わりにあなたが、その後にモックを注入し、動作をスタブすることができ、クラス内の' Autowired' @フィールドでなければなりません。 –