具有void类型的单元测试方法

时间:2014-05-23 11:52:22

标签: c# asp.net web-services unit-testing

我已经获得了一些代码,如下所示,有多种方法调用Web服务从数据库中获取一些数据。这将生成一组字段,然后从Web应用程序添加到另一个数据库。这一切都很好但我不知道如何对它进行单元测试,因为它主要是输出空白,而来自数据库的数据在每次点击按钮时都会发生变化。有没有办法进行单元测试,方法是否有效?对不起,我对单元测试很新,但我知道它有多重要,所以任何帮助都会受到赞赏。

    //Get webservice service
    private Service1 GetService()
    {
        return new TestProjectService.Service1();
    }

    //Choose which webservice we want to use based on radio button selection
    private TestProjectService.CommandMessages GetCommand(Service1 service)
    {
        var command = new TestProjectService.CommandMessages();

        switch (WebServiceRadio.SelectedIndex)
        {
            case 0:
                command = service.GetData();
                break;
            case 1:
                command = service.GetDataLINQ();
                break;
        }

        return command;
    }

    //Display the results in a label on screen
    private void DisplayResult(string text)
    {
        LatestCommandLabel.Text = text;
    }

    //Get the current username of the user logged in
    public string GetUsername()
    {
        return System.Security.Principal.WindowsIdentity.GetCurrent().Name;
    }

    //Submit the data to the database using Linq
    private void SubmitData(string username, TestProjectService.CommandMessages command)
    {
        var dc = new TestProjectLinqSQLDataContext();

        var msg = new TestProjectCommandMessage
        {
            Command_Type = command.CommandType,
            Command = command.Command,
            DateTimeSent = command.DateTimeSent,
            DateTimeCreated = command.DateTimeCreated,
            Created_User = username,
            Created_Dttm = DateTime.Now
        };

        dc.TestProjectCommandMessages.InsertOnSubmit(msg);
        dc.SubmitChanges();
    }

    //Return the value and submit data to database
    private void ReturnValue()
    {
        var service = GetService();
        var command = GetCommand(service);
        var username = GetUsername();

        if (command != null)
        {
            DisplayResult(String.Format("Last Command Called (Using {0}) : {1}", WebServiceRadio.SelectedItem.ToString(), command.Command));
            string userName = GetUsername();
            SubmitData(username, command);
        }
        else
        {
            DisplayResult("No Commands Available");
        }
    }

    //Onlick return value
    protected void GetCommandButton_Click(object sender, EventArgs e)
    {
        ReturnValue();
    }

1 个答案:

答案 0 :(得分:2)

Behavior verification是用于测试不返回任何值的方法的方法。

简而言之,由于该方法不会返回任何结果,因此测试唯一可以做的就是确保该方法能够执行相应的操作。这通常通过使用mock object来完成,include seams in the design跟踪其方法是否已被调用。

为了让您的测试使用测试双打,您需要Dependency Injection in .Net系统。

强烈建议您阅读Mark Seeman撰写的{{3}}。由于你是单元测试的新手,你无疑对单元测试所涉及的机制有很多疑问(这个答案可能引发更多问题) - 本书详细回答了这些问题。