Spring 集成 - 如何模拟输入通道

Spring Integration - How to mock input-channel

我是 Spring 集成的新手,所以如果我的问题很荒谬,请原谅并纠正我。我正在尝试为 Spring 集成应用程序编写单元测试用例,我只测试控制器并希望模拟服务调用。

测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest({HeaderUtils.class})
@PowerMockIgnore({ "javax.management.*", "javax.script.*" })
public class DocMgmtImplTestPower {

    private MockMvc mvc;

    @InjectMocks
    private DocMgmtImpl docMgmtImpl;

    @Mock
    DocMgmtService docMgmtServiceGateway;

    @Mock
    SendComnMsgResponse sendComnMsgResponse;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this); //
        mvc = MockMvcBuilders.standaloneSetup(DocMgmtImpl.class).build();

        PowerMockito.mockStatic(HeaderUtils.class, new Answer<Map<String, Object>>() {

            @Override
            public Map<String, Object> answer(InvocationOnMock arg0) throws Throwable {
                Map<String, Object> headers = new HashMap<String, Object>();
                HeaderInfo headerInfo = new HeaderInfo();               
                headers.put(BusinessServiceConstants.SERVICE_HEADER, headerInfo);
                return headers;
            }
        });
    }

    @SuppressWarnings("deprecation")
    @Test
    public void testMethod() throws Exception {
        SpecialFormMsgRequest arg = new SpecialFormMsgRequest();
        Map<String, Object> headers = new HashMap<String, Object>();
        Mockito.when(docMgmtServiceGateway.specialFormMsg(Mockito.any(SpecialFormMsgRequest.class),
                (Matchers.<Map<String, Object>>any()))).thenReturn(new SendComnMsgResponse());
        
        SpecialFormMsgRequest msg = new SpecialFormMsgRequest();
        msg.setUiStaticDocFlag("N");
        mvc.perform(post("/specialMsg").accept(MediaType.APPLICATION_JSON).content(asJsonString(msg))
                .contentType(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk());
    }

    public static String asJsonString(final Object obj) {
        try {
            return new ObjectMapper().writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

控制器:

@Controller
public class DocMgmtImpl implements DocMgmt {
    @Autowired
    **DocMgmtService docMgmtServiceGateway;**   **// I want to mock this service.**
    
    @Override
    @RequestMapping(value = "/specialMsg", method = RequestMethod.POST)
    @ResponseBody
    public SendComnMsgResponse specialMsg(@Valid @RequestBody final SpecialFormMsgRequest specialFormMsgRequest)
            throws BusinessException, TechnicalException {

        SendComnMsgResponse sendComnMsgResponse = null;
        try {
            Map<String, Object> headers = HeaderUtils.getHeaders(poBusinessHeader); // PowerMockito working here...     
            
            sendComnMsgResponse = **this.docMgmtServiceGateway.specialFormMsg(specialFormMsgRequest, headers);** // docMgmtServiceGateway is getting null...
        } catch (Exception exception) {
            handleException(exception);
        }
        return sendComnMsgResponse;
    }
}

Gateway.xml:

<int:gateway id="docMgmtServiceGateway" service-interface="group.doc.svc.gateway.DocMgmtService"
    default-reply-channel="docReplyChannel" error-channel="docErrorChannel">    
    
        <int:method name="sendComnMsg" request-channel="sendComnMsgRequestChannel" />   
        
</int:gateway>

si-chain.xml:

<int:chain input-channel="esDBBISendComnMsgRequestChannel" output-channel="docReplyChannel">
        <int:transformer method="formatRequest" ref="esSendComnMsgTransformer"/>
        <int:service-activator ref="sendComnMsgActivator" method="sendComnMsg" />
        <int:transformer method="parseResponse" ref="esSendComnMsgTransformer"/>
</int:chain>

我在想,我做的是否正确。因为 DocMgmtService 服务是一个接口,它没有实现。在控制器调用转到上面配置的 Transformer 之后。在此设置上,我有以下问题。

  1. 我可以用相同的设置模拟 DocMgmtService 服务吗?如果不是,那么正确的方法是什么。
  2. 如果是,那么我该如何模拟我的服务。 谢谢

这完全取决于您要测试的内容。

如果您模拟接口,则您测试的只是该接口的模拟存根(毫无意义)。

框架创建接口的实现,该接口根据参数创建消息并将其发送到通道。

您应该将网关自动连接到您的测试中并调用它。

您可以根据需要模拟任何下游组件(例如 sendComnMsgActivator)。