【问题标题】:Issue testing null check using NUnit使用 NUnit 测试空检查
【发布时间】:2016-08-31 19:18:00
【问题描述】:

我是一名初级开发人员,刚接触单元测试。我的公司使用 NUnit,我正在尝试在我创建的服务方法中测试空检查。如果我尝试测试 string acctName = "" 是否知道我的 Assert 语句应该是什么样子?出于某种原因,string acctName 出现编译器错误提示

“当前上下文中不存在该名称。”

我的方法:

public Dict getOrder(Client client)
{
    string acctName = client != null ? client.AccountName : "";

    Dict replacements = new Replacement
    {
        {COMPANY_NAME, acctName}
    };
    return new Dict(replacements);
}

我的测试:

public void getOrderNullTest()
{

    //Arrange

    Client myTestClient = null;

    //Act

    contentService.getOrder(myTestClient);

    //Assert

    Assert.AreEqual(string acctName, "");

}

【问题讨论】:

  • 另外,Client.AccountName 的类型是什么?你确定它是string,并且该属性是由类定义的吗?
  • 添加了错误,是的,由于Visual Studio,我很肯定它是类型字符串;)
  • 为什么我的问题被否决了?
  • 首先,我没有否决您的问题。其次,This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. 通常会导致投票关闭这些主题。
  • 虽然您最终回答了自己的问题并使其工作,但要知道问题在于在调用断言时您有 Assert.AreEqual(string acctName, "") 这是一个语法错误,string acctName 这是当您正在定义一个方法,而不是试图调用它。希望对您有所帮助。

标签: c# unit-testing tdd nunit


【解决方案1】:

我最终是这样写的:

//Arrange

Client myTestClient = null;
string expectedValue = String.Empty;
string expectedKey = COMPANY_NAME;

//Act

Dict actual = contentService.getOrder(myTestClient);

//Assert

Assert.IsTrue(actual.ContainsKey(expectedKey));
Assert.IsTrue(actual.ContainsValue(expectedValue));

【讨论】:

    【解决方案2】:

    虽然您最终回答了自己的问题并使其正常工作,但要知道问题在于在调用断言时您有 Assert.AreEqual(string acctName, "") 有语法错误,string acctName 用于定义方法时,不想调用它。

    这是你可以写的另一种方式

    //Arrange
    Client myTestClient = null;
    string expectedValue = String.Empty;
    string expectedKey = COMPANY_NAME;
    
    //Act
    Dict result = contentService.getOrder(myTestClient);
    
    //Assert
    Assert.IsNotNull(result);
    
    string actualValue = result[expectedKey];
    
    Assert.IsNotNull(actualValue);
    Assert.AreEqual(expectedValue, actualValue);
    

    【讨论】:

    • 感谢@Nkosi 的回答和解释,但为什么字符串actualValue = result[expectedKey]; 中的括号中是expectedKey?
    • 假设 Dict 是 Dictionary 类型,这将允许使用返回存储在该键处的值的键进行索引调用。
    • 我刚刚学到了一些新东西。 :) 我认为索引调用必须引用索引号才能获取值,例如 [0] 或 [1]
    猜你喜欢
    • 2011-05-19
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 2014-08-14
    • 1970-01-01
    相关资源
    最近更新 更多