c# – 单元测试Void方法调用另一个void,启动Task()

我正在寻找一些关于为下面的代码编写一些单元测试的建议.抛开实现(这不是我的代码,但我的任务是追溯性地为它编写一些测试)有人会建议我如何测试它吗?我没有使用nUnit或类似的框架;我正在使用Visual Studio内置的测试工具.

我是编写单元测试的新手,但我想我至少应该测试以下内容:

>传递给SaveFormBrokerResponse()方法的有效响应
>测试catch()抛出的有效异常
>测试已启动的任务,但不知道如何执行此操作

我已经剥离了这个函数,主要是与实例化和一些对象的填充:

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])));
}

我意识到测试void实现是棘手和可疑的,并且这里有一些集成测试问题,但是说我不能(当前)改变实现并需要为我所拥有的内容编写测试.

最佳答案
如果您允许对代码稍作修改,我会执行以下操作,这只是一个小改动:

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");
    }

    Dispatch(form,isLive,request);
}

virtual void Dispatch(IForm form, bool isLive, HttpRequestBase request){
    Task.Factory.StartNew(() => DispatchFormResponseViaEmail(form, isLive, request.Form.AllKeys.ToDictionary(r => r, r => (object)request.Form[r])));
}

我不知道这个类的名称是什么,所以假设该类名为DutClass,您现在可以得到该类的不同实现,如下所示:

public class UnitTestClass : DutClass{
    override Dispatch(){
        //don't do anything or set a state variable that this method was called
    }
}

然后,不是测试DutClass,而是测试UnitTextClass,它具有Dispatch方法的不同实现,并且根本不启动任务.然后,您可以测试实际调用此方法,测试异常等.

转载注明原文:c# – 单元测试Void方法调用另一个void,启动Task() - 代码日志