RavenDB:如何在UnitTests中使用RavenProfiler?

时间:2012-04-23 15:56:43

标签: ravendb nancy

我正在使用NancyFX + RavenDB。我目前正在尝试实施Ayende推荐的Denormalized Reference技术,以便从AggregateRoot构建域引用。如果您阅读该链接,您可以看到诀窍是加载父实例,然后使用RavenDB的'Include'语句预先获取引用的实例。

我已经做了所有这些并且似乎有效但我正在努力通过单元测试来确定引用的实例是否真的是预先获取的。以下是我的单元测试中的一个片段,用于说明:

[Fact]
public void Should_preload_the_mentor_mentee_references_to_improve_performance()
{
    //Given
    var db = Fake.Db();
    var mentor = Fake.Mentor(db);
    var mentee = Fake.Mentee(db);
    var relationship = Fake.Relationship(mentor, mentee, db);

    //When
    relationship = db
        .Include("Mentor.Id")
        .Include("Mentee.Id")
        .Load<Relationship>(relationship.Id);
    mentor = db.Load<User>(relationship.Mentor.Id);
    mentee = db.Load<User>(relationship.Mentee.Id);

    //Then
    relationship.ShouldNotBe(null);
    mentor.ShouldNotBe(null);
    mentee.ShouldNotBe(null);
}

上面的单元测试检查我是否可以从我的虚拟数据库(它是内存中的RavenDB嵌入式实例)加载我的实例,但它不会检查它们是否是预先获取的。

我想也许我可以使用RavenProfiler。也许这会计算我可以断言的db请求的数量(如果请求&gt; 1,则上面的单元测试会失败。)

为了完成这项工作,我必须将MVCIntegration包安装到我的单元测试项目(ouch)

PM> install-package RavenDB.Client.MvcIntegration

我还必须添加对System.Web的引用,这让我颤抖。我不认为这会起作用。

然后我将适当的初始化添加到我的Fake db提供程序中,如下所示:

public class InMemoryRavenSessionProvider : IRavenSessionProvider
{
    private static IDocumentStore documentStore;

    public static IDocumentStore DocumentStore { get { return (documentStore ?? (documentStore = CreateDocumentStore())); } }

    private static IDocumentStore CreateDocumentStore()
    {
        var store = new EmbeddableDocumentStore { RunInMemory = true};
        store.Initialize();
        store.Conventions.IdentityPartsSeparator = "-";
        RavenProfiler.InitializeFor(store); //<-- Here is the Profiler line
        return store;
    }

    public IDocumentSession GetSession()
    {
        return DocumentStore.OpenSession();
    }
}

最后,我尝试在单元测试结束时从RavenProfiler中检索某种值:

var requests = RavenProfiler.CurrentRequestSessions();

这不起作用!它在RavenProfiler中失败了,因为HttpContext为null - 这就是我对System.Web的预感。哦,好吧。

那么,我如何计算对我的RavenDB实例发出的请求数量?这可以在不需要MVC或System.Web的情况下完成,因此可以很容易地将其用于单元测试吗?

由于

1 个答案:

答案 0 :(得分:3)

您可以使用以下代码:

session.Advanced.NumberOfRequests

RavenDB探查器不会针对嵌入式文档存储运行。

您还可以查看Raven源代码中的单元测试they test this scenario