Spring Cloud Stream - 模拟源总是失败(没有现有的 MQ 实例)

Spring Cloud Stream - Mock Source always failed (without an existing MQ instance)

我有一个 RestController,它有一个 @autowired Source 属性。我想添加一些 RestController 的测试用例。但它总是失败,因为 Source 需要一个真正的消息代理。

所以我的问题是:我可以模拟 Source 还是有现成的方法?还是我的测试用例代码不正确?谢谢。

代码

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));
    }
}

如果您只是测试单个应用程序,则可以使用 spring-cloud-stream-test-support 中的 TestSupportBinder。 Spring Cloud Stream 文档中的 section 提供了一些有关如何使用它的信息。您还可以参考 Spring Cloud Stream.

中的一些单元测试 类