N
N
nordwind20132018-07-21 09:41:55
ASP.NET
nordwind2013, 2018-07-21 09:41:55

How to force a method to fall with an exception?

There is a repository method that adds an object to the base (in my case the base is a list). However, if an empty object is passed to it, it must be thrown with an exception for further processing.

public bool Save(T entity)
        {
            entity = new T();

            bool SaveResult = false;

            if (entity != null)
            {
                AllItem.Add(entity);

                SaveResult = true;
            }
            return SaveResult;
        }

And here is the test code
[TestMethod]
        public void SaveNullObjectTest()
        {
            AccountModel ent = new AccountModel();

            ent = null;

            bool result = AccountBS.Save(ent);

            Assert.IsFalse(result);
        }

But for some reason the result is still true

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
ProTreo, 2018-07-21
@nordwind2013

entity = new T();
Doesn't it bother you?
Object instance created, variable will not be null

A
Alexander Yudakov, 2018-07-21
@AlexanderYudakov

public void Save(T entity)
{
    if (entity == null)
        throw new ArgumentNullException(nameof(entity));

    AllItem.Add(entity);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question