Faking Orchard content items for testing

When testing Orchard modules, it’s often necessary to build fake content items that will be usable by your code, but won’t be database-bound. For this purpose, I’ve built a number of stubs and helpers over the years that enable most scenarios to work using fake content items. Because everything in Orchard is based off interfaces and dependency injection, mocking is rarely necessary, and a few good stubs are often all you need.

Oftentimes, you may be tempted to just new up a part. That usually won’t work, because parts are not designed to live on their own: they are supposed to be composed into content items. The part won’t be useful until it’s welded onto a content item.

That is still not enough however: some parts will also need an associated record (even if it never sees a database), and the rest of them will need an InfosetPart to exist on the content item.

In order to make it easier to build a fake content item, I’ve built the following helper:

public class ContentHelpers {
public static ContentItem PreparePart<TPart, TRecord>(
TPart part, string contentType, int id = -1)
where TPart : ContentPart<TRecord>
where TRecord : ContentPartRecord, new() {

part.Record = new TRecord();
return PreparePart(part, contentType, id);
}

public static ContentItem PreparePart<TPart>(
TPart part, string contentType, int id = -1)
where TPart : ContentPart {

var contentItem = part.ContentItem = new ContentItem {
VersionRecord = new ContentItemVersionRecord {
ContentItemRecord = new ContentItemRecord()
},
ContentType = contentType
};
contentItem.Record.Id = id;
contentItem.Weld(part);
contentItem.Weld(new InfosetPart());
return contentItem;
}
}

You can also find the file here, as part of the test project of the Nwazet.Commerce module.

The way you use it is that you new up a part, then call PreparePart on it:

var bodyPart = new BodyPart {
Record = new BodyPartRecord {
Text = "The body"
}
};
var item = ContentHelpers.PreparePart(bodyPart, "TestType", 1);

The compiler will choose the right method depending on whether the part has a record or not, then the helper will new up a record if necessary, create a content item, then weld your part, and a new InfosetPart, onto the content item. The result should be a content item that should just work in most of your test code. Note that you can weld additional parts onto the item as necessary.

In the next post, I’ll show how to stub the content manager, which is sometimes necessary, for example when the tested code needs item metadata.

No Comments