简体   繁体   中英

PACT - Handling provider service state and running actual provider with mocked or actual database

I am new to PACT and trying to use pact-net for contract testing for a .net microservice. I understand the concept of consumer test which generates a pact file. There is the concept of a provider state middleware which is responsible for making sure that the provider's state matches the Given() condition in the generated pact. I am bit confused on the following or how to achieve this:

The provider tests are run against the actual service. So we start the provider service before tests are run. My provider service interacts with a database to store and retrieve records. PACT also mentions that all the dependencies of a service should be stubbed.

  1. So we run the actual provider api that is running against the actual db?
  2. If we running the api against actual db how do we inject the data into the db? Should we be using the provider api's own endpoints to add the Given() data?
  3. If the above is not the correct approach then what is?

All the basic blog articles I have come across do not explain this and usually have examples with no provider states or states that are just some text files on the file system.

Help appreciated.

The provider tests are run against the actual service

Do you mean against a live environment, or the actual service running locally to the unit test (the former is not recommended, because of (2) above).

  1. This is one of the exceptions to that rule. You can choose to use a real DB or an in-memory one - whatever is most convenient. It's common to use docker and tools like that for testing.

  2. In your case, I'd have a specific test-only set of routes that respond to the provider state handler endpoints, that also have access to the repository code and can manipulate state of the system.

I'm going to add to Matt's comment, you have three options:

  1. Do your provider test with a connected environment but you will have to do some cleanup manually afterwards and make sure your data is always available in your db or/and the external APIs are always up and running. Simple to write but can be very hard to maintain.

  2. You mock your API calls but call the real database.

  3. You mock all your external dependencies: the API and the DB calls.

For 2) or 3) you will have to have test routes and inject the provider state middleware in your provider test fixture. Then, you can configure provider states to be called to generate in-memory data if solution 3) or add some data-init if you are in solution 2)

You can find an example here: https://github.com/pact-foundation/pact-net/tree/master/Samples/EventApi/Provider.Api.Web.Tests

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM