gpt4 book ai didi

spring - 在我的 JUnit 测试中,如何验证 Spring RedirectView?

转载 作者:行者123 更新时间:2023-12-01 09:23:06 25 4
gpt4 key购买 nike

我正在使用 Spring 3.2.11.RELEASE 和 JUnit 4.11。在一个特定的 Spring Controller 中,我有一个这样结束的方法......

return new ModelAndView(new RedirectView(redirectUri, true));

在我的 JUnit 测试中,如何验证从提交到返回此 RedirectView 的 Controller 的返回?我曾经使用 org.springframework.test.web.AbstractModelAndViewTests.assertViewName,但它只返回“null”,即使返回非空 ModelAndView 对象也是如此。以下是我构建 JUnit 测试的方式...

    request.setRequestURI(“/mypage/launch");
request.setMethod("POST");

final Object handler = handlerMapping.getHandler(request).getHandler();
final ModelAndView mav = handlerAdapter.handle(request, response, handler);
assertViewName(mav, "redirect:/landing");

感谢任何有关如何验证 RedirectView 以正确值返回的帮助,

最佳答案

正如 Koiter 所说,考虑转向 Spring 测试 a 和 MockMvc

它提供了一些以声明方式测试 Controller 和请求/响应的方法

你需要一个 @Autowired WebApplicationContext wac;

并在您的 @Before 方法上设置它以使用该类的 @WebAppConfiguration

你会得到一些东西

 @ContextConfiguration("youconfighere.xml")
//or (classes = {YourClassConfig.class}
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class MyControllerTests {

@Autowired WebApplicationContext wac
private MockMvc mockMvc;


@Before
public void setup() {
//setup the mock to use the web context
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
}

那么你只需要使用MockMvcResultMatchers断言事情

 @Test
public void testMyRedirect() throws Exception {
mockMvc.perform(post("you/url/")
.andExpect(status().isOk())
.andExpect(redirectUrl("you/redirect")
}

注意:post(), status() isOk() redirectUrl() 是从 MockMvcResultMatchers

导入的静态数据

查看更多您可以匹配的内容here

关于spring - 在我的 JUnit 测试中,如何验证 Spring RedirectView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29906356/

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