Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

No connection could be made because the target machine actively refused it. #235

Closed
KevinConti opened this issue Mar 2, 2020 · 4 comments

Comments

@KevinConti
Copy link

Error when occurs when calling WillRespondWith().

ConsumerEnumsPact.cs:

using PactNet;
using PactNet.Mocks.MockHttpService;
using PactNet.Models;
using System;
using System.Collections.Generic;
using System.Text;

namespace EnumsUnitTests.ContractTests
{
    class ConsumerEnumsPact : IDisposable
    {
        public IPactBuilder PactBuilder { get; private set; }
        public IMockProviderService MockProviderService { get; private set; }

        public int MockServerPort { get { return 7071; } }
        public string MockProviderServiceBaseUri { get { return String.Format("http://localhost:{0}", MockServerPort); } }

        public ConsumerEnumsPact()
        {
            var pactConfig = new PactConfig();
            pactConfig.SpecificationVersion = "2.0.0";
            pactConfig.PactDir = @"..\..\pacts";
            pactConfig.LogDir = @"..\..\pacts\logs";
            PactBuilder = new PactBuilder(pactConfig); //Configures the PactDir and/or LogDir.); 
            //PactBuilder = new PactBuilder();
            PactBuilder
              .ServiceConsumer("EnumsConsumer")
              .HasPactWith("EnumsProvider");

            MockProviderService = PactBuilder.MockService(MockServerPort, host: IPAddress.Any);
        }
        public void Dispose()
        {
            PactBuilder.Build(); //NOTE: Will save the pact file once finished
        }
    }
}

EnumConsumerTests.cs

using Microsoft.VisualStudio.TestTools.UnitTesting;
using PactNet.Mocks.MockHttpService;
using PactNet.Mocks.MockHttpService.Models;
using System;
using System.Collections.Generic;
using System.Net;

namespace EnumsUnitTests.ContractTests
{
    [TestClass]
    public class EnumConsumerTests     
    {
        private static IMockProviderService _mockProviderService;
        private static string _mockProviderServiceBaseUri;

        [ClassInitialize]
        public static void SetupTests(TestContext testContext)
        {
            using ConsumerEnumsPact pact = new ConsumerEnumsPact();
            _mockProviderService = pact.MockProviderService;
            _mockProviderService.ClearInteractions(); //NOTE: Clears any previously registered interactions before the test is run
            _mockProviderServiceBaseUri = pact.MockProviderServiceBaseUri;
        }

        [TestMethod]
        public void GivenNoToken_WhenPostEndpointIsCalled_ThenA401IsReturned()
        {
             _mockProviderService
                  .Given("There is a something with id 'tester'")
                  .UponReceiving("A GET request to retrieve the something")
                  .With(new ProviderServiceRequest
                  {
                      Method = HttpVerb.Get,
                      Path = "/somethings/tester",
                      Headers = new Dictionary<string, object>
                        {
                            { "Accept", "application/json" }
                        }
                  })
                  .WillRespondWith(new ProviderServiceResponse
                  {
                      Status = 200,
                      Headers = new Dictionary<string, object>
                      {
                        { "Content-Type", "application/json; charset=utf-8" }
                                    },
                      Body = new //NOTE: Note the case sensitivity here, the body will be serialised as per the casing defined
                      {
                          id = "tester",
                          firstName = "Totally",
                          lastName = "Awesome"
                      }
                  }); //NOTE: WillRespondWith call must come last as it will register the interaction
}

Error message:

Message: 
    Test method EnumsUnitTests.ContractTests.EnumConsumerTests.GivenNoToken_WhenPostEndpointIsCalled_ThenA401IsReturned threw exception: 
    System.AggregateException: One or more errors occurred. (No connection could be made because the target machine actively refused it.) (No connection could be made because the target machine actively refused it.) ---> System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it. ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it.
  Stack Trace: 
    ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
    --- End of inner exception stack trace ---
    ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
    HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
    HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
    RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
    --- End of inner exception stack trace ---

StdOut:

INFO  WEBrick 1.3.1
INFO  ruby 2.2.2 (2015-04-13) [i386-mingw32]
INFO  WEBrick::HTTPServer#start: pid=29280 port=7071

Any help would be greatly appreciated!

@neilcampbell
Copy link
Member

Seems as though the mock server didn't start correctly. It could be that your user doesn't have permission.

@neilcampbell
Copy link
Member

Also see #233 for some troubleshooting advice

@bethesque
Copy link
Member

I wonder if the mock service is just taking too long to start? The INFO WEBrick::HTTPServer#start: pid=29280 port=7071 output suggests that it does actually start 🤔

@KevinConti
Copy link
Author

KevinConti commented Mar 17, 2020

Hey, it turns out that this was due to the using block, which cleaned it up before the test actually ran.

Was able to fix this by manually and destroying the component after the unit tests were complete!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants