单元测试学习:无返回值,触发委托

要测试以下方法:

private void DoAct(string msg)
{
    ActMessage(msg);
}

public Action<string> ActMessage;

 

测试无返回值的方法主要是否引发了异常,有没有对非空做处理:

public void DoActTest()
{
    Form1_Accessor target = new Form1_Accessor(); 
    Exception ex = null;
    string msgResponse = string.Empty;
    string msgPost = string.Empty; 

    try
    {
        target.DoAct(msgPost);
    }
    catch (Exception e)
    {
        ex = e;
    }

    Assert.IsNull(ex, "异常,测试失败!");
}    
二,测试被测方法是否正正触发了委托:
public void DoActTest()
{
    Form1_Accessor target = new Form1_Accessor(); 
    Exception ex = null;
    string msgResponse = string.Empty;
    string msgPost = string.Empty;
    target.ActMessage = (m) => { msgResponse = m; };
    try
    {
        target.DoAct(msgPost);
    }
    catch (Exception e)
    {
        ex = e;
    }

    Assert.IsNull(ex, "异常,测试失败!");            
                
    Assert.AreEqual(msgPost, msgResponse);
}

一般我的做法是,在DoAct 中需要判断下 ActMessage 是否为空的判断。此处DoAct是私有方法,VS 产生的是一个私有方法访问器,如上的 Form1_Accessor,而不是公用方法的 Form1 实例。

posted @ 2010-03-15 16:23  life++  阅读(1057)  评论(0编辑  收藏  举报