我在Spring云流中创建了一个具有自定义输入和输出的自定义通道。假设这是创建的通道:
public interface Channel {
String FOO = "foo-request";
String BAR = "bar-response";
@Input(FOO)
SubscribableChannel fooRequest();
@Output(BAR)
MessageChannel barResponse();
}
Something.java:
public class Something{
@Autowired
private Channel channel;
public void doSomething(..){
// Do some steps
channel.barRequest().send(MessageBuilder.withPayload(outputMessage).build())
}
}
可以看出,我正在Something
类中注入自定义通道,以便在方法末尾发送消息。
当我想测试这个方法时,我在Something
类中进行注入时遇到了一些问题。我无法注入Something
类,因为它不是组件。但是这个类注入了一个Channel
对象。因此,以下是我为这个类注入内部属性的限制所做的:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyChannel.class})
public class SomethingTest{
@Autowired
private Channel myChannel;
@Test
public void TestDoSomething(){
// cannot inject it as it does not have any qualified bean
Something something = new Something();
ReflectionTestUtils.setField(something, "channel", channel);
}
@EnableBinding(Channel.class)
public static class MyChannel {
}
}
如果没有ReflectionTestUtls
行,我将在doSomething
方法中的channel.barRequest().send()
上获得NullPointerException
。有了这条线通过注入的对象,我得到了以下错误:
org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'application.bar-response'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers
首先,我不确定我所做的是否是处理我的自定义通道和测试相应方法的最佳方法,所以请让我知道是否有更好的方法。第二,为什么我会遇到这个异常,以及如何解决它?
p.S:我已经在application.yml
文件中设置了与绑定器和通道相关的测试所需的配置,其方式与我以正常方式运行应用程序的方式类似。到目前为止,这种方法已经在其他属性中发挥了作用。
首先要注意的是,您试图将消息发送到通常接收消息的输入通道。
尝试将其更改为channel.barResponse().send(...)
除此之外,我面临着同样的问题,但有一个更复杂的用例。我们已经定义了兔子队列。