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

1.5k Views Asked by At

I have a RestController which has a @autowired Source attribute. I want to add some test cases of RestController. But it always fails, because the Source needs a real message broker.

So my question is: can i mock Source or is there a existing way to that? Or is my testing case code not correct? Thanks.

Code

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

There are 1 best solutions below

0
On BEST ANSWER

If you are testing just the individual app, you can use TestSupportBinder from spring-cloud-stream-test-support. This section in the Spring Cloud Stream doc has some info on how to use it. You can also refer some of the unit test classes inside Spring Cloud Stream.