You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#项目用NUnit做空值校验时遭遇NUnit1001错误求助

问题与解决方法

问题场景

基于C#开发的应用,依赖Microsoft.EntityFrameworkCore 6.0.25;单元测试使用Moq 4.20.70和NUnit 4.0.1。编写空值检查测试时触发NUnit1001错误,测试代码如下:

[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"));
}

错误提示:

error NUnit1001: 无法将位置“0”处的<null>类型参数值分配给类型为string的“certificatePassword”参数

原因与解决方案

NUnit 4.0+对引用类型参数传递null的类型校验更严格,默认无法直接识别[TestCase(null)]中的null属于string类型,可通过以下两种方式解决:

方式一:显式指定null的类型

修改测试用例属性,将null强制转换为string类型:

[TestCase((string)null)]
public void TestCreateClient_ShouldThrowException_IfPasswordIsNull(string certificatePassword)
{
    // 原有测试逻辑保持不变
}

方式二:使用NUnit的NullArg特性

NUnit 4.0.1及以上版本提供了NullArg.Value用于传递类型匹配的null值,需确保引用NUnit.Framework命名空间:

using NUnit.Framework;

[TestCase(NullArg.Value)]
public void TestCreateClient_ShouldThrowException_IfPasswordIsNull(string certificatePassword)
{
    // 原有测试逻辑保持不变
}

额外提示

你的断言逻辑存在小问题:ArgumentNullException的ParamName属性仅存储参数名称(即nameof(certificatePassword)),自定义错误信息会存放在Message属性中。如果CreateClientAsync方法是通过如下方式抛出异常:

throw new ArgumentNullException(nameof(certificatePassword), "certificatePassword can not be null or empty");

建议修正断言为:

// 验证参数名称
Assert.That(exception.ParamName, Is.EqualTo(nameof(certificatePassword)));
// 验证错误信息
Assert.That(exception.Message, Does.Contain("certificatePassword can not be null or empty"));

内容的提问来源于stack exchange,提问作者brendan davton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 06:07:32