Use Hypothesist to observe and validate entity events on an Entity Framework context.
await using var context = new TestContext(...);
var observer = context.ObserverFor<Item>();
context.Items.Add(new Item(0));
await context.SaveChangesAsync();
await Hypothesis
.On(observer)
.Timebox(2.Seconds())
.Any()
.Match(new Item(1))
.Validate();
If you need the state change of the entity in your validation, specify the filter on the observer:
var observer = context.ObserverFor<Item>(EntityState.Added);
or:
var observer = context.ObserverFor<Item>(args => args.State == EntityState.Added);
Don't use this for normal straightforward in-process entity framework events where you can just use normal async/await operations. Use this as a validation entry-point for out-of-process interactions from a test with your system-under-test!
A great example is with dapr, where:
- your test invokes the sidecar
- the sidecar sends a message to a pub/sub broker
- the broker puts a request on your API endpoint
- the API endpoint invokes some business logic
- the business logic ultimately stores something in a database
Here you leverage the pluggable component of the database context to validate that the expected entity event occured. Another option is to hook into the middleware of ASP.NET, for example using the ASP.NET adapter.