I have a problems with unit testing of a method with TokenSource cancellation.
SUT method is very simple:
public void OnTaskCancellationExecute(object obj)
{
TaskCancellation = true;
TokenSource.Cancel();
CommandCompletedControlsSetup();
}
And is called by command execution:
TaskCancellationCommand = new DelegateCommand(OnTaskCancellationExecute);
CommandCompletedControlsSetup
method, that is executed after TokenSource
is cancelled, contains:
TaskCancellation = false;
My test method:
[Fact]
public void OnTaskCancellationExecute_CancelTask_True()
{
_viewModel.TaskCancellation = false;
_viewModel.TokenSource = new CancellationTokenSource();
_viewModel.TaskCancellationCommand.Execute(null);
Assert.True(_viewModel.TaskCancellation);
}
Cancellation of all Tasks with TokenSource
in SUT takes a while in running solution. But not in unit testing. How should I Assert
, that _viewModel.TaskCancellation
was true
, before was changed again to false
after CommandCompletedControlsSetup
was called in tested method? Or it is kind of problem with my architecture? Should I create some Tasks in test method and attach the SUT tokens somehow?
This way it is not possible. Since you set TaskCancellation
explicitly to true
right after entering the method you don't need to test the property itself. It will work of course. If the value of TaskCancellation
is the result of an operation you would test this operation separately. If the value of TaskCancellation
is the result of a condition you would test this condition separately. To test your example code, you first assert that the TokenSource.IsCancellationRequested
is true
after the command has executed. Then write a second test case to test CommandCompletedControlsSetup()
.