Search code examples
c#seleniumrestsharp

How to handle an variable that returns null inside an Assert


I'm hustling around with selenium and having a little hard time with my Assert. I have something like this.

_request = new RestRequest($"applications", Method.GET);
var result = JsonConvert.DeserializeObject<AppRoot[]>(_restClient.Execute(_request).Content);

var org = result.FirstOrDefault(a => a.orgNr.ToString() == "1337");

Assert.IsTrue((org.applicationType == type && org == null) ? true : false, "Failed" + type);

Now if org.applicationType match the type Assert is passing (true).

And if var org = null, I want the Assert to return false, with the message - Failed type

But here the assert is looking for the variable and fails with the classic System.NullReferenceException : Object reference not set to an instance

Any ideas on how this can be handled?

Thanks in advance.


Solution

  • I think the ? conditional access syntax will help you avoid the error message. This will handle the case where org is null:

    Assert.IsTrue(org?.applicationType == type, "Failed" + type);
    

    org?.applicationType is null if org is null, so this will work around the exception that is thrown. This statement asserts that org?.applicationType == type, so when org is null the comparison will be null == type. This returns false, thus failing the test if org.applicationType is null, and passing if org.applicationType == type.