1
我有一個RestController,它具有@autowired 源屬性。我想添加一些RestController的測試用例。但它總是失敗,因爲Source需要一個真正的消息代理。Spring雲流 - 模擬源始終失敗(沒有現有的MQ實例)
所以我的問題是:我可以模擬來源或有沒有現有的方法呢?或者我的測試用例代碼不正確?謝謝。
代碼
Controller
@RestController
public class MyController {
@Autowired
private MySource mySource;
@RequestMapping(path = "hello", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@ResponseBody
public String process(@RequestBody Object body) {
Message msg = new GenericMessage("");
mySource.sendMessage(msg);
return "success";
}
}
Source
@EnableBinding(Source.class)
public class MySource {
@Autowired
@Output(Source.OUTPUT)
private MessageChannel channel;
public void sendMessage(Message msg) {
channel.send(msg);
}
}
test case
@RunWith(SpringRunner.class)
@WebMvcTest({MyController.class, MySource.class})
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Mock
private MySource mySource;
@Test
public void test() throws Exception {
mySource = Mockito.mock(MySource.class);
Message msg = new GenericMessage("");
Mockito.doNothing().when(mySource).sendMessage(msg);
ResultActions actions = mockMvc.perform(post("hello").contentType(MediaType.APPLICATION_JSON_VALUE).content("{}"));
actions.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));
}
}
謝謝,我會閱讀並驗證它 – JasonS