今日からオフィスで Spring Test MVC Framework の勉強を始めました。便利そうに見えますが、すぐに重大な問題に直面します。グーグルで数時間を費やしましたが、私の問題に関連するものは何も見つかりませんでした。
これが私の非常に単純なテストクラスです:
import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = WebAppContext.class)
public class ControllerTests {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = webAppContextSetup(wac).build();
}
@Test
public void processFetchErrands() throws Exception {
mockMvc.perform(post("/errands.do?fetchErrands=true"))
.andExpect(status().isOk())
.andExpect(model().attribute("errandsModel", allOf(
hasProperty("errandsFetched", is(true)),
hasProperty("showReminder", is(false)))));
}
}
if
テストは次のコントローラーに到達しますが、適切に承認されていないため、最初の句で失敗します。
@RequestMapping(method = RequestMethod.POST, params="fetchErrands")
public String processHaeAsioinnit(HttpSession session, HttpServletRequest request, ModelMap modelMap,
@ModelAttribute(ATTR_NAME_MODEL) @Valid ErrandsModel model,
BindingResult result, JopoContext ctx) {
if (request.isUserInRole(Authority.ERRANDS.getCode())) {
return Page.NO_AUTHORITY.getCode();
}
[...]
}
MockHttpServletRequest
によって作成された のユーザー ロールを追加MockMvcRequestBuilders.post()
して、コントローラーの権限チェックを通過できるようにするにはどうすればよいですか?
MockHttpServletRequest
method があることは知っていaddUserRole(String role)
ますがMockMvcRequestBuilders.post()
、 a を返すためMockHttpServletRequestBuilder
、 を手に入れることMockHttpServletRequest
ができず、そのメソッドを呼び出すことができません。
Spring ソースを確認するMockHttpServletRequestBuilder
と、ユーザー ロールに関連するメソッドがなくMockHttpServletRequest.addUserRole(String role)
、そのクラスで呼び出されることもないため、ユーザー ロールをリクエストに追加するように指示する方法がわかりません。
私が考えることができるのは、フィルタ チェーンにカスタム フィルタを追加し、HttpServletRequestWrapper
そこから の実装を提供するカスタムを呼び出すisUserInRole()
ことだけですが、そのような場合は少し極端に思えます。確かに、フレームワークはより実用的なものを提供する必要がありますか?