如果文本== null

时间:2019-02-08 10:45:27

标签: c# unit-testing

我正在使用Microsoft单元测试进行一些单元测试

我有这段代码:

public void AddComment(Case c, string text)
        {
            if (text == null)
            {
                return;
            }

            var comment = UnitOfWork.GetRepository<CaseComment>().Create();

            comment.Case = c;
            comment.Account = _userInfoProvider.UserName;
            comment.DateUtc = DateTimeHelper.UtcNow();
            comment.Text = text;

            UnitOfWork.GetRepository<CaseComment>().Insert(comment);
        }

我对这片cdoe进行了单元测试:

 if (text == null)
            {
                return;
            }

我是这样的单元测试:

 [TestMethod]
        public void BaseProcess_Should_AddCommentIfNull()
        {
            string text = null;

            var result = string.IsNullOrEmpty(text);

            Assert.AreEqual(text, null);

        }

它显示绿色。但是代码覆盖率仍然是黄色而不是蓝色。

谢谢

我现在这样子:

 [TestMethod]
        public void BaseProcess_Should_AddCommentIfNull()
        {
            string comment = "Comment";
            var newInstance = new Case
            {

                Reference = comment,                
                DateSubmitted = DateTime.Now,                      
                Status = CaseStatus.Submitted,
            };          

            string text = null;

            var result = string.IsNullOrEmpty(text);
            Action act = () => CorrectionRequestCaseProcess.AddComment(newInstance, comment);

            Assert.AreEqual(text, null);

        }

但是如果我这样做:

 [TestMethod]
        public void BaseProcess_Should_AddCommentIfNull()
        {
            string comment = "";
            var newInstance = new Case
            {

                Reference = comment,                
                DateSubmitted = DateTime.Now,                      
                Status = CaseStatus.Submitted,
            };          

            string text = null;

            var result = string.IsNullOrEmpty(text);
            Action act = () => CorrectionRequestCaseProcess.AddComment(newInstance, text);

            Assert.AreEqual(text, null);

        }

没有任何变化enter code here

我写了另一个这样的单元测试:

[TestMethod]
public void BaseProcess_should_equalToNull()
{
    string comment = "Comment";
    var newInstance = new Case
    {

        Reference = comment,
        DateSubmitted = DateTime.Now,
        Status = CaseStatus.Submitted,
    };

    var newComment = new CaseComment();
    newComment.Case = newInstance;
    newComment.Account = _userInfoProvider.UserName;
    newComment.DateUtc = DateTimeHelper.UtcNow();
    newComment.Text = comment;

    var comment2 = _testUnitOfWork.GetRepository<CaseComment>().Create();
    _testUnitOfWork.GetRepository<CaseComment>().Insert(newComment);
}

1 个答案:

答案 0 :(得分:0)

您应该添加文本变量不等于null的其他测试用例,并验证是否调用了存储库。之后,该功能的覆盖范围将为%100。