简体   繁体   English

如何在c#桌面应用程序中对特定功能执行单元测试?

[英]How to perform unit testing for a particular function in c# desktop application?

I have a function named LoadCitation. 我有一个名为LoadCitation的函数。

public void LoadCitation()
    {

        cmd = new SqlCommand("select * from tbl_Users where isLogin=1", con);
        sqlDataAdapter = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        sqlDataAdapter.Fill(ds);
        String username = ds.Tables[0].Rows[0]["username"].ToString();
        sqlDataAdapter = new SqlDataAdapter("select id,title,author1_fname,author1_lname,author2_fname,author2_lname,author3_fname,author3_lname,doctype,year,publisher,abstract,nameofdoc,issue,volume,pgno,url,accessdate,notes,tag from tbl_Citation  where username ='" + username + "'", con);
        DataSet = new DataSet();
        con.Open();
        sqlDataAdapter.Fill(DataSet, "tbl_Citation");
        con.Close();

        dgeviewcitation.DataSource = DataSet;
        dgeviewcitation.DataMember = "tbl_Citation";
    }

I want to perform unit testing for this method. 我想为此方法执行单元测试。

[TestClass()]
public class EditcitationTests
{

    [TestMethod()]
    public void LoadCitationTest()
    {

    }
}

I have created method but didn't know what to write inside the function for unit testing... 我已经创建了方法,但不知道该在函数内部编写什么以进行单元测试...

As written, this method is not unit testable. 如所写,此方法不可单元测试。

That's because it has a hard dependency on an external resource. 那是因为它对外部资源有严格的依赖性。 What if the test was run in an environment that didn't have that DB set up? 如果测试在没有设置数据库的环境中运行怎么办? How do you know what data will be in the DB? 您如何知道数据库中将包含哪些数据? Unit tests should never leave their class (and any mocks). 单元测试永远都不应离开其类(以及任何模拟)。

So first, you need to get that SQL into a service that is injected into your form (also fix the SQL injection vulnerability while you're at it!). 因此,首先,您需要将该SQL放入注入到表单的服务中(还可以解决SQL注入漏洞!)。 Then your test will mock that service (using something like NSubstitute or Moq ) and you can verify that the data the mock returns is stored correctly in dgeviewcitation . 然后,您的测试将模拟该服务(使用NSubstituteMoq类的东西),并且您可以验证模拟返回的数据是否正确存储在dgeviewcitation

Note that UIs are usually terrible candidates for unit tests, the correct approach is to have them as a very thin (as thin as possible) layer over your actual logic, and then unit test the logic. 请注意,UI通常是单元测试的糟糕选择,正确的方法是将UI置于实际逻辑上非常薄(尽可能薄)的层上,然后对逻辑进行单元测试。 Architectural patterns like MVVM try to help with this. 诸如MVVM之类的架构模式试图对此提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM