Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing Void method which calls another void, starts Task()

I'm looking for some advice on writing some unit tests for the code below. Implementation aside (it's not my code, but I've been tasked to retroactively write some tests for it) could someone suggest how I might test this? I'm not using nUnit or a similar framework; I am using the testing tools built into Visual Studio.

I'm fairly new to writing unit tests, but I imagine I should at least test the following:

  • Valid response passed into SaveFormBrokerResponse() method
  • Test for valid exceptions thrown by the catch()
  • Testing the started Task, but not sure how to do this

I've stripped just a bit out of this function, mostly to do with instantiation and population of some objects:

public void SaveResponse(IForm form, bool isLive, HttpRequestBase request)
{
    try
    {
        var response = new FormBrokerResponses();
        // Initialize some vars on response

        using (var memory = new MemoryStream())
        {
            var serializer = new DataContractSerializer(typeof(FormKeyValue[]));
            serializer.WriteObject(memory, request.Form.AllKeys.Select(r => new FormKeyValue(r, request.Form[r])).ToArray());
            memory.Flush();
            memory.Seek(0, SeekOrigin.Begin);
            response.Values = Encoding.UTF8.GetString(memory.ToArray());
        }

        _dataHandler.SaveFormBrokerResponses(response);
    }
    catch (Exception ex)
    {
        throw new Exception("boom explosions");
    }

    Task.Factory.StartNew(() => DispatchFormResponseViaEmail(form, isLive, request.Form.AllKeys.ToDictionary(r => r, r => (object)request.Form[r])));
}

I realize that testing void implementations is tricky and questionable and that there are some integration test concerns here, but that said I can't (currently) change the implementation and need to write tests for what I have.

like image 478
trnelson Avatar asked Aug 20 '26 11:08

trnelson


1 Answers

You can't. You've created a method that fires off an asynchronous operation and then doesn't expose any means of observing the completion/results of that operation to the caller. There are lots of ways of doing this (returning a task, accepting a callback, an event, etc.) but you need to do something for the caller to be able to observe the results of the asynchronous operation. If the method doesn't expose anything, then there is nothing that the caller can reliably do.

like image 88
Servy Avatar answered Aug 22 '26 08:08

Servy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!