DatabaseEnabledTests and HQL

Topics: Customizing Orchard
Jan 26, 2012 at 4:25 PM

We're trying to write some tests using the DatabaseEnabledTestsBase class in the Orchard.Tests.Modules project. The tests we're trying to write are very similar to the CommentServiceTests or TagServiceTests, where we have a service class which queries the Orchard database and performs some other logic that we want to test.

So we followed the same pattern used in those tests where we get everything needed registered in the Register override, and returned all of the types involved in the query from the DatabaseTypes property. Our issue is that the test runs okay, but our code which does the actual query doesn't return any results even though it seems like it should. The difference in our code vs. the Comment or Tag services is that we're using HQL queries instead of using the ContentManager directly. So our class has an ISessionLocator injected and does the standard sort of pattern like this:

using (var session = _sessionLocator.For(typeof(WorkItemRecord))) {
    var queryString = @"..." //query string built up here
    var query = session.CreateQuery(queryString);
    return query.List<int>();

I should say that our test is using the ContentManager to create some sample records like so:

for (i = 1; i <= 5; i++) {
    var workItem = _contentManager.New("WorkItem");
    _contentManager.Create(workItem, VersionOptions.Published);

If we use the ContentManager in our service class to just return a list of the WorkItem content items, it works. But using our HQL query like shown above doesn't return any results, even though we're only testing it with a simple query which just queries for the WorkItemRecords (in reality, it can get more complex which is why we're using HQL instead of ContentManager in the first place).

Has anybody else done this kind of thing? Can you think of any reason it wouldn't work with an HQL query when it does with ContentManager?


Jan 26, 2012 at 4:45 PM

Maybe you should call _contentManager.Flush() before trying to read the data.

Jan 26, 2012 at 5:15 PM

Hmm, that didn't work either. We had previously tried inserting a call to the ClearSession() method on the base class, which calls _session.Flush(), but that didn't help either.

Curiously, the TearDown method in the base class throws an exception on our code, saying that the session was already closed (it does this after our assertion fails). That makes me think the problem lies with the session that's being used. Maybe our service code isn't getting the same session when it does the query that the ContentManager used when it created the sample data in our test setup?