PHP协定-来自模拟服务器的404响应代码

时间:2018-12-27 11:10:00

标签: php api testing pact

我尝试使用示例配置为PHP配置Pact。我的问题是我可以运行mockServer,但是我发出的每个请求都返回404响应。当然,我像在GitHub自述文件中一样设置了所有内容。仍然,我知道服务器是可见的(localhost配置),但是路由无法注册。

代码示例:

class PactTest extends \Tests\BaseTestCases\V2TestCase
{

/** @var MockServerConfig */
private $config;

public function setUp()
{
    // Create your basic configuration. The host and port will need to match
    // whatever your Http Service will be using to access the providers data.
    $this->config = new MockServerConfig();
    $this->config->setHost('localhost');
    $this->config->setPort(7200);
    $this->config->setConsumer('someConsumer');
    $this->config->setProvider('someProvider');
    $this->config->setHealthCheckTimeout(60);
    $this->config->setCors(true);

    // Instantiate the mock server object with the config. This can be any
    // instance of MockServerConfigInterface.
    $server = new MockServer($this->config);

    // Create the process.
    $server->start();

    // Stop the process.
    $server->stop();
}

public function testSimple()
{
    $matcher = new Matcher();

    // Create your expected request from the consumer.
    $request = new ConsumerRequest();
    $request
        ->setMethod('GET')
        ->setPath('/test/abc')
        ->addHeader('Content-Type', 'application/json');

    // Create your expected response from the provider.
    $response = new ProviderResponse();
    $response
        ->setStatus(200)
        ->addHeader('Content-Type', 'application/json;charset=utf-8')
        ->setBody([
            'message' => $matcher->term('Hello, Bob', '(Hello, )[A-Za-z]')
        ]);

    // Create a configuration that reflects the server that was started. You can
    // create a custom MockServerConfigInterface if needed. This configuration
    // is the same that is used via the PactTestListener and uses environment variables.
    $builder = new InteractionBuilder($this->config);
    $builder
        ->given('a thing exists')
        ->uponReceiving('a get request to /test/abc')
        ->with($request)
        ->willRespondWith($response); // This has to be last. This is what makes an API request to the Mock Server to set the interaction.

    $service = new HttpClientService($this->config->getBaseUri()); // Pass in the URL to the Mock Server.
    $result  = $service->getTestAbc(); // Make the real API request against the Mock Server.

    $builder->verify();

    self::assertEquals('Hello, Bob', $result); // Make your assertions.
}

getTestAbc()在哪里:

public function getTestAbc(): string
{
    $uri = $this->baseUri;
    $response = $this->httpClient->get("{$uri->getHost()}/test/abc", [
        'headers' => ['Content-Type' => 'application/json']
    ]);
    $body   = $response->getBody();
    $object = \json_decode($body);

    return $object->message;
}

我该怎么办?

1 个答案:

答案 0 :(得分:1)

您要在setUp中停止模拟服务器。在进行tearDown测试之后,您应该停止服务器。我注意到这是手册中的代码,可能会引起误解,但我认为它只是作为示例来手动启动/停止模拟服务器。