0

I'm writing unit test for ASP.MVC 3 app with EF 4.0 and I have problem with System.NullReferenceException during the testing. I'm testing this method in service layer:

public IQueryable<Pricing> GetPricing(int categoryID)
    {
        var query = from t in _repository.GetAllPricing()
                    where t.FK_Category == categoryID
                    where t.Status.Equals("1")
                    select t;
        return query;
    }

It's working fine. But when Status equals to null and I call

svc.GetPricing(1).Count();

in the test method, then it throws exception. I'm using fake repository and other (empty) string works well.

I've tried to use pricing.Status = Convert.ToString(null); instead of pricing.Status = null; but this doesn work either.

1 Answer 1

1

The problem is that you can't call .Equals on a null reference - it will as you've experienced throw a NullReferenceException.

Instead you can call the equality operator:

public IQueryable<Pricing> GetPricing(int categoryID)
{
    var query = from t in _repository.GetAllPricing()
                where t.FK_Category == categoryID
                where t.Status == "1"
                select t;
    return query;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, test pass now. So when use Equals and when ==? Application worked fine with Equals to, only tests fail.
variable.Equals(other) will work UNLESS variable is (or could be) null. I'd stick to == to be on the safe side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.