views:

42

answers:

1

Now this is just strange:

The code as it is below works fine in a NUnit unit test with RhinoMocks (the assert passes).

This is creating an IndexSearcher in the code. Now if I use the mocked version of Get (swap the commented assignment of IndexSearcher) so now the searcher is returned by the mock, it doesn't pass the assertion.

Can anyone figure out why that is? (NUnit 2.5.2 - RhinoMocks 3.6 - Lucene 2.9.2)

    [Test]
    public void Test()
    {

        ISearcherManager searcherManager = _repository.StrictMock<ISearcherManager>();
        Directory directory = new RAMDirectory();
        IndexWriter writer = new IndexWriter(directory, new StandardAnalyzer(), true);

        searcherManager.Expect(item => item.Get()).Return(new IndexSearcher(writer.GetReader())).Repeat.AtLeastOnce();

        _repository.ReplayAll();

        //searcherManager.Get();

        Document doc = new Document();
        doc.Add(new Field("F", "hello you", Field.Store.YES, Field.Index.ANALYZED));
        writer.AddDocument(doc);

        IndexSearcher searcher = searcherManager.Get();
        //IndexSearcher searcher = new IndexSearcher(writer.GetReader());
        QueryParser parser = new QueryParser("F", new StandardAnalyzer());
        Query q = parser.Parse("hello");
        TopDocs hits = searcher.Search(q, 2);

        Assert.AreEqual(1, hits.totalHits);
    }
+1  A: 

I'm not familiar with Lucene, but the only difference I see is that via the Expect call, you are creating your IndexSearcher before adding the document to the writer. In the code that is commented out, the creation of the IndexSearcher is happening after you add the document to the writer. Is that an important distinction?

Patrick Steele
I think you're right. However I don't have a way of testing the theory. Is there a way of using a Func<T> for return so the code gets executed when the mock is called?
Khash
I moved the Expectation post indexing and it worked! Thanks. But I'm still curious to know if I can have Func<T> (like a function version of WhenCalled in Rhino)
Khash
Instead of .Return(...) try .WhenCalled(...). The lambda you pass to WhenCalled still seems to be called twice though (once when declaring the Expect and again when the "Get" is called). Not sure why that is, but it should get you past this hurdle.
Patrick Steele