niceToExist
niceToExist

Reputation: 55

unit testing with ArgumentValidator.VerifyNotNullOrEmpty

I am doing unit testing. And I have the following method:

  public PortfolioFileGetListDto(string documentsCaseNumber)
        {
            ArgumentValidator.VerifyNotNullOrEmpty(documentsCaseNumber, nameof(documentsCaseNumber));

            CaseNumber = documentsCaseNumber;
        }

and I try to unit test this method like so:

 [TestMethod]
        public void PortfolioFileGetListDto_Constructor_ShouldValidateParameters()
        {
            // Portfolio           
            Action act = () => new PortfolioFileGetListDto(null);
            act.Should().Throw<ArgumentNullException>().WithMessage("Value cannot be null.\n\rParameter name: portfolio");
        }

But if I debug the unit test, I get the following exception:

System.ArgumentNullException: 'Value cannot be null.
Parameter name: documentsCaseNumber'

So how to pass this unit test?

Thank you

Upvotes: 0

Views: 159

Answers (2)

Fabio
Fabio

Reputation: 32455

Assertions expects message with ".. Parameter name: portfolio", but method under the test will raise exception with parameter name "documentsCaseNumber".

Do you really want to be very strict about the message of the exception?
I would suggest just check that correct name of the variable is included. Type of the exception already confirmed with generic assertion.

[TestMethod]
public void Constructor_WithInvalidParameter_ThrowsException()
{     
    Action construct = () => new PortfolioFileGetListDto(null);
    construct.Should().Throw<ArgumentNullException>()
            .Which.Message.Should().ContainEquivalentOf("documentsCaseNumber");
}

Upvotes: 1

David
David

Reputation: 525

The assertion depends on which Unit-Test-Framework you are using.

For Microsoft TestPlatform:

var exception = Assert.ThrowsException<Exception>(x => {
    new PortfolioFileGetListDto(null);
});
Assert.AreEqual("Value cannot be null.\n\rParameter name: portfolio", exception.Message);

Upvotes: 1

Related Questions