繁体   English   中英

单元测试 IBM MQ

[英]Unit Test IBM MQ

我是 MQ 主题的新手。

如何测试/单元测试我的 Java 服务,这些服务针对真实队列执行操作。 我的课程进行连接、删除等操作。

有什么方法可以在不对生产队列执行操作的情况下测试这些服务?

@Service
public class QueueConnectionService {

    private final MQConfigMapping configMapping;

    private MQQueueManager queueManager;

    @Autowired
    public QueueConnectionService(MQConfigMapping configMapping) {
        this.configMapping = configMapping;
    }


    MQQueue connect(String queuePropertyTitle, int openOptions, String queueName) throws MQException {
        MQEnvironment.hostname = configMapping.getNamed().get(queuePropertyTitle).getHostname();
        MQEnvironment.channel = configMapping.getNamed().get(queuePropertyTitle).getChannel();
        MQEnvironment.port = configMapping.getNamed().get(queuePropertyTitle).getPort();
        MQEnvironment.userID = configMapping.getNamed().get(queuePropertyTitle).getUser();
        MQEnvironment.password = configMapping.getNamed().get(queuePropertyTitle).getPassword();
        queueManager = new MQQueueManager(configMapping.getNamed().get(queuePropertyTitle).getQueueManager());
        return queueManager.accessQueue(queueName, openOptions);
    }
}

这是我的 QueueConnectionService,但我不知道如何在本地测试中使用它。

为了进行单元测试,您需要使用Mockito之类的框架模拟 IBM MQ 类。

您将遇到的一个问题是您无法模拟对MQQueueManager构造函数的调用,因为无法模拟new运算符。 我建议创建一个MqQueueManagerFactory服务,将此服务自动连接到您的QueueConnectionService并在测试中模拟它。

您的单元测试最终将如下所示:

@ExtendWith(MockitoExtension.class)
class QueueConnectionServiceTest {

  private static final String TITLE = "Some random string";
  private static final String QUEUE_MANAGER = "Actual value does not matter";
  private static final String NAME = "Really. Those constants are magic strings.";
  private static final int OPTIONS = 42;

  @InjectMock
  private QueueConnectionService service;

  @Mock(answer = RETURNS_DEEP_STUBS)
  private MQConfigMapping configMapping;

  @Mock
  private MqConnectionManagerFactory connectionManagerFactory;

  @Mock
  private MQConnectionManager connectionManager;

  @Mock
  private MQQueue queue;

  @Test
  void should_provide_queue() {
    when(configMapping.getNamed().get(TITLE).getQueueManager()).thenReturn(QUEUE_MANAGER);
    // repeat above line for each configuration parameter.
    // Alternatively, create a config object and:
    when(configMapping.getNamed().get(TITLE)).thenReturn(config);

    when(connectionManagerFactory.create(QUEUE_MANAGER)).thenReturn(connectionManager);
    when(connectionManager.accessQueue(NAME, OPTIONS)).thenReturn(queue);

    var actual = service.connect(TITLE, OPTIONS, NAME);

    assertSame(actual, queue);
  }

}

(这是与JUnit 5Mockito 一起使用的。您可能会与另一个测试框架或另一个 mocking 框架略有不同。)

作为旁注,在每个连接处创建一个队列管理器闻起来很糟糕。 您可能想在@PostConstruct方法中创建一次。

您可以设置一个开发队列管理器来运行单元测试。 请参阅https://developer.ibm.com/learningpaths/ibm-mq-badge/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM