TDD 相当新;想先试试BDD。我正在使用 MVP UI 演示模式框架,并且正在尝试使用 SubSpec 和 XUnit 编写我的第一个测试,但是当我调用存储库时,我从演示者那里得到了 NullReferenceException。
我确信答案是显而易见的,但它让我明白了。此外,我的测试似乎更关注演示模式的细节——我相信它可以工作并且可能不需要像下面那样进行测试(即引发 view.load 事件)但我想不出另一种方式。欢迎任何关于更好测试的建议。
我的单元测试:
[Specification]
public void ViewLoad_WhenTheView.LoadEventIsRaised_ViewLoadShouldGetAll()
{
var view = MockRepository.GenerateMock<IOpenJobsView>();
var repository = MockRepository.GenerateMock<IOpenJobsRepository>();
var model = new OpenJobsModel().OpenJobs;
var openJobs = new List<OpenJob>();
var jobsFromModel = view.Stub(v => v.Model.OpenJobs).Return(model);
var jobsFromRepo = repository.Stub(r => r.GetAll()).Return(openJobs);
var presenter = default(OpenJobsPresenter);
"Given an openJobsPresenter"
.Context(() => presenter = new OpenJobsPresenter(view, repository));
"when the view loads"
.Do(() => view.Raise(v => v.Load += presenter.ViewLoad, view, new EventArgs()));
"the object subscribed to the event should result in a call to GetAll"
.Assert(() => repository.AssertWasCalled(o => o.GetAll()));
"the results from the call to GetAll should be equal to the model"
.Assert(() => Assert.Equal(jobsFromModel, jobsFromRepo));
我的主持人:
public class OpenJobsPresenter : Presenter<IOpenJobsView>
{
readonly IOpenJobsRepository openJobsRepository;
public OpenJobsPresenter(IOpenJobsView view, IOpenJobsRepository openJobsRepository) : base(view)
{
this.openJobsRepository = openJobsRepository;
View.Load += ViewLoad;
}
public void ViewLoad(object sender, System.EventArgs e)
{
View.Model.OpenJobs = openJobsRepository.GetAll(); //Getting NullReferenceException here
}
}