" ToDictonary"在Mocked对象上使用时抛出异常

时间:2017-12-06 11:01:34

标签: c# unit-testing mocking moq

我有这个抽象类

unsplit(lapply(split(df, df$Pupil), function(x) {
  idx <- rev(seq_len(max(which(cumsum(x$participation == 0) == 0))))
  x[idx, 'sum'] <- x[idx, 'points'] - cumsum(x[idx, 'bonus'])
  x[is.na(x$sum), 'sum'] <- 0
  x
}), df$Pupil)

   Pupil participation bonus points sum
1      2            55     6     10 -23
2      2            33     3     10 -17
3      2            88     9     10 -14
4      2            44     8     10  -5
5      2            44     0     10   3
6      2            66     7     10   3
7      2             0    11     10   0
8      1            22    12     10 -40
9      1            33    13     10 -28
10     1            33    13     10 -15
11     1             3    11     10  -2
12     1            44     1     10   9
13     1             0     3     10   0
14     1             0     0     10   0

和这个界面

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

    public virtual void Dispose();
}

我需要测试这个方法

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

在测试中,到目前为止我所做的是:

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

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); 获得var grps = groups.ToDictionary(x => x?.Name);

System.NullReferenceException: 'Object reference not set to an instance of an object.'不为空且Name不为空。里面发生了一些事情。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

你不能像这样设置空值作为字典键; (可能为空)

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

消除null或具有null Name值的项目。

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