如何清空?

问题描述 投票:0回答:2

我的应用程序由 C# 开发(Microsoft.EntityFrameworkCore,版本 6.0.25)。

我使用 Moq(版本 4.20.70)和 NUnit(版本 4.0.1)进行单元测试用例

我尝试了以下方法来进行空检查,

 [TestCase(null)]
 public void TestCreateClient_ShouldThrowException_IfPasswordIsNull(string certificatePassword)
   {
      //Arrange
    var clientFactory = new ClientFactory(_mockRepositoryWrapper.Object, _alertService.Object);

      //Act
      var exception = Assert.ThrowsAsync<ArgumentNullException>(() => clientFactory.CreateClientAsync(certificatePassword, TestValues.CERTIFICATE_BASE64, TestValues.APP_ID, TestValues.DOMAIN, TestValues.CUSTOMER_ID, TestValues.ENVIRONMENT_ID, TestValues.LOCALE));

       //Assert
     Assert.That(exception.ParamName, Is.EqualTo("certificatePassword can not be null or empty"));
        }

但是我遇到了以下错误

错误NUnit1001:

<null>
类型的位置“0”处的参数值无法分配给字符串类型的参数“certificatePassword”

c# unit-testing nunit moq testcase
2个回答
0
投票

将 NUnit 与可空参数一起使用时,您应该对可空类型使用

TestCase(null)
。但是,由于
string
是引用类型并且已经可以为空,因此您应该使用
TestCase((string)null)
显式传递
null
值。

    [TestCase((string)null)]
    public void TestCreateClient_ShouldThrowException_IfPasswordIsNull(string certificatePassword)
    {
        // Arrange
        var clientFactory = new ClientFactory(_mockRepositoryWrapper.Object, _alertService.Object);
    
        // Act
        var exception = Assert.ThrowsAsync<ArgumentNullException>(() => clientFactory.CreateClientAsync(
            certificatePassword,
            TestValues.CERTIFICATE_BASE64,
            TestValues.APP_ID,
            TestValues.DOMAIN,
            TestValues.CUSTOMER_ID,
            TestValues.ENVIRONMENT_ID,
            TestValues.LOCALE));
    
        // Assert
        Assert.That(exception.ParamName, Is.EqualTo("certificatePassword can not be null or empty"));

}

0
投票

添加!像这样的 null 之后 -> [TestCase(null!)] 应该可以解决您遇到的错误。这告诉编译器将 null 视为certificatePassword 参数的有效值。

© www.soinside.com 2019 - 2024. All rights reserved.