1

I have a method (some code removed):

try
{
   var task = Task.Factory.StartNew(ValidateAccounts, _token);
}
catch (AggregateException)
{
   _tokenSource = new CancellationTokenSource();
   _token = _tokenSource.Token;
}

ValidateAccounts is a private method withing the same class. I would like to test that it was called and would like to be able to mock the task and try with the exception thrown and without it.

user3043457
  • 523
  • 1
  • 5
  • 16
  • 7
    Unit tests are not meant to test internal behaviour of components but to guarantee output for a determined input. If there's something you can't test, you should probably reconsider your component architecture, access modifiers or just the way you test the behaviour. – Florian F. Jun 01 '14 at 11:39

1 Answers1

3

As others have mentioned, you have to be careful when treading the fine line of what-to-test vs. what-not-to-test. It can lead to brittle tests that are too coupled with the implementation.

That being said, I absolutely see the utility in doing what you're trying to do. Testing the exception handling alone is worth asking this question.

The problem is rooted in your use of a static object (Task.Factory). Static objects/methods are notorious for impeding testability. The solution to this problem is the same used for decoupling any type of static object - introducing a seam.

You are using the static object to kick off, and return a reference to, a Task. This is something that you can define a role interface for. It might look something like:

public interface ITaskFactory
{
    Task StartNew(Action action);
}

With a production implementation that looks like:

public class TplTaskFactory : ITaskFactory
{
    public Task StartNew(Action action)
    {
        return Task.Factory.StartNew(action);
    }
}

You could then use dependency injection to supply your SUT with a mock implementation of this interface, which gives you the capability you're looking for.

Lilshieste
  • 2,744
  • 14
  • 20