I have a async function say DoWork() which does some work and stores the result in a file. So the return type is void. I need to write a unit test for this function and here comes my problem.
internal sealed class MainClass: InheritedClass { public override async void Start() { base.Start(); var result = await TaskEx.Run(() => DoSomeWork()); Store(result); } } In the unit test class if I have code like below it does not wait, it moves to the next line for execution which fails the test. So, how can I make it to WAIT until the base operation is completed.
public async Task StoreDataTest() { var t = Task.Factory.StartNew(MainClass.Start); t.Wait(); var data = UtilityClass.GetStoredData(); Assert.IsNotNull(data, "No data found"); } I cannot change the return type when overriding Start(). In my case the base class is inherited in many places and changing the return type of the virtual method in base class is not an option. So should i start using background worker and event-handler ? should i use this approach ?
We cannot use .NET 4.5 because we still support XP :( So, I am using BCL libraries on .net 4.0 to get async and await features..Recently, I came across some blog which suggested not to use backgroundworker because its obsolete in later .NET versions ?
List<EntityClass> result = null; var worker = new BackgroundWorker(); worker.DoWork += (sender, e) => { result = GetData(); }; worker.RunWorkerCompleted += (sender, eventArgs) => { if (result == null) { return; } Store(result); // Event used for Unit testing purpose if (DataStoredEvent != null) { DataStoredEvent(this, new EventArgs()); } }; worker.RunWorkerAsync(); Thanks
async voidmethod :) Just make sure the method returnsTask, and you'll be fine (it gives you something toawait/Wait).I have a async function say DoWork() which does some work and stores the result in a file. So the return type is void.The latter does not in fact follow from the former. The fact that you have a function that does some work and stores the result in a file means that the return type should not bevoid, unless it's a synchronous function.