C
C#3w ago
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?
1 Reply
SWEETPONY
SWEETPONYOP3w ago
I understand why this happens but I don't understand how to avoid this exception and just check content done
Want results from more Discord servers?
Add your server