【发布时间】:2017-05-15 13:30:28
【问题描述】:
我正在尝试为根据设备类型执行不同操作的控制器编写单元测试。
第一个控制器方法及其测试工作正常,方法参数model有一个值,我可以在测试中验证该值。
第二个控制器方法期望设备在从浏览器调用时工作,但在单元测试中不。当调用测试方法doSomething2Test() 时,我得到一个
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.mobile.device.Device]: Specified class is an interface
我的问题:为什么参数 model 正确实例化但 device 没有?有没有办法在 MockMvc 请求中设置设备,或者我可以以某种方式模拟设备?
控制器:
@Controller
@RequestMapping("home")
public class MyController {
@RequestMapping("/test1")
public String doSomething1(Model model) {
String value = "foo";
model.addAttribute("attribute1", value);
return "newUrl";
}
@RequestMapping("/test2")
public String doSomething2(Model model, Device device) {
if (device.isNormal()) {
// do stuff
}
return "newUrl";
}
}
测试:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT)
@WithMockUser(username="admin", authorities = {"ALL"})
public class MyControllerTest {
private MockMvc mockMvc;
@InjectMocks
private MyController controllerUnderTest;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/templates");
viewResolver.setSuffix(".html");
this.mockMvc =
MockMvcBuilders.standaloneSetup(this.controllerUnderTest)
.setViewResolvers(viewResolver)
.build();
}
@Test
public void doSomething1Test() throws Exception {
this.mockMvc.perform(get("/home/test1"))
.andExpect(status().isOk())
.andExpect(model().attribute("attribute1", contains("foo")));
}
@Test
public void doSomething2Test() throws Exception {
this.mockMvc.perform(get("/home/test2"))
.andExpect(status().isOk()));
}
}
【问题讨论】:
-
你解决了吗?我和你的情况一样,我无法在单元测试中注入设备..
-
不,但如果您找到解决方案,请告诉我。
标签: java unit-testing spring-mvc controller mocking