question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Response null instead of mocked resource

See original GitHub issue

Similar to pact-js I expected the response to be mocked so I could test an API client against pact’s mock server. I modified example code to match my implementation as well. My codebase uses OpenAPI to generate the api client.

However I could not assert any of my tests due to the response being always null.

Reproduction steps with an OpenAPI generated petstore: https://github.com/tomsiwik/oas-pactnet-error

Now I’m not sure if this is csharp-netcore’s client generator or that I’m using PactNet version 4.0.0-beta.3. Is this a bug or am I doing something wrong here? Thanks in advance.

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:9 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
tomsiwikcommented, Mar 28, 2022

Added: LogLevel = PactLogLevel.Debug to PactConfig. I can’t specify a log-file though.

# Just in case...
DEBUG=true dotnet test petstore
  Determining projects to restore...
  All projects are up-to-date for restore.
  Petstore -> /Users/tom/Code/problem/petstore/src/Petstore/bin/Debug/net6.0/Petstore.dll
  Petstore.Test -> /Users/tom/Code/problem/petstore/src/Petstore.Test/bin/Debug/net6.0/Petstore.Test.dll
Test run for /Users/tom/Code/problem/petstore/src/Petstore.Test/bin/Debug/net6.0/Petstore.Test.dll (.NETCoreApp,Version=v6.0)
Microsoft (R) Test Execution Command Line Tool Version 17.0.0+68bd10d3aee862a9fbb0bac8b3d474bc323024f3
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:01.07]     Petstore.Test.Api.PetApiTests.FindPetByStatus_WhenCalled_ReturnsPet [FAIL]
  Failed Petstore.Test.Api.PetApiTests.FindPetByStatus_WhenCalled_ReturnsPet [370 ms]
  Error Message:
   Expected pets not to be <null>.

With configuration:
- Use declared types and members
- Compare enums by value
- Include all non-private properties
- Include all non-private fields
- Match member by name (or throw)
- Without automatic conversion.
- Without automatic conversion.
- Be strict about the order of items in byte arrays

  Stack Trace:
     at FluentAssertions.Execution.XUnit2TestFramework.Throw(String message)
   at FluentAssertions.Execution.TestFrameworkProvider.Throw(String message)
   at FluentAssertions.Execution.CollectingAssertionStrategy.ThrowIfAny(IDictionary`2 context)
   at FluentAssertions.Equivalency.EquivalencyValidator.AssertEquality(EquivalencyValidationContext context)
   at FluentAssertions.Collections.CollectionAssertions`2.BeEquivalentTo[TExpectation](IEnumerable`1 expectation, Func`2 config, String because, Object[] becauseArgs)
   at FluentAssertions.Collections.CollectionAssertions`2.BeEquivalentTo(Object[] expectations)
   at Petstore.Test.Api.PetApiTests.<>c__DisplayClass2_0.<<FindPetByStatus_WhenCalled_ReturnsPet>b__0>d.MoveNext() in /Users/tom/Code/problem/petstore/src/Petstore.Test/Api/PetApiTests.cs:line 93
--- End of stack trace from previous location ---
   at PactNet.PactBuilder.VerifyAsync(Func`2 interact)
   at Petstore.Test.Api.PetApiTests.FindPetByStatus_WhenCalled_ReturnsPet() in /Users/tom/Code/problem/petstore/src/Petstore.Test/Api/PetApiTests.cs:line 87
--- End of stack trace from previous location ---
  Standard Output Messages:
 Mock server logs:

 [DEBUG][pact_mock_server::hyper_server] Creating pact request from hyper request
 [DEBUG][pact_mock_server::hyper_server] Extracting query from uri /pet/findByStatus?status=available
 [INFO][pact_mock_server::hyper_server] Received request HTTP Request ( method: GET, path: /pet/findByStatus, query: Some({"status": ["available"]}), headers: Some({"connection": ["Keep-Alive"], "user-agent": ["OpenAPI-Generator/1.0.0/csharp"], "accept-encoding": ["gzip", "deflate"], "host": ["127.0.0.1:49562"], "accept": ["application/json"]}), body: Empty )
 [INFO][pact_matching] comparing to expected HTTP Request ( method: GET, path: /pet/findByStatus, query: Some({"status": ["available"]}), headers: Some({"Accept": ["application/json"]}), body: Missing )
 [DEBUG][pact_matching]      body: ''
 [DEBUG][pact_matching]      matching_rules: MatchingRules { rules: {QUERY: MatchingRuleCategory { name: QUERY, rules: {} }, HEADER: MatchingRuleCategory { name: HEADER, rules: {} }, PATH: MatchingRuleCategory { name: PATH, rules: {} }} }
 [DEBUG][pact_matching]      generators: Generators { categories: {} }
 [DEBUG][pact_matching::matchers] String -> String: comparing '/pet/findByStatus' to '/pet/findByStatus' using Equality (false)
 [DEBUG][pact_matching] expected content type = '*/*', actual content type = '*/*'
 [DEBUG][pact_matching] content type header matcher = 'RuleList { rules: [], rule_logic: And, cascaded: false }'
 [DEBUG][pact_matching::matchers] String -> String: comparing 'available' to 'available' using Equality (false)
 [DEBUG][pact_matching] --> Mismatches: []
 [DEBUG][pact_mock_server::hyper_server] Test context = {"mockServer": Object({"href": String("http://127.0.0.1:49562"), "port": Number(49562)})}
 [INFO][pact_mock_server::hyper_server] Request matched, sending response HTTP Response ( status: 200, headers: Some({"Content-Type": ["application/json; charset=utf-8"]}), body: Present(16 bytes, application/json) )
 [DEBUG][pact_mock_server::hyper_server]      body: '[{"name":"Max"}]'

Failed!  - Failed:     1, Passed:    55, Skipped:     0, Total:    56, Duration: 398 ms - /Users/tom/Code/problem/petstore/src/Petstore.Test/bin/Debug/net6.0/Petstore.Test.dll (net6.0)

The assertion (inside async Task):

var example = new Pet(1, "Max", null, new List<string>());

await this.pact.VerifyAsync(async ctx =>
{
  var client = new PetApi(ctx.MockServerUri.ToString());

  List<Pet> pets = await client.FindPetsByStatusAsync("available"); // body: '[{"name":"Max"}]'

  pets.Should().BeEquivalentTo(new[] { example }); // Expected pets not to be <null>.
});

Hope this helps.

0reactions
mefellowscommented, Apr 12, 2022

Hi @tomsiwik, I noticed you closed the issue. Did you get to the bottom of it?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Mockito mock objects returns null - java
All method calls to Mockito mocks return null by default. If you want it to return something else you need to tell it...
Read more >
Mockito 1.10.19 mock returns null instead of result #1374
Mocking rest template to return a response entity fails, instead of receiving a response entity, the value returned by the mock is null....
Read more >
Don't understand why my Mocked method always returns null
Given this Class Under Test: --- package macau.gr8 class Grader2 { def expectedAnswers def graderFileReader def grade(String s) {
Read more >
Returns won't return null in JustMock
I will get an instance of IList<IBob> back instead of null. ... Also, you can't return null directly like one you mentioned: Mock....
Read more >
Stubbing and Mocking with Mockito and JUnit
Learn how to create true unit tests by mocking all external dependencies in your JUnit classes with the help of Mockito.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found