Adding fields to a fake Orchard content item

In previous posts, I’ve shown how to build fake content items, and how to use a fake content manager for testing Orchard modules. In this post, I’ll show how to add fields to a fake content item.

Fields are actually pretty easy to add, by just calling Weld on the part you want to add the field to. The only difficulty is to provide the storage that the field will need. Fortunately, Orchard comes with a very handy class, SimpleFieldStorage, that makes it possible to provide Lambdas for the getting and setting of any storage value that the field may be using.

Here is how to make it work on a text field attached to the body part of a fake item:

var bodyPart = new BodyPart {
Record = new BodyPartRecord {
Text = "Body text"
}
};
var item = ContentHelpers.PreparePart(bodyPart, "TestType", 1);
bodyPart.Weld(new TextField {
PartFieldDefinition = new ContentPartFieldDefinition("Summary"),
Storage = new SimpleFieldStorage(
(name, type) => "Text field value",
(name, type, value) => { }
)
});

Of course, this is rather heavy-handed, as it will return the same value no matter what is being queried for. You can instead let the Lambda check the name and return a different value based on that. You might also want to provide real implementation for the setter, and implement some simple dictionary as underlying storage so values can be consistently set and gotten back. For simple test cases however, this coarse approach may be all you need.

No Comments