How to properly make integration tests with triggers? #133
-
Hi! I'm trying to make integration tests using AspNet WebApplicationFactory but apparently triggers are not being instantiated. Indeed, when running my real application the triggers run fine. The only difference I found between the testing and the real application is that when running the test application it is using InMemoryDatabaseContext while the real application uses SqlServer. Here is my code of the WebApplicationFactory: protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Testing");
builder.ConfigureServices(services =>
{
services.AddTransient(services =>
{
var channelMock = new Mock<IModel>();
channelMock.Setup(channel => channel.CreateBasicProperties()).Returns(Mock.Of<IBasicProperties>());
return channelMock.Object;
});
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();
services.AddDbContext<DatabaseContext>(options =>
{
IServiceCollectionExtensions.AddTriggers(options);
options.UseInMemoryDatabase("InMemoryDbForTesting");
options.UseInternalServiceProvider(serviceProvider);
});
var sp = services.BuildServiceProvider();
using var scope = sp.CreateScope();
var scopedServices = scope.ServiceProvider;
var databaseContext = scopedServices.GetRequiredService<DatabaseContext>();
databaseContext.Database.EnsureCreated();
});
}
// IServiceCollectionExtensions
public static DbContextOptionsBuilder AddTriggers(DbContextOptionsBuilder options)
{
return options.UseTriggers(triggerOptions =>
{
triggerOptions.AddTrigger<MovementOrderUpdatedTrigger>();
});
} Any help or suggestion of another way to test my application would be really appreciated :) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
This library is agnostic to the database provider that you are using. Triggers will run equally on in-memory databases as they do on actual databases. In your example code, you build two ServiceProviders, perhaps that is the source of this issue? |
Beta Was this translation helpful? Give feedback.
-
That's correct! When removing this additional ServiceProvider problem is solved. But this I will try to figure out why are we using it and remove to prevent this issue. Thank you! |
Beta Was this translation helpful? Give feedback.
This library is agnostic to the database provider that you are using. Triggers will run equally on in-memory databases as they do on actual databases.
In your example code, you build two ServiceProviders, perhaps that is the source of this issue?
AddEntityFrameworkInMemoryDatabase
is not an extension that is provided by EF Core and is likely something custom that you own :)