Search code examples
c#unit-testingnunitmoqtestcase

How to Null Check?


My application developed by C# (Microsoft.EntityFrameworkCore, version 6.0.25).

I am using Moq (version 4.20.70) and NUnit (version 4.0.1) for unit test cases

I tried below method to null check,

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

but i got below error

error NUnit1001: The value of the argument at position '0' of type <null> cannot be assigned to the parameter 'certificatePassword' of type string


Solution

  • Adding ! after null like this -> [TestCase(null!)] should resolve the error you're encountering. This tells the compiler to treat null as a valid value for the certificatePassword parameter.