dotnet / dotnet/aspnetcore

WebApplicationFactory failing to replace registrations in Background Service

Open
#55,845 3 comments 0 reactions 0 assignees View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

I have run into an issue when trying to integration test a background service that listens to messages from RabbitMq. The issue is, after the first test runs, the subsequent test still has the same registration as the previous one.

I have created a project to illustrate the issue.

```
[Fact]
public async Task FirstTest1()
{
await SetupRabbitMq();

_fixture.BuildConsumerHttpClient((service) =>
{
service.Replace(ServiceDescriptor.Transient());
return true;
});

BasicPublish(new PublicationAddress(_rabbitMqClientConsumerConfiguration.ExchangeType, _rabbitMqClientConsumerConfiguration.LoggingExchangeName, string.Empty), "MessageTest1"u8.ToArray());
}

[Fact]
public async Task SecondTest2()
{
await SetupRabbitMq();

_fixture.BuildConsumerHttpClient((service) =>
{
service.Replace(ServiceDescriptor.Transient());

return true;
});

BasicPublish(new PublicationAddress(_rabbitMqClientConsumerConfiguration.ExchangeType, _rabbitMqClientConsumerConfiguration.LoggingExchangeName, string.Empty), "MessageTest2"u8.ToArray());
}

public class MessageTest1 : IMessage
{
public string Message => "MessageTest1";
}
public class MessageTest2 : IMessage
{
public string Message => "MessageTest2";
}

```

Here we set the service for each test to be MessageTest1 and MessageTest2 respectively along with the message that is sent from each test. Yet, as we can see in the Service, while it is receiving the message string "MessageTest2", the service registered is MessageTest1.

![image](https://github.com/dotnet/aspnetcore/assets/379692/781fc3f9-f72f-461e-aa82-51a141fa2f42)

The tests use testcontainers to allow for easy running.

### Expected Behavior

_No response_

### Steps To Reproduce

https://github.com/Pastafarian/WebApplicationFactoryBugIssue

### Exceptions (if any)

_No response_

### .NET Version

8

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.