How to Null Check?

164 views Asked by At

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

2

There are 2 answers

0
Pathum Senaratna On BEST ANSWER

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.

3
Abdul Moiz On

When using NUnit with nullable parameters, you should use TestCase(null) for nullable types. However, since string is a reference type and already nullable, you should use TestCase((string)null) to explicitly pass a null value.

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

}