使用 NUnit 发布测试空检查

Issue testing null check using NUnit

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

"The name does not exist in the current context."

我的方法:

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