简体   繁体   中英

“ToDictonary” throws exception when used on Mocked object

I have this abstract class

public abstract class DisposableList<T> : List<T>, IDisposable
{
    protected DisposableList();

    public virtual void Dispose();
}

and this Interface

public interface IGroup : IDisposable
{
    string Name { get; }
}

I need to test this method

public class MyClass
{
    public void MyMethod(IConnection connection)
    {
        var groups = connection.GetGroups();
        var grps = groups.ToDictionary(x => x?.Name); //Here gets System.NullReference exception
    }
}

In testing, so far what I did is:

var group1 = new Mock<IGroup>();
group1.SetupGet(c => c.Name).Returns("abc");

var groups = new Mock<DisposableList<IGroup>>();
groups.Object.Add(group1.Object);

Mock<IConnection> connection.Setup(c => c.GetGroups()).Returns(() => groups.Object);

new MyClass().MyMethod(connection);

but var grps = groups.ToDictionary(x => x?.Name); gets System.NullReferenceException: 'Object reference not set to an instance of an object.'

Name is not null and groups is not null. Something happens inside.

how can I fix this?

You can't set null value as dictionary key like this; (It is possible to be null)

groups.ToDictionary(x => x?.Name);

Eliminate the items which is null or has null Name value.

groups.Where(x => x != null && !string.IsNullOrEmpty(x.Name)).ToDictionary(x => x.Name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM