如何使用Fake It Easy进行假方法的参数验证

时间:2020-04-06 00:20:11

标签: c# unit-testing fakeiteasy

我不熟悉使用Fake It Easy编写单元测试用例。 我无法弄清楚,我们如何验证该方法是否由某些特定参数调用?

请参见下面的示例

主班

//Model
public class Request 
{
    public string Param { get; set; }
}

//Repository
public class MyRepository : IMyReporitory
{
    public string Get(Expression<Func<Request, bool>> query) { }
}

//Service
public class MyService
{
    private readonly IMyReporitory _myReposotory;
    public MyService(IMyReporitory myReposotory) 
    {
        _myReposotory = myReposotory;
    }

    public string Search(string searchText) 
    {
       return _myReposotory.Get(x => x.Param == searchText);  
    }
}

测试课程

[TestClass]
public class DashboardServiceTest
{
    MyService service;
    IMyRepository _fakeMyRepository;

    public void Initialize()
    {
        _fakeMyRepository= A.Fake<IMyRepository>();
        service = new MyService(_fakeMyRepository);
    }

    [TestMethod]
    public void GetFilteredRfqs_FilterBy_RfqId()
    {
       var result = service.Search("abc");
       A.CallTo(() => _fakeMyRepository.Get(A<Expression<Func<Request, bool>>>._)).MustHaveHappened();
    }
}

在此示例中,如何检查使用“ abc”参数调用的_myReposotory.Get()方法?

1 个答案:

答案 0 :(得分:0)

执行此操作!

[TestMethod]
public void GetFilteredRfqs_FilterBy_RfqId()
{
   //the test that get was called with the x => x.Param == "abc" parameter
   A.CallTo(() => _fakeMyRepository.Get(x => x.Param == "abc")).MustHaveHappened();

   //or this (you can add any any specific test replace "default")
   A.CallTo(() => _fakeMyRepository.Get(x => x.Param == "abc")).WhenArgumentsMatch(default);

   //or this
   A.CallTo(() => _fakeMyRepository.Get(x => x.Param == "abc")).WhenArgumentsMatch((Expression<Func<Request, bool>> query) => true).Returns("Correctly worked!!");

   //this throws an exception if query.ReturnType.Name == "xyz"
   A.CallTo(() => _fakeMyRepository.Get(x => x.Param == "abc")).WhenArgumentsMatch((Expression <Func<Request, bool>> query) => query.ReturnType.Name == "xyz" /*query.Equals(default)*/).Throws<Exception>();

  //I EDITED THIS POST TO ADD THIS ONE

  //if you want to make more detail check on your parameter, you can do this!
  A.CallTo(() => _fakeMyRepository.Get(A<Expression<Func<Request, bool>>>.That.Matches(s => s.Type.Name == "xyz"))).MustHaveHappened();
}