I have a multi tenant web API where I seed a database with initial data.
I also have a transient IUserService which has a GetCustomerId function to retrieve the current customerId. This service is used in the databaseContext to store the CustomerId foreign key on the created domain entity "under the hood".
So when I seed the database I create a new scope and use a ICurrentUserInitializer to set the CustomerId in the IUserService for that scope, so the CustomerId is valid when the database context stores the entity.
This works just fine in development, but not for testing. Since I want to mock the IUserService when I test, this means that Moq overrides the GetCustomerId. But I only want to mock that service AFTER I've finished seeding the test database.
I've also tried not mocking the IUserService, and instead use a ICurrentUserInitializer for every test that runs, i.e. for every test, create a new scope, set the CustomerId with the ICurrentUserInitializer in that scope, and run the test in that scope, and then reset for the next test. This seems to work, but isn't as flexible when you want to run tests as different users and it doesn't seem as elegant, since I have to write more code to handle the scope correctly.
I Use xUnit, Moq, Respawn, and Microsoft.AspNetCore.Mvc.Testing
DbContext :
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
int? customerId = CurrentUser.GetCustomerId();
HandleAuditingBeforeSaveChanges(customerId);
int result = await base.SaveChangesAsync(cancellationToken);
return result;
}
private void HandleAuditingBeforeSaveChanges(int? customerId)
{
foreach (var entry in ChangeTracker.Entries<IMustHaveTenant>().ToList())
{
entry.Entity.CustomerId = entry.State switch
{
EntityState.Added => customerId.Value,
_ => entry.Entity.CustomerId
};
}
}
DatabaseInitializer :
public async Task InitializeApplicationDbForCustomerAsync(Customer Customer, CancellationToken cancellationToken)
{
// First create a new scope
using var scope = _serviceProvider.CreateScope();
// This service injects a CustomerId, so that ICurrentUser retrieves this value, but
// doesn't work, since Moq overrides the value
scope.ServiceProvider.GetRequiredService<ICurrentUserInitializer>()
.SetCurrentCustomerId(customer.Id);
// Then run the initialization in the new scope
await scope.ServiceProvider.GetRequiredService<ApplicationDbSeeder>()
.SeedDatabaseAsync(_dbContext, cancellationToken);
}
CustomWebApplicationFactory:
public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration(configurationBuilder =>
{
var integrationConfig = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.Build();
configurationBuilder.AddConfiguration(integrationConfig);
});
builder.ConfigureServices((context, services) =>
{
services
.Remove<DbContextOptions<ApplicationDbContext>>()
.AddDbContext<ApplicationDbContext>((sp, options) =>
{
options.UseSqlServer(context.Configuration.GetConnectionString("DefaultConnection"),
builder => builder.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName));
});
});
builder.ConfigureTestServices(services =>
{
services
.Remove<ICurrentUser>()
.AddTransient(_ => Mock.Of<ICurrentUser>(s =>
s.GetCustomerId() == GetCurrentCustomerId()));
});
}
}
Testing / CollectionFixture :
public class DatabaseCollection : ICollectionFixture<Testing>
{
}
public partial class Testing : IAsyncLifetime
{
private static WebApplicationFactory<Program> _factory = null!;
private static IConfiguration _configuration = null!;
private static IServiceScopeFactory _scopeFactory = null!;
private static Checkpoint _checkpoint = null!;
private static int? _currentCustomerId = null;
public Task InitializeAsync()
{
_factory = new CustomWebApplicationFactory();
_scopeFactory = _factory.Services.GetRequiredService<IServiceScopeFactory>();
_configuration = _factory.Services.GetRequiredService<IConfiguration>();
_checkpoint = new Checkpoint
{
TablesToIgnore = new[] { new Table("__EFMigrationsHistory") },
};
return Task.CompletedTask;
}
public static int? GetCurrentCustomerId()
{
return _currentCustomerId;
}
public static void RunAsDefaultUserAsync()
{
_currentCustomerId = DefaultValues.Customer.Id;
}
public static async Task<TResponse> SendAsync<TResponse>(IRequest<TResponse> request)
{
using var scope = _scopeFactory.CreateScope();
var mediator = scope.ServiceProvider.GetRequiredService<ISender>();
return await mediator.Send(request);
}
public static async Task<TEntity?> FindAsync<TEntity>(params object[] keyValues)
where TEntity : class
{
using var scope = _scopeFactory.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
return await context.FindAsync<TEntity>(keyValues);
}
public static async Task AddAsync<TEntity>(TEntity entity)
where TEntity : class
{
using var scope = _scopeFactory.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Add(entity);
await context.SaveChangesAsync();
}
public static async Task ResetState()
{
await _checkpoint.Reset(_configuration.GetConnectionString("DefaultConnection"));
await _factory.Services.InitializeDatabasesAsync();
_currentCustomerId = null;
}
public Task DisposeAsync()
{
return Task.CompletedTask;
}
}
DepartmentTest:
[Collection("Database collection")]
public class GetDepartmentsTest : BaseTestFixture
{
[Fact]
public async Task ShouldReturnDepartments()
{
RunAsDefaultUserAsync();
var query = new ListDepartmentRequest();
var result = await SendAsync(query);
result.ShouldNotBeNull();
}
[Fact]
public async Task ShouldReturnAllDepartments()
{
RunAsDefaultUserAsync();
await AddAsync(new Department
{
Description = "Department 1",
});
await AddAsync(new Department
{
Description = "Department 2",
});
var query = new ListDepartmentRequest();
var result = await SendAsync(query);
result.ShouldNotBeNull();
result.Count.ShouldBe(2);
}
}
BaseTestFixture:
public class BaseTestFixture : IAsyncLifetime
{
public async Task InitializeAsync()
{
await ResetState();
}
public async Task DisposeAsync()
{
await ResetState();
//return Task.CompletedTask;
}
}
Related
The Problem
I have a collection fixture in xunit test that lets me group all my tests together to allow for 1) a docker db setup and 2) each test to have their own service collection for activities.
The problem is that the since the tests are all in a collection fixture, the tests classes don't run in parallel. I've tried a few different things in their parallelization docs with no luck. They still run pretty fast but it seems like this would be a big bump in perf that should be doable. Any thoughts here?
The Code
i have a test collection fixture like this
[CollectionDefinition(nameof(TestFixture))]
public class TestFixtureCollection : ICollectionFixture<TestFixture> {}
public class TestFixture : IAsyncLifetime
{
public static IServiceScopeFactory BaseScopeFactory;
public async Task InitializeAsync()
{
// docker db setup
builder.ConfigureServices();
var services = builder.Services;
var provider = services.BuildServiceProvider();
BaseScopeFactory = provider.GetService<IServiceScopeFactory>();
}
public Task DisposeAsync()
{
return Task.CompletedTask;
}
}
public static class ServiceCollectionServiceExtensions
{
public static IServiceCollection ReplaceServiceWithSingletonMock<TService>(this IServiceCollection services)
where TService : class
{
services.RemoveAll(typeof(TService));
services.AddScoped<TService>(_ => Mock.Of<TService>());
return services;
}
}
testing service scope
public class TestingServiceScope
{
private readonly IServiceScope _scope;
public TestingServiceScope()
{
_scope = BaseScopeFactory.CreateScope();
}
public TScopedService GetService<TScopedService>()
{
var service = _scope.ServiceProvider.GetService<TScopedService>();
return service;
}
public async Task<T> ExecuteScopeAsync<T>(Func<IServiceProvider, Task<T>> action)
=> await action(_scope.ServiceProvider);
public Task<T> ExecuteDbContextAsync<T>(Func<CoreDomainDbContext, Task<T>> action)
=> ExecuteScopeAsync(sp => action(sp.GetService<CoreDomainDbContext>()));
public Task<int> InsertAsync<T>(params T[] entities) where T : class
{
return ExecuteDbContextAsync(db =>
{
foreach (var entity in entities)
{
db.Set<T>().Add(entity);
}
return db.SaveChangesAsync();
});
}
}
example test:
[Collection(nameof(TestFixture))]
public class AddRecipeCommandTests
{
[Fact]
public async Task can_add_new_recipe_to_db()
{
// Arrange
var testingServiceScope = new TestingServiceScope();
var fakeRecipeOne = new FakeRecipeForCreationDto().Generate();
// Act
var command = new AddRecipe.Command(fakeRecipeOne);
var recipeReturned = await testingServiceScope.SendAsync(command);
var recipeCreated = await testingServiceScope.ExecuteDbContextAsync(db => db.Recipes
.FirstOrDefaultAsync(r => r.Id == recipeReturned.Id));
// Assert
recipeReturned.Title.Should().Be(fakeRecipeOne.Title);
recipeReturned.Visibility.Should().Be(fakeRecipeOne.Visibility);
recipeReturned.Directions.Should().Be(fakeRecipeOne.Directions);
recipeReturned.Rating.Should().Be(fakeRecipeOne.Rating);
recipeReturned.DateOfOrigin.Should().Be(fakeRecipeOne.DateOfOrigin);
recipeReturned.HaveMadeItMyself.Should().Be(fakeRecipeOne.HaveMadeItMyself);
recipeCreated.Title.Should().Be(fakeRecipeOne.Title);
recipeCreated.Visibility.Should().Be(fakeRecipeOne.Visibility);
recipeCreated.Directions.Should().Be(fakeRecipeOne.Directions);
recipeCreated.Rating.Should().Be(fakeRecipeOne.Rating);
recipeCreated.DateOfOrigin.Should().Be(fakeRecipeOne.DateOfOrigin);
recipeCreated.HaveMadeItMyself.Should().Be(fakeRecipeOne.HaveMadeItMyself);
}
}
I'm stuck and the docks for the lib are unhelpful. Given the below saga definition:
public class GetOrdersStateMachine : MassTransitStateMachine<GetOrdersState>
{
public State? FetchingOrdersAndItems { get; private set; }
public Event<GetOrders>? GetOrdersIntegrationEventReceived { get; private set; }
public GetOrdersStateMachine()
{
Initially(
When(GetOrdersIntegrationEventReceived)
.Activity(AddAccountIdToState)
.TransitionTo(FetchingOrdersAndItems));
}
private EventActivityBinder<GetOrdersState, GetOrders> AddAccountIdToState(
IStateMachineActivitySelector<GetOrdersState, GetOrders> sel) =>
sel.OfType<AddAccountIdToStateActivity>();
}
And the below activity definition:
public class AddAccountIdToStateActivity : Activity<GetOrdersState, GetOrders>
{
private readonly IPartnerService _partnerService;
public AddAccountIdToStateActivity(IPartnerService partnerService) => _partnerService = partnerService;
public void Probe(ProbeContext context) =>
context.CreateScope($"GetOrders{nameof(AddAccountIdToStateActivity)}");
public void Accept(StateMachineVisitor visitor) => visitor.Visit(this);
public async Task Execute(
BehaviorContext<GetOrdersState, GetOrders> context,
Behavior<GetOrdersState, GetOrders> next)
{
context.Instance.AccountId = await _partnerService.GetAccountId(context.Data.PartnerId);
await next.Execute(context);
}
public Task Faulted<TException>(
BehaviorExceptionContext<GetOrdersState, GetOrders, TException> context,
Behavior<GetOrdersState, GetOrders> next) where TException : Exception =>
next.Faulted(context);
}
And the below test definition:
var machine = new GetOrdersStateMachine();
var harness = new InMemoryTestHarness();
var sagaHarness = harness.StateMachineSaga<GetOrdersState, GetOrdersStateMachine>(machine);
var #event = new GetOrders("1", new[] {MarketplaceCode.De}, DateTime.UtcNow);
await harness.Start();
try
{
await harness.Bus.Publish(#event);
await harness.Bus.Publish<ListOrdersErrorResponseReceived>(new
{
#event.CorrelationId,
AmazonError = "test"
});
var errorMessages = sagaHarness.Consumed.Select<ListOrdersErrorResponseReceived>().ToList();
var sagaResult = harness.Published.Select<AmazonOrdersReceived>().ToList();
var state = sagaHarness.Sagas.Contains(#event.CorrelationId);
harness.Consumed.Select<GetOrders>().Any().Should().BeTrue();
sagaHarness.Consumed.Select<GetOrders>().Any().Should().BeTrue();
harness.Consumed.Select<ListOrdersErrorResponseReceived>().Any().Should().BeTrue();
errorMessages.Any().Should().BeTrue();
sagaResult.First().Context.Message.IsFaulted.Should().BeTrue();
errorMessages.First().Context.Message.CorrelationId.Should().Be(#event.CorrelationId);
errorMessages.First().Context.Message.AmazonError.Should().Be("test");
state.IsFaulted.Should().BeTrue();
}
finally
{
await harness.Stop();
}
As you can see, the AddAccountToStateActivity has a dependency on the IPartnerService. I can't figure a way to configure that dependency.There's nothing in the docs and neither can I find anything on the github. How do I do it?
Thanks to the help of one of the library's authors I ended up writing this code:
private static (InMemoryTestHarness harness, IStateMachineSagaTestHarness<GetOrdersState, GetOrdersStateMachine> sagaHarness) ConfigureAndGetHarnesses()
{
var provider = new ServiceCollection()
.AddMassTransitInMemoryTestHarness(cfg =>
{
cfg.AddSagaStateMachine<GetOrdersStateMachine, GetOrdersState>().InMemoryRepository();
cfg.AddSagaStateMachineTestHarness<GetOrdersStateMachine, GetOrdersState>();
})
.AddLogging()
.AddSingleton(Mock.Of<IPartnerService>())
.AddSingleton(Mock.Of<IStorage>())
.BuildServiceProvider(true);
var harness = provider.GetRequiredService<InMemoryTestHarness>();
var sagaHarness = provider
.GetRequiredService<IStateMachineSagaTestHarness<GetOrdersState, GetOrdersStateMachine>>();
return (harness, sagaHarness);
}
As you can see I'm registering my mocks with the ServiceProvider.
When I try to return my orderList as IQueryable, I get the following error:
"ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'KeplerContext'"
Ps. If I work with the DbContext directly at my controller, everything works fine.
Some help? Thanks in advance.
My controller class is:
public class OrderController : Controller
{
public readonly IAppOrder _IAppOrder;
public readonly UserManager<User> _userManager;
// Ps.: Directly for the context works fine
//private readonly KeplerContext _context;
public OrderController(IAppOrder IAppOrder, UserManager<User> userManager) //, KeplerContext context)
{
_IAppOrder = IAppOrder;
_userManager = userManager;
// Ps.: Directly for the context works fine
//_context = context;
}
public async Task<IActionResult> Index(string sortOrder, int? pageNumber)
{
var user = await _userManager.GetUserAsync(User);
var orderList = _IAppOrder.OrderList(user);
^^^^
if (!orderList.Any())
{
TempData["info"] = "no orders.";
}
else
{
var orderActive = await _IAppOrder.GetLastOrder(user);
if (orderActive.IdOrderStatus <= 5)
{
return RedirectToAction(nameof(OrderController.Order), "Order", new { Area = "App", Id = orderActive.IdOrder });
}
}
// paging
ViewData["CurrentSort"] = sortOrder;
ViewData["NumSort"] = String.IsNullOrEmpty(sortOrder) ? "num_asc" : "";
switch (sortOrder)
{
case "num_asc":
orderList = orderList.OrderBy(s => s.IdOrder);
break;
default:
orderList = orderList.OrderByDescending(s => s.IdOrder);
break;
}
int pageSize = 8;
return View(await PagingHelper<Order>.CreateAsync(orderList.AsNoTracking(), pageNumber ?? 1, pageSize));
}
}
My application class: (Ps. I am working with DDD, others classes I have omitted to simplify the question):
public IQueryable<Order> OrderList (User user)
{
return _IOrder.OrderList(user);
}
My repository class:
public class RepositoryOrder : RepositoryGenerics<Order>, IDomOrder
{
private readonly DbContextOptions<KeplerContext> _optionsBuilder;
public RepositoryOrder()
{
_optionsBuilder = new DbContextOptions<KeplerContext>();
}
public IQueryable<Order> OrderList(User user)
{
using var db = new DbContext(_optionsBuilder);
var result = db.Order
.Include(p => p.IdOrderStatusNavigation)
.Include(p => p.IdNavigation)
.Where(u => u.Id == user.Id)
.AsQueryable();
return result;
^^^^^^ <<< Error happens here!!!
}
}
My repository generics class:
public class RepositoryGenerics<T> : IDomGeneric<T>, IDisposable where T : class
{
private readonly DbContextOptions<KeplerContext> _OptionsBuilder;
public RepositoryGenerics()
{
_OptionsBuilder = new DbContextOptions<KeplerContext>();
}
public async Task Add(T obj)
{
using var data = new KeplerContext(_OptionsBuilder);
await data.Set<T>().AddAsync(obj);
await data.SaveChangesAsync();
}
public async Task Delete(T obj)
{
using var data = new KeplerContext(_OptionsBuilder);
data.Set<T>().Remove(obj);
await data.SaveChangesAsync();
}
public async Task<T> GetEntityById(int Id)
{
using var data = new KeplerContext(_OptionsBuilder);
return await data.Set<T>().FindAsync(Id);
}
public async Task<List<T>> List()
{
using var data = new KeplerContext(_OptionsBuilder);
return await data.Set<T>().AsNoTracking().ToListAsync();
}
public async Task Update(T obj)
{
using var data = new KeplerContext(_OptionsBuilder);
data.Set<T>().Update(obj);
await data.SaveChangesAsync();
}
// https://learn.microsoft.com/pt-br/dotnet/standard/garbage-collection/implementing-dispose
bool disposed = false;
SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);
// "Dispose Pattern"
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
handle.Dispose();
}
disposed = true;
}
}
Dependency injection inside the Startup.cs:
// Repository
services.AddSingleton(typeof(IDomGeneric<>), typeof(RepositoryGenerics<>));
...
services.AddSingleton<IDomOrder, RepositoryOrder>();
...
// Inteface da Application
...
services.AddSingleton<IAppOrder, AppOrder>();
...
// Service Domain
...
services.AddSingleton<IServiceOrder, ServiceOrder>();
...
Your RepositoryOrder.OrderList is returning an IQueryable meaning you are not executing the query within the scope of the method. So I believe what you are seeing is that when the query is eventually executed the DbContext has already been disposed of, because it is disposed as soon as you leave the method scope.
Instead you could call ToList rather than AsQueryable.
I am using MassTransit 5.5.5 version and xunit 2.4.1
My consumer looks like this
public class StorageInformationConsumer : IConsumer<CreateStorageInformationSummary>
{
private readonly IBus _serviceBus;
private readonly USIntegrationQueueServiceContext _USIntegrationQueueServiceContext;
public StorageInformationConsumer(IBus serviceBus, USIntegrationQueueServiceContext USIntegrationQueueServiceContext)
{
_serviceBus = serviceBus;
_USIntegrationQueueServiceContext = USIntegrationQueueServiceContext;
}
public async Task Consume(ConsumeContext<CreateStorageInformationSummary> createStorageInformationSummarycontext)
{
//....
}
}
And my Test like this
public class StorageInformationConsumerTest
{
private readonly USIntegrationQueueServiceContext _dbContext;
private readonly Mock<IBus> _serviceBusMock;
private readonly StorageInformationConsumer _storageInformationConsumer;
public StorageInformationConsumerTest()
{
var options = new DbContextOptionsBuilder<USIntegrationQueueServiceContext>()
.UseInMemoryDatabase(databaseName: "InMemoryArticleDatabase")
.Options;
_dbContext = new USIntegrationQueueServiceContext(options);
_serviceBusMock = new Mock<IBus>();
_storageInformationConsumer = new StorageInformationConsumer(_serviceBusMock.Object, _dbContext);
}
[Fact]
public async void ItShouldCreateStorageInformation()
{
var createStorageInformationSummary = new CreateStorageInformationSummary
{
ClaimNumber = "C-1234",
WorkQueueItemId = 1,
StorageInformation = CreateStorageInformation(),
};
//How to consume
}
}
How to consume the CreateStorageInformationSummary message in order to call consumer, following doesn't work
var mockMessage = new Mock<ConsumeContext<CreateStorageInformationSummary>>(createStorageInformationSummary);
await _storageInformationConsumer.Consume(mockMessage.Object);
Since you have not clarified what is actually not working, the most I can provide is how to create the mock context and pass it to the subject method under test.
This is simple enough since ConsumeContext<T> is already an interface
[Fact]
public async Task ItShouldCreateStorageInformation() {
//Arrange
var createStorageInformationSummary = new CreateStorageInformationSummary {
ClaimNumber = "C-1234",
WorkQueueItemId = 1,
StorageInformation = CreateStorageInformation(),
};
//Mock the context
var context = Mock.Of<ConsumeContext<CreateStorageInformationSummary>>(_ =>
_.Message == createStorageInformationSummary);
//Act
await _storageInformationConsumer.Consume(context);
//Assert
//...assert the expected behavior
}
Also take note that the test has been updated to return async Task and not async void
Reference Moq Quickstart
I need to resolve a DbContext based on tenant's owin value. But in the pipeline of method OnDisconnected of hub, the HttpContext is not accessible.
My hub class:
public class UserTrackingHub : Hub
{
private readonly UserContext _context;
public UserTrackingHub(UserContext context) { ... }
public override async Task OnConnected() { /* OK HERE...*/ }
public override async Task OnDisconnected(bool stopCalled)
{
// NEVER FIRES WITH IF I USE THE CTOR INJECTION.
var connection = await _context.Connections.FindAsync(Context.ConnectionId);
if (connection != null)
{
_context.Connections.Remove(connection);
await _context.SaveChangesAsync();
}
}
}
Here's my Autofac config:
public static IContainer Register(IAppBuilder app)
{
var builder = new ContainerBuilder();
// Other registers...
builder.Register<UserContext>(c =>
{
// Details and conditions omitted for brevity.
var context = HttpContext.Current; // NULL in OnDisconnected pipeline.
var owinContext = context.GetOwinContext();
var tenant = owinContext.Environment["app.tenant"].ToString();
var connection = GetConnectionString(tenant);
return new UserContext(connection);
});
var container = builder.Build();
var config = new HubConfiguration
{
Resolver = new AutofacDependencyResolver(container)
};
app.MapSignalR(config);
return container;
}
Can someone help me to identify the tenant OnDisconnected in this or any other way?
Thanks!
For anyone interested, I end up injecting a context factory instead the context itself:
public class UserTrackingHub : Hub
{
private readonly Func<string, UserContext> _contextFactory;
public UserTrackingHub(Func<string, UserContext> contextFactory) { ... }
public override async Task OnConnected() { ... }
public override async Task OnDisconnected(bool stopCalled)
{
var tenant = Context.Request.Cookies["app.tenant"].Value;
using (var context = _contextFactory.Invoke(tenant))
{
var connection = await context.Connections.FindAsync(Context.ConnectionId);
if (connection != null)
{
context.Connections.Remove(connection);
await context.SaveChangesAsync();
}
}
}
}
And Autofac's config:
// Resolve context based on tenant
builder.Register<Func<string, UserContext>>(c => new Func<string, UserContext>(tenant => UserContextResolver.Resolve(tenant)));