This question already has answers here:
How do I start unit testing?
                                
                                    (8个答案)
                                
                        
                                6年前关闭。
            
                    
因此,我开始写一个类库,其中包含多年以来我编写和学习的有用方法,我将以两个代码示例开始,然后提出我的具体问题:

我还想提出这样的论点,即这与其他“我从哪里开始单元测试问题”中的某些部分不重复。

检查网络连接(不是互联网,只是网络)

    public static Boolean IsNetworkConnected()
    {
        Boolean ret = false;
        try
        {
            String HostName = System.Net.Dns.GetHostName();
            System.Net.IPHostEntry thisHost = System.Net.Dns.GetHostEntry(HostName);
            String thisIpAddr = thisHost.AddressList[0].ToString();

            ret = thisIpAddr != System.Net.IPAddress.Parse("127.0.0.1").ToString();
        }
        catch (Exception)
        {
            return false;
        }
        return ret;
    }


还有我的IsValiEmail方法(注意,我没有写正则表达式)

   public const String MatchEmailPattern = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
         + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
         + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
         + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";


    public static bool IsValidEmail(string email)
    {
        if (email != null && email != string.Empty)
            return Regex.IsMatch(email, MatchEmailPattern);
        else
            return false;
    }


因此,我的问题是如何测试这些方法是否有效,显然我想开始对我的代码进行更多的单元测试,这比这些快速示例更加复杂。

如果可能的话,我想避免安装其他工具/框架,但是我愿意接受您的想法。



这个新的单元测试代码(通过已发布的链接)应该放在哪里?在同一集合中?单独的组装?

最佳答案

看看这本书。 The art of unit testing。 Wiki页面上有很多很棒的资源。

09-30 14:06
查看更多