【问题标题】:Testing same API for multiple response sets为多个响应集测试相同的 API
【发布时间】:2017-11-03 23:56:56
【问题描述】:

我们一直在尝试测试从一个微服务(比如 GET /contacts)公开的 API,该微服务正在被另一个微服务使用。

为了避免集成测试,我们创建了消费者驱动的契约测试,消费者微服务在其中创建契约并将它们发布到代理,生产者将从那里单独验证契约。

我们使用Pact IO 来实现这一点,到目前为止效果非常好。

现在我们在尝试进行详尽的测试时遇到了一些问题,我们想看看如何从 GET /contacts 返回一个空列表。

问题是:在添加交互时,我们可以使用提供者状态,但我们无法找到一种方法来区分编写测试以从 GET /contacts 获取联系人列表和在另一个测试中获取空列表。

这就是我们在消费者微服务中创建契约测试的方式:

mockServer.start()
        .then(() => {
          provider = pact({
            // config
          })
          return provider.addInteraction({
            state: 'Get all contacts',
            uponReceiving: 'Get all contacts',
            withRequest: {
              method: 'GET',
              path: '/contacts',
              headers: {
                Accept: 'application/json; charset=utf-8'
              }
            },
            willRespondWith: {
              status: 200,
              body: //list of all contacts
            }
          })
        .then(() => {
          return provider.addInteraction({
            state: 'Get empty list of contacts',
            uponReceiving: 'Get empty list of contacts',
            withRequest: {
              method: 'GET',
              path: '/contacts',
              headers: {
                Accept: 'application/json; charset=utf-8'
              }
            },
            willRespondWith: {
              status: 200,
              body: [] // empty list
            }
          })
        })

我们无法在测试中找到区分这些交互的方法! :(

任何帮助将不胜感激!

谢谢。

【问题讨论】:

    标签: javascript node.js rest microservices pact


    【解决方案1】:

    假设您使用的是 Mocha 之类的东西,您应该将这些交互分成单独的测试 - 例如在与您正在运行的测试用例相关的每个 describe 块中调用 addInteraction(可能在 before 中以使您的测试更清晰)。

    您的一般结构可能如下所示(伪代码):

    context("Contacts exist")
      describe("call some API")
        before()
          provider.addInteraction(interactionWithContacts)
    
        it("Returns a list of contact objects")
          # your test code here
          # Verify - this will also clear interactions so
          # your next test won't conflict 
          provider.verify()
    
    context("No contacts exist")
      describe("call some API")
        before()
          provider.addInteraction(interactionWithNoContacts)
    
        it("Returns an empty list of contacts")
          # your test code here
          # Verify - this will also clear interactions so
          # your next test won't conflict 
          provider.verify()       
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多