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

Question: Unable get response from wiremock.net server in c# #213

Closed
Elangopalakrishnan opened this issue Oct 16, 2018 · 16 comments
Closed

Comments

@Elangopalakrishnan
Copy link

Elangopalakrishnan commented Oct 16, 2018

Hi ,

Problem:

I'm trying to implement the wiremock in c#, For that I have downloaded the wiremock .net library from NuGet,

And I'm trying to do GET method , but i'm getting below error message :(

From C#

"Id = 17, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}""
if i use "await" - It is waiting for long time then it is returning 404 file not found error,

From Post Man

Could not get any response
There was an error connecting to http://localhost:62092/product/p0001.
Why this might have happened:
The server couldn't send a response:
Ensure that the backend is working properly
Self-signed SSL certificates are being blocked:
Fix this by turning off 'SSL certificate verification' in Settings > General
Proxy configured incorrectly
Ensure that proxy is configured correctly in Settings > Proxy
Request timeout:
Change request timeout in Settings > General

Versions of packages:
WireMock.Net - 1.0.3.16
System.Net.Http - 4.3.3

Code snippet:

_server = FluentMockServer.Start();
            _server
                      .Given(Request.Create().WithUrl("/product/p0001").UsingGet())
                      .RespondWith(
                        Response.Create()
                          .WithStatusCode(200)                         
                          .WithBody(@"{ msg: ""Hello world!""}"));
            var getResp = new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/product/p0001");

Please advice me what I'm missing here :(

Thanks in advance!
Elango

@StefH
Copy link
Collaborator

StefH commented Oct 16, 2018

Which Framework do you use ?
.NET 4.x.x ?
Or
.NET Core 2.x

@Elangopalakrishnan
Copy link
Author

Target framewok:
.NET Core 2.0

@StefH
Copy link
Collaborator

StefH commented Oct 16, 2018

  1. Use WithPath instead WithUrl
  2. HttpClient uses an async method

Solution:

class Program
{
    static void Main(string[] args)
    {
        RunAsync().GetAwaiter().GetResult();
    }

    static async Task RunAsync()
    {
        var server = FluentMockServer.Start();
        server
            .Given(Request.Create().WithPath("/product/p0001").UsingGet())
            .RespondWith(
                Response.Create()
                    .WithStatusCode(200)
                    .WithBody(@"{ msg: ""Hello world!""}"));
        var getResp = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/product/p0001");

        Console.WriteLine(getResp);
    }
}

@Elangopalakrishnan
Copy link
Author

Elangopalakrishnan commented Oct 16, 2018

hi @StefH ,

Thanks for reply, Its working fine,

For POST method , How can i check POST's response in our c# code,
like GET has - var getResp = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/product/p0001");

Can you please share the some example .json files for POST method,
It would be grateful.

Thanks!
Elango

@Elangopalakrishnan
Copy link
Author

Elangopalakrishnan commented Oct 16, 2018

Hi @StefH

I used below code, to get post's response ,

 StringContent content = new StringContent(JsonConvert.SerializeObject(ob), Encoding.UTF8, "application/json");
 HttpResponseMessage response = await client.PostAsync("api/products/save", content);
 string content = await response.Content.ReadAsStringAsync();

Thanks!
Elango

@StefH StefH changed the title Unable get response from wiremock.net server in c# Question: Unable get response from wiremock.net server in c# Oct 16, 2018
@Elangopalakrishnan
Copy link
Author

Elangopalakrishnan commented Oct 16, 2018 via email

@StefH
Copy link
Collaborator

StefH commented Oct 16, 2018

BTW you can use on github issues:

triple single quotes space C# ( ``` c#) to start a code block
and
tripple single quotes space (```) to end a code block

@StefH
Copy link
Collaborator

StefH commented Oct 16, 2018

AH, you need a JSON mapping example.

Something like this?

{
    "Request": {
        "Path": {
            "Matchers": [
                {
                    "Name": "WildcardMatcher",
                    "Pattern": "api/products/save"
                }
            ]
        },
        "Methods": [
            "post"
        ]
    },
    "Response": {
        "BodyAsJson": { "body": "static mapping" },
        "Headers": {
            "Content-Type": "application/json"
        }
    }
}

@StefH
Copy link
Collaborator

StefH commented Oct 16, 2018

@StefH
Copy link
Collaborator

StefH commented Oct 16, 2018

BTW you can also use the gitter channel for asking questions.
https://gitter.im/wiremock_dotnet/Lobby

@Elangopalakrishnan
Copy link
Author

Elangopalakrishnan commented Oct 16, 2018

@StefH ,

I have two .json files one is for request and one is for response,
lets say req.json and resp.json,
I'm just reading those jsons and storing in two string variables,
Then I'm just deserializing and creating objects,
and my code is,

String requestpath = @"C:\Users\req.json";
String req = n.GetJSONObjectFromFile(requestpath);
String responsePath = @"C:\Users\resp.json";
String resp = n.GetJSONObjectFromFile(responsePath);
Requests ob = JsonConvert.DeserializeObject<Requests>(req);
Resp obresp = JsonConvert.DeserializeObject<Resp>(resp);
StringContent content = new StringContent(JsonConvert.SerializeObject(ob), Encoding.UTF8, "application/json");
	server
	  .Given(
		Request.Create()
			.WithPath("/emailValidate")
			.WithBody(new JsonMatcher(JsonConvert.SerializeObject(ob))).UsingPost())
			.RespondWith(
		Response.Create()
			.WithStatusCode(200)
			.WithHeader("Constent-Type", "application/json")                   
			.WithBody(resp));   
HttpResponseMessage response = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/emailValidate", content);
Console.WriteLine(JsonConvert.SerializeObject(obresp));

req.json

{  
   "Email":"[email protected]"
}

resp.json

{  
   "isValid":true,
   "certainty":"Verified"   
}

But i don't know , how i need to match and all, i saw above site, but i don't understand why we are using matchers.

Thanks
Elango

@StefH
Copy link
Collaborator

StefH commented Oct 16, 2018

You need to use use a matcher for the body to make sure that only a request with a specific body is matched.

So on your case you can use code like:

var server = FluentMockServer.Start();
server
    .Given(Request
    .Create()
    .WithPath("/jsonmatcher1")
    .WithBody(new JsonMatcher("{ \"Email\": \"[email protected]\" }"))
    .UsingPost())
    .WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f2")
    .RespondWith(Response.Create().WithBody(@"{ ""isValid"": ""true"" }"));

@Elangopalakrishnan
Copy link
Author

Hi , I'm using same code, and getting response like below, But i'm getting error 500.
How we can get responses ???

server
.Given(Request
.Create()
.WithPath("/jsonmatcher1")
.WithBody(new JsonMatcher("{ "Email": "[email protected]" }"))
.UsingPost())
.WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f2")
.RespondWith(Response.Create().WithBody(@"{ ""isValid"": ""true"" }"));
StringContent cnent = new StringContent(JsonConvert.SerializeObject("{ "Email": "[email protected]" }"), Encoding.UTF8, "application/json");
HttpResponseMessage rponse = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", cnent);

Thanks!
Elango

@Elangopalakrishnan
Copy link
Author

Elangopalakrishnan commented Oct 16, 2018

Hi , I'm using same code, and getting response like below, But i'm getting error 500.
How we can get responses ???

server
.Given(Request
.Create()
.WithPath("/jsonmatcher1")
.WithBody(new JsonMatcher("{ "Email": "[email protected]" }"))
.UsingPost())
.WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f2")
.RespondWith(Response.Create().WithBody(@"{ ""isValid"": ""true"" }"));
StringContent cnent = new StringContent(JsonConvert.SerializeObject("{ "Email": "[email protected]" }"), Encoding.UTF8, "application/json");
HttpResponseMessage rponse = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", cnent);

Thanks!
Elango

Sorry , by mistake closed :(

@Elangopalakrishnan
Copy link
Author

Can you please review

StringContent cnent = new StringContent(JsonConvert.SerializeObject("{ "Email": "[email protected]" }"), Encoding.UTF8, "application/json");
HttpResponseMessage rponse = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", cnent);

These codes are correct??

Thanks
Elango

@StefH
Copy link
Collaborator

StefH commented Oct 16, 2018

use

var stringContent1 = new StringContent("{ \"Email\": \"[email protected]\" }", Encoding.UTF8, "application/json");
var postResponse1 = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", stringContent1);
string postContent1 = await postResponse1.Content.ReadAsStringAsync();
Console.WriteLine(postContent1);

// or

var stringContent2 = new StringContent(JsonConvert.SerializeObject(new { Email = "[email protected]" }), Encoding.UTF8, "application/json");
var postResponse2 = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", stringContent2);
string postContent2 = await postResponse2.Content.ReadAsStringAsync();
Console.WriteLine(postContent2);

@StefH StefH closed this as completed Oct 16, 2018
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

2 participants