简体   繁体   English

对通用查询工厂进行单元测试

[英]Unit testing a generic query factory

I have implemented a command/query architecture for a project I am working on, but am having trouble testing my classes that require use of the associated factories. 我已经为正在处理的项目实现了命令/查询体系结构,但是在测试需要使用关联工厂的类时遇到了麻烦。 The basis of my architecture can be found here: https://cuttingedge.it/blogs/steven/pivot/entry.php?id=92 我的体系结构的基础可以在这里找到: https : //cuttingedge.it/blogs/steven/pivot/entry.php?id=92

In particular, I have something similar to the following 特别是,我有类似以下内容

public interface IQueryFactory
{
    TQuery CreateQuery<TQuery, TResult>() 
        where TQuery : IQuery<TResult>;
}

public interface IQuery<TResult>
{
} 

public interface IQueryHandler<in TQuery, out TResult>
    where TQuery : IQuery<TResult>
{
    TResult Execute(TQuery query);
}

public interface IQueryHandlerFactory
{
    IQueryHandler<TQuery, TResult> CreateQueryHandler<TQuery, TResult>()
        where TQuery : IQuery<TResult>;
}

public class GetFooDataQuery : IQuery<IEnumerable<FooData>>
{   
    public int FooId { get; set; }
}

public class GetFooQueryHandler : IQueryHandler<GetFooDataQuery, IEnumerable<FooData>>
{        
    private readonly IFooRepository _fooRepository;

    public GetFooDataQueryHandler(IFooRepository fooRepository)
    {          
        _fooRepository = fooRepository;
    }

    public IEnumerable<FooData> Execute(GetFooDataQuery query)
    {           
        return    _fooRepository.Foo.Where(x => x.fooId > query.FooId).ToList();            
    }
}

My classes that need to query the database have a constructor that includes a query factory and a query handler factory. 我需要查询数据库的类具有一个构造函数,该构造函数包括一个查询工厂和一个查询处理程序工厂。 Everything gets wired up via Ninject. 一切都通过Ninject连接起来。

It works fine, but I am finding it difficult to create Unit tests for any class that includes query factories as I need to include the factories as part of the constructor. 它工作正常,但是我发现很难为任何包含查询工厂的类创建单元测试,因为我需要将工厂包含在构造函数中。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Create a test repository that implements IFooRepository and pass that to the constructor for GetFooQueryHandler. 创建一个实现IFooRepository的测试存储库,并将其传递给GetFooQueryHandler的构造函数。 Since it is your test class, you can set it to known test values for the purposes to testing code that depends on this. 由于它是您的测试类,因此可以将其设置为已知的测试值,以测试依赖于此的代码。

[TestMethod]
public void TestMethod1()
{
    var x = new GetFooQueryHandler(new TestFooRepository
        {
            Foo = new List<FooData>()
        });
    var result = x.Execute(new GetFooDataQuery { FooId = 45 });

}

class TestFooRepository : IFooRepository
{
    public IEnumerable<FooData> Foo { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM