【问题标题】:Testing event listener测试事件监听器
【发布时间】:2014-05-01 12:43:52
【问题描述】:

在我的代码中:

public class StudentPresenter
{
    IView myview;
    Repository myrepo;
    public StudentPresenter(IView vw, Data.Repository rep)
    {
        this.myview = vw;
        this.myrepo = rep;
        this.myview.ButonClick += myview_ButonClick;
    }

    public void myview_ButonClick()
    {
        var d = this.myrepo.GetById(int.Parse(myview.GivenId));
        this.myview.GetStudent(d);
    }
}

我想测试GetStudent方法会调用,所以我尝试了

[Test]
public void ctor_whenviewbuttonclick_callsviewButtonClickevent()
{
    var mock = Substitute.For<IView>();
    var stub=Substitute.For<Repository>();
    Student st = new Student();
    stub.When(p => p.GetById(Arg.Any<int>())).Do(x => st=new Student());

    StudentPresenter sp = new StudentPresenter(mock, stub);

    mock.ButonClick += Raise.Event<Action>();

    mock.Received().GetStudent(st);      
}

但测试失败:说:

Application.UnitTests.Form1Tests.ctor_whenviewbuttonclick_callsviewButtonClickevent: NSubstitute.Exceptions.ReceivedCallsException :预计会收到一个 调用匹配:GetStudent(Student) 实际上没有收到匹配 来电。

我在这里做错了什么?

【问题讨论】:

    标签: c# nunit nsubstitute


    【解决方案1】:

    这个错误可能是由Repository.GetById() 不是virtual 引起的。文档Creating a substitute 页面上的介绍有一段关于替换类时要注意的事项。

    排序后,需要对测试进行一些其他调整才能使其运行。我已经评论了这些部分,并做了一些小的重命名,以便我更容易理解。

    [Test]
    public void ctor_whenviewbuttonclick_callsviewButtonClickevent()
    {
        var view = Substitute.For<IView>();
        var repo = Substitute.For<Repository>();
        //Stub out GivenId
        view.GivenId.Returns("42");
        Student st = new Student();
        //Make GetById return a specific Student for the expected ID
        repo.GetById(42).Returns(x => st);
    
        StudentPresenter sp = new StudentPresenter(view, repo);
    
        view.ButonClick += Raise.Event<Action>();
    
        view.Received().GetStudent(st);
    }
    

    第一个更改是删除GivenId,因为演示者要求它是一个可解析为整数的字符串。第二个是让GetById 返回预期的学生(原始示例中的When..do 语法重新分配st 变量。它没有设置返回值)。

    希望这会有所帮助。

    【讨论】:

    • 谢谢,我在提出问题后也做了同样的事情。上帝保佑
    猜你喜欢
    • 2018-03-17
    • 2019-12-31
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多