C# 使用NUnit发出测试空检查

C# 使用NUnit发出测试空检查,c#,unit-testing,tdd,nunit,C#,Unit Testing,Tdd,Nunit,我是一名初级开发人员,不熟悉单元测试。我的公司使用NUnit,我正在尝试在我创建的服务方法中测试空检查。如果我试图测试string acctName=”“,你知道我的断言语句应该是什么样子吗?由于某种原因,string acctName得到的编译器错误是 “该名称在当前上下文中不存在。” 我的方法: public Dict getOrder(Client client) { string acctName = client != null ? client.AccountName : "

我是一名初级开发人员,不熟悉单元测试。我的公司使用NUnit,我正在尝试在我创建的服务方法中测试空检查。如果我试图测试
string acctName=”“
,你知道我的断言语句应该是什么样子吗?由于某种原因,
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, "");

}
我的测试:

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, "");

}

我最后写的是这样的:

//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));

虽然您最终回答了自己的问题并使其正常工作,但要知道,问题是在调用assert时,您有一个语法错误,
assert.AreEqual(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);

您应该包括编译器错误是什么。另外,
客户端.AccountName
的类型是什么?您确定它是
string
,并且属性是由类定义的吗?添加了错误,是的,我肯定它是类型string,这要感谢visual studio;)为什么我的问题被否决了?首先,我没有否决你的问题。其次,
这个问题是由一个无法再复制的问题或一个简单的印刷错误引起的。虽然这里可能有类似的问题,但这一问题的解决方式不太可能对未来的读者有所帮助。
这通常会导致投票将这些问题视为离题。感谢@Nkosi的回答和解释,但是为什么expectedKey在string
actualValue=result[expectedKey]的括号中?假设Dict属于Dictionary类型,允许使用返回存储在该键上的值的键进行索引调用。我刚刚学到了一些新知识。:)我认为索引调用必须引用索引号才能获得值,如[0]或[1]