我对单元测试 (TDD) 感到很困惑。我有一个要测试的基本存储库模式,但我不确定我是否正确地做事。在这个阶段,我正在测试我的域,而不是担心控制器和视图。为了简单起见,这里有一个演示项目。
班级
public class Person
{
public int PersonID { get; set; }
public string Name{ get; set; }
}
界面
public interface IPersonRepository
{
int Add(Person person);
}
具体的
public class PersonnRepository : IPersonRepository
{
DBContext ctx = new DBContext();
public int Add(Person person)
{
// New entity
ctx.People.Add(person);
ctx.SaveChanges();
return person.id;
}
}
我已将 NUnit 和 MOQ 添加到我的测试项目中,并想知道如何正确测试功能。
我不确定它是否正确,但是在阅读了一些博客之后,我最终创建了一个 FakeRepository,但是如果我基于此进行测试,那如何验证我的实际界面?
public class FakePersonRepository
{
Dictionary<int, Person> People = new Dictionary<int, Person>();
public int Add(Person person)
{
int id = People.Count + 1;
People.Add(id, person);
return id;
}
}
然后用
[Test]
public void Creating_A_Person_Should_Return_The_ID ()
{
FakePersonRepository repository = new FakePersonRepository();
int id = repository.Add(new Person { Name = "Some Name" });
Assert.IsNotNull(id);
}
我是否接近在正确的庄园进行测试?
我想在将来测试诸如不传递名称会导致错误等的事情。