来自我一天的第二个MSpec问题,这是一个新的记录。我试图非常快速地理解MSpec,并且遇到了MSpec一直存在的一些旧问题。针对存储库进行单元测试,使用MSpec,我正在做对吗?
场景:我有一个存储库,其中包含一堆漫画。现在我只需要在一个名称参数中过滤这个参数,这是一个字符串。据我所知,稍后我需要在更多属性上过滤这个属性,我决定创建一个类,它通过IoC接受我的ICartoonRepository,并包含一个名为GetByName(string name)的简单方法。
你可能会认为这是矫枉过正,但我试图教自己如何使用MSpec并以更多TDD方式工作。
所以我创建如下:
[Subject(typeof(CartoonViewModelBuilder))]
public class when_cartoon_repository_is_asked_to_get_by_id : specification_for_cartoon_viewmodel_builder
{
static string name;
static Cartoon the_cartoon;
static Cartoon result;
Establish context =() =>
{
name = "Taz";
the_cartoon = new Cartoon();
the_cartoon_repository.Stub(r => r.GetAll().Where(x=>x.Name == name).FirstOrDefault()).Return(the_cartoon);
};
Because of =() => result = subject.GetByName(name);
It should_return_cartoon =() => result.ShouldBeTheSameAs(the_cartoon);
}
这失败的存根作为仓库是空的。我有一些其他测试通过很好(简单地测试GetAll()等)。我是否需要将内容添加到存储库以进行测试?这是我难倒的地方,请温柔。另外,如果我在存根中编写linq语句,看起来好像我在实际执行和测试中做了两次。这是关键吗?它没有感觉没错。有更好的方法可以写这个测试吗?
为了清楚起见,这里是实际执行(我省略了接口和类,它只是有一个属性:
public class CartoonViewModelBuilder: ICartoonViewModelBuilder
{
readonly ICartoonRepository _cartoonRepository;
public CartoonQueryObject(ICartoonRepository cartoonRepository)
{
_cartoonRepository = cartoonRepository;
}
public IList<Cartoon> GetAllCartoons()
{
return _cartoonRepository.GetAll();
}
public Cartoon GetByName(string name)
{
return _cartoonRepository.GetAll().Where(x => x.Name == name).FirstOrDefault();
}
}
编辑1:基于缺乏反应,我应该说如果我使用的是像NUnit这样的东西,我会在测试类上创建一个类似于“LoadDummyData”的方法,并将数据投入到存储库中,然后执行复杂的过滤或查看模型构建以及手动检查发生了,这使得大的重构成为一件苦差事,看起来好像规格允许你避免这种情况吗?
编辑2:这是我的更正现在通过的测试。让我知道如果我做对了,我想我是。再次感谢握手!
static string name;
static Cartoon the_cartoon;
static Cartoon result;
static IQueryable<Cartoon> the_cartoons;
Establish context =() =>
{
name = "Taz";
the_cartoon = new Cartoon {Name = name};
the_cartoons = new List<Cartoon> {the_cartoon, new Cartoon(), new Cartoon() }.AsQueryable();
the_cartoon_repository.Stub(r => r.GetAll()).Return(the_cartoons.ToList());
};
Because of =() => result = subject.GetByName(name);
It should_return_cartoon =() => result.ShouldBeTheSameAs(the_cartoon);
编辑3:给你两个分,但是我只能不幸地给一个最好的答案。
什么类型是主题?并且为什么您将知识库存档,因为这是您的系统正在测试中? –
是的,你的代码现在看起来在技术上还行。我在回答中添加了评论。 – NOtherDev