© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4mo ago•
9 replies
gax

Best way to test something that depends on a ClientWebSocket

In one of our services, we use
ClientWebSocket
ClientWebSocket
to send over some data, however we now need to write integration tests for said services. The current setup basically creates the service from a factory method that reads some config from an environment variable and the scoped service instantiates a new client to connect to said websocket, do the job it's supposed to and dispose thereafter.

I am fairly new to this codebase and thankfully have the freedom to change it if necessary, primarily because the codebase is only a few months old as well

I've never worked with WebSockets like this either so any extra feedback on how to improve this code would be great

The initialization is as follows:
    private MyService(string serverUrl)
    {
        _serverUri = new Uri(serverUrl);
        _webSocket = new ClientWebSocket();
        _cts = new CancellationTokenSource();
    }
    private MyService(string serverUrl)
    {
        _serverUri = new Uri(serverUrl);
        _webSocket = new ClientWebSocket();
        _cts = new CancellationTokenSource();
    }

Then, we connect to the server by calling the following method
    public async Task ConnectAsync()
    {
        if (_webSocket.State == WebSocketState.Open) return;

        await _webSocket.ConnectAsync(_serverUri, CancellationToken.None).ConfigureAwait(false);
    }
    public async Task ConnectAsync()
    {
        if (_webSocket.State == WebSocketState.Open) return;

        await _webSocket.ConnectAsync(_serverUri, CancellationToken.None).ConfigureAwait(false);
    }


Obviously theres some more logic to it, however removed due to being unrelated to this specifically

I initially thought of writing a super simple interface with a thin wrapper around the client then inject it via DI, though i'm not sure if that's the best way
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ What's the best way to test a URL that's it's valid?
C#CC# / help
3y ago
✅ ClientWebSocket concurrency question
C#CC# / help
4y ago
ClientWebSocket hangs on ReceiveAsync, never continues
C#CC# / help
3y ago
Blazor Design: Expression Service That Depends on other Objects
C#CC# / help
2y ago