【发布时间】:2015-09-07 23:08:34
【问题描述】:
我有一个 spring-boot 应用程序,它通过控制器公开一个 REST 接口。这是我的控制器的一个例子:
@RestController
public class Controller {
@Autowired
private Processor processor;
@RequestMapping("/magic")
public void handleRequest() {
// process the POST request
processor.process();
}
}
我正在尝试为此类编写单元测试,并且必须模拟处理器(因为处理需要很长时间,并且在测试控制器行为期间我试图避免此步骤)。请注意,为了这个问题,提供的示例已简化。
我正在尝试使用 mockito 框架来完成这项任务:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = App.class)
@WebAppConfiguration
@ActiveProfiles("test")
public class ControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
Processor processor = Mockito.mock(Processor.class);
ReflectionTestUtils.setField(Controller.class, "processor", processor);
}
@Test
public void testControllerEmptyBody() throws Exception {
this.mockMvc.perform(post("/magic")).andExpect(status().isOk());
}
}
但是,这失败了
java.lang.IllegalArgumentException: Could not find field [processor] of type [null] on target [class org.company.Controller]
at org.springframework.test.util.ReflectionTestUtils.setField(ReflectionTestUtils.java:112)
...
请有人给我一个提示,如何将这个模拟注入到我的控制器中?
【问题讨论】:
标签: java testing junit spring-boot mockito