© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•16mo ago•
2 replies
SWEETPONY

✅ How to write unit test for this?

I have controller with this method:
[HttpGet("stream")]
public async Task StreamAsync(CancellationToken cancellationToken)
{
    Response.Headers.Append("Content-Type", "text/event-stream");

    while(!cancellationToken.IsCancellationRequested)
    {
        var sseEvent = new SseEvent<object>
        {
            Action = SseAction.Heartbeat,
            Timestamp = timeProvider.GetUtcNow().DateTime
        };

        var serializedSseEvent = Serialization.Serialize(sseEvent);

        await Response.WriteAsync($"{serializedSseEvent}", cancellationToken).ConfigureAwait(false);
        await Response.Body.FlushAsync(cancellationToken).ConfigureAwait(false);

        await Task.Delay(sseSettings.Timeout, cancellationToken).ConfigureAwait(false);
    }
}
[HttpGet("stream")]
public async Task StreamAsync(CancellationToken cancellationToken)
{
    Response.Headers.Append("Content-Type", "text/event-stream");

    while(!cancellationToken.IsCancellationRequested)
    {
        var sseEvent = new SseEvent<object>
        {
            Action = SseAction.Heartbeat,
            Timestamp = timeProvider.GetUtcNow().DateTime
        };

        var serializedSseEvent = Serialization.Serialize(sseEvent);

        await Response.WriteAsync($"{serializedSseEvent}", cancellationToken).ConfigureAwait(false);
        await Response.Body.FlushAsync(cancellationToken).ConfigureAwait(false);

        await Task.Delay(sseSettings.Timeout, cancellationToken).ConfigureAwait(false);
    }
}


unit test:
[Test]
public async Task StreamAsync_ShouldWriteHeartbeatEvents()
{
    var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));

    await controller.StreamAsync(cts.Token).ConfigureAwait(false);
}
[Test]
public async Task StreamAsync_ShouldWriteHeartbeatEvents()
{
    var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));

    await controller.StreamAsync(cts.Token).ConfigureAwait(false);
}

I want to check that Response contains sseEvents but always get an exception:
System.Threading.Tasks.TaskCanceledException : A task was canceled.

how to fix it?
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

How to refactor and unit test this method.
C#CC# / help
4y ago
Please help, Hi I need to write unit test for the following methods
C#CC# / help
3y ago
Unit test help
C#CC# / help
17mo ago
Unit test error
C#CC# / help
2y ago