Creating DbItem with Item ID – Sitecore FakeDb
- By : Mydatahack
- Category : Sitecore, Web Technologies
- Tags: FakeDb, Sitecore, Unit Test
With FakeDb, we can mock content items. Each tree node can be created by the DbItem class. DbItem class has three constructors as below.
public DbItem(string name); public DbItem(string name, ID id); public DbItem(string name, ID id, ID templateId);
When your code is calling GetItem with the Sitecore.Data.ID object, you want to mock the content with ID.
The official documentation gives us a lot of examples. But, it seems like it only has the example with DbItem created by the first constructor. The motivation for writing this post is to give you the example of instantiating DbItem with other constructors, which is missing from the documentation (at least at the moment).
I also have a perfect example for using the second constructor. Let’s write unit tests from the previous post that uses GetItem with ID (see Using Data Source in Controller Renderings).
Just to recap, here is the repository method that uses GetItem with ID.
Let’s mock Sitecore Item with FakeDb. The key here is to instantiate DbItem with ID as the second argument. Then, the rest is straight forward.
If you are having trouble with running FakeDb, I recommend you to read this one, How to Troubleshoot FakeDb Error. Setting up FakeDb can be tricky. But, the post will explain everything that you need to successfully use FakeDb in your test project.
I have one final though about FakeDb. Using it for mocking content items like this one should be the last resort. The better design is to abstract out the logic to call Sitecore API. For example, you can use Glass.Mapper to abstract the data retrieval from the items and you will not even need to use FakeDb. Another quick way is to extract GetItem method into a helper class and inject it to the class. In this way, we can simply mock the return data from the abstracted method.
That’s it. This is the end of this topic.
There are more…
Just for fun, let’s write the test for the controller that uses this repository from the previous blog. This test is a variation of the one we have here. Except the rendering parameter bit, it is pretty much the same.
Here is the controller.
Here is the test.
Yeah, this was fun!