我创建了一个存储库类来访问我的数据库,然后使用FakeItEasy库进行了单元测试。使用真实存储库我得到了预期的结果,而使用假存储库则返回null。
[TestClass]
public class clientRepositoryTest
{
[TestMethod]
public void GetclientById()
{
var fakeRepository = A.Fake<IclientRepository>();
const int expectedclient = 1;
IclientRepository realRepository = new clientRepository();
var realResult = realRepository.GetclientById(expectedclient); // returns expected object
try
{
A.CallTo(() => fakeRepository.GetclientById(expectedclient)).MustHaveHappened();
var fakeResult = fakeRepository.GetSupplierById(expectedSupplier); // returns null
A.CallTo(() => fakeRepository.GetSupplierById(expectedSupplier).IdSupplier).Equals(expectedSupplier);
}
catch (Exception ex)
{
//The current proxy generator can not intercept the specified method for the following reason:
// - Non virtual methods can not be intercepted.
}
}
答案 0 :(得分:0)
在拨打任何实际功能呼叫之前,您需要确保拨打所有内部虚假呼叫,如下所示
A.CallTo(() => fakeRepository.GetclientById(expectedclient)).WithAnyArguments().Returns(Fakeobject/harcoded object);
然后去单元测试电话
var fakeResult = fakeRepository.GetSupplierById(expectedSupplier);
之后去找MustHaveHappened / MustNotHaveHappened / Equals
A.CallTo(() => fakeRepository.GetclientById(expectedclient)).MustHaveHappened();
A.CallTo(() => fakeRepository.GetSupplierById(expectedSupplier).IdSupplier).Equals(expectedSupplier);
实施应该是这样的
[TestClass]
public class clientRepositoryTest
{
[TestMethod]
public void GetclientById()
{
var fakeRepository = A.Fake<IclientRepository>();
const int expectedclient = 1;
IclientRepository realRepository = new clientRepository();
var realResult = realRepository.GetclientById(expectedclient); // returns expected object
try
{
A.CallTo(() => fakeRepository.GetclientById(expectedclient)).WithAnyArguments().Returns(Fakeobject/harcoded object);
var fakeResult = fakeRepository.GetSupplierById(expectedSupplier); // returns null
A.CallTo(() => fakeRepository.GetclientById(expectedclient)).MustHaveHappened();
A.CallTo(() => fakeRepository.GetSupplierById(expectedSupplier).IdSupplier).Equals(expectedSupplier);
}
catch (Exception ex)
{
//The current proxy generator can not intercept the specified method for the following reason:
// - Non virtual methods can not be intercepted.
}
}