我使用MockMvc与Mockito,绘制大量的春季温室样本。我有一个简单的控制器返回一个字符串viewname,或null,如果有某种错误。它在servlet环境中工作得很好,但是当我尝试用MockMvc standaloneSetup对控制器进行单元测试时,我得到
javax.servlet.ServletException: Circular view path [register]: would dispatch back to the current handler URL [/register] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
这是我的控制器
@Controller
public class SignupController {
@RequestMapping(value="/register", method=RequestMethod.GET)
public RegistrationForm createNewRegForm(){
return new RegistrationForm();
}
/**
* Process a signup form submission.
* Delegate to a {@link SignupServiceImpl} to actually complete the signin transaction.
* Redirects the new member to the application home page on successful sign-in.
*/
@RequestMapping(value="/register", method=RequestMethod.POST)
public String signup(@Validated(Registration.class) RegistrationForm form, BindingResult formBinding) {
if(formBinding.hasErrors())
return null;
boolean success = signupHelper.signup(form.getUser(), formBinding);
return (!formBinding.hasErrors() && success) ? "redirect:/" : null;
}
}
和失败的测试:
public void signup_duplicateEmail() throws Exception {
AccountManager accountRepository = mock(AccountManager.class);
AccountAuthUtils authorization = mock(AccountAuthUtils.class);
when(accountRepository.createAccount(any(User.class))).thenThrow(new EmailAlreadyOnFileException("roy@clarkson.com"));
SignupServiceImpl gateway = new SignupServiceImpl(accountRepository, authorization);
SignupController signupController = new SignupController(gateway);
MockMvc mockMvc = standaloneSetup(signupController).build();
mockMvc.perform(post("/register").contentType(APPLICATION_FORM_URLENCODED)
.param("user.username","habuma")
.param("user.email","roy%40clarkson.com")
.param("user.password", "letmein1")
.param("confirmPassword", "letmein1"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.forwardedUrl("/register.do"))
.andExpect(MockMvcResultMatchers.model().hasErrors())
.andExpect(MockMvcResultMatchers.model().attributeHasFieldErrors("registrationForm", "user.email"));
}
一个简单的遍历返回"/register "。在控制器中,do"而不是null表示失败,但我宁愿不改变我的代码来使测试工作。
我的猜测是这种差异的原因是因为在生产中你已经配置你的ViewResolver使用"/WEB-INF/"和可能的后缀。在您的独立测试设置中,您没有添加ViewResolver,因此默认情况下只是将视图名称转换为路径,此时它意识到它与请求路径相同。
至于。doc,你有什么观点吗,我们很快会添加一些东西,跟踪这里。
好吧,经过几个小时的努力,我终于明白了。
基本上,只要初始url与结束url相同,它就会给出这个问题。但是,您可以通过请求post("register.do") (servlet就是这样做的)来欺骗它,并检查它是否返回"register"。因此,我的解决方案是:
mockMvc.perform(post("/register.do").contentType(APPLICATION_FORM_URLENCODED)
.param("user.username","habuma")
.param("user.email","roy%40clarkson.com")
.param("user.password", "letmein1")
.param("confirmPassword", "letmein1"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.forwardedUrl("register"))
现在它可以在测试和服务器环境中工作。
注:我希望所有这些。do的东西都有好的文档。使用了这么多年,我从来没有真正理解过它。