Reputation: 3611
How should the following method be unit tested?
/// <summary>
/// Entry point for GUI thread.
/// </summary>
public void VerifyDataTypesAsync()
{
Task verificationTask = Task.Factory.StartNew(() =>
{
VerifyDataManagerAsync();
});
}
is it only possible to test via integration testing or is it possible to test that a task was created?
Thanks for your help
Upvotes: 2
Views: 3646
Reputation: 651
You can create a Factory for creating this task and use it through seams. You can use property seam - it is when you set the instance of your factory to a property of an under test class or you can use constructor seam by giving the factory through a constructor. Then you can mock this factory and set it through one of two seams and check does your VerifyDataTypesAsync method call the method of creating your task.
class YourClass
{
public YourClass(ITaskFactory factory)
{}
public void VerifyDataTypesAsync()
{
Task verificationTask = factory.Create(); // you can pass an instance of a delegate as parameter if you need.
}
}
class TasksFactory : IFactory
{
public Task Create()
{
}
}
Then in your test you can create a mock object of IFactory and pass it to the constructor of your class then set mock rules for mock to check if the method Create was called.
If we are talking about NUnit and RhinoMocks it can be looked about this:
var mockRepository = new MockRepository();
var mockObject = mockRepository.CreateMock<IFactory>();
var yourClass = new YourClass(mockObject);
Expect.Call(mockObject.Create);
mockRepository.ReplayAll();
mockObject.VerifyDataTypesAsync()
mockRepository.VerifyAll(); // throw Exception if your VerifyDataTypesAsync method doesn't call Create method of IFactory mock
roughly speaking like this... but it is just one way...
Upvotes: 3
Reputation: 2590
You could wrap the creation of the task in your own Task factory class and verify that it has been used correctly by mocking it in the unit test. For example, create a class like this:
class MyTaskFactory
{
public virtual void CreateTask(Action a)
{
Task.Factory.StartNew(a);
}
}
You supply your objects that need to create tasks with one of these factory objects. In a unit test, you supply a mocked version instead of the actual factory, and see if the CreateTask
method has been called.
For more information on mocking, have a look at RhinoMocks or Moq.
Upvotes: 2