使用UnitofWork Pattern的Rhino Mock Entity Framework无法正常工作

g.f*_*ley 5 c# nunit entity-framework rhino-mocks

这是我第一次尝试这样的事情,所以希望这很简单.

我创建了一个WCF服务,它使用Entity Framework来访问数据库.我已经实现了UnitOfWork接口,因此我的服务可以使用EF,同时仍然可以测试.

这是我的服务:

public class ProjectService : IProjectService
{
    private IUnitOfWork db = null;

    public ProjectService(IUnitOfWork unitofwork)
    {
        db = unitofwork;
    }

    public int RegisterSite(int CPUID)
    {
        if (db.Servers.Count(x => x.CPUID == CPUID) > 0)
        {
            // do something
        }

        return 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的UnitOfWork界面:

public interface IUnitOfWork
{
    IObjectSet<tblClient> Clients { get; }
    IObjectSet<tblServer> Servers { get; }
    IObjectSet<tblSite> Sites { get; }
    IObjectSet<tblServerLog> ServerLogs { get; }
    void Commit();
}
Run Code Online (Sandbox Code Playgroud)

当我使用此服务与a SQLUnitOfWork(使用EF)或InMemoryUnitOfWork(仅在内存对象)的具体实现时,它工作正常.

在我的内存对象测试完成后,我尝试了这个测试.

[Test]
public void RegisterAnExistingServer()
    {
        MockRepository mocks = new MockRepository();

        IUnitOfWork MockUnitOfWork = mocks.DynamicMock<IUnitOfWork>();

        ProjectService service = new ProjectService(MockUnitOfWork);


        Expect.Call(MockUnitOfWork.Servers.Count(x => x.CPUID == 1234)).Return(0);

        mocks.ReplayAll();

        int NewSiteID = service.RegisterSite(1234);

        mocks.VerifyAll();
    }
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试在Rhino Mock中使用它与Servers.Count上的期望时,我收到以下错误:

System.ArgumentNullException : Value cannot be null.
Parameter name: arguments
at System.Linq.Expressions.Expression.RequiresCanRead(Expression expression, String paramName)
at System.Linq.Expressions.Expression.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arg, ParameterInfo pi)
at System.Linq.Expressions.Expression.ValidateArgumentTypes(MethodBase method, ExpressionType nodeKind, ref ReadOnlyCollection`1 arguments)
at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments)
at System.Linq.Queryable.Count(IQueryable`1 source, Expression`1 predicate)
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么??

Pat*_*ele 4

迈克·伊斯特是正确的。Rhino.Mocks 不进行递归模拟。您需要模拟 Servers 属性以返回某些内容(只需创建一个空的 IObjectSet<tblServer> 并将其设置为返回值)。

另外,您不想对 lambda 设定期望。一旦所有内容都编译完毕,代码中的 lambda 和单元测试中的 lambda 就是两种完全不同的方法(并且您的期望总是会失败)。有关更多详细信息,请参阅http://groups.google.com/group/rhinomocks/msg/318a35ae7536d90a 。