user6274 user6274 -4 years ago 97
C# Question

Mocking Sitecore Database using Sitecore FakeDb

I'm currently unit testing some methods that calls sitecore database. The class has an attribute of Sitecore Database and uses that to get the items. I'm thinking of using Sitecore FakeDb to mock the items. Is there a way that I can use Sitecore FakeDb to test the methods?

public class myClass
private Database myDb;

public string getMyItemValue()
var myItem = myDb.GetItem(SomeID);
string myItemValue = myItem["value"];

return myItemValue;

I also created a constructor for the class

public myClass(myDatabase)
myDb = myDatabase;

Now on the unit test I'm trying to use Sitecore FakeDB. I've tried using the basic FakeDb information that I got from this link The code breaks when passing the FakeDb parameter to the class since it is not a Database. I'm using Xunit by the way.

public class myClassTests
public void myItemValueTest()
using (var db = new Db
new DbItem("myItem") { { "value", "hello world!" } }
myClass myclass = myClass(db); /*code breaks here*/

string myItemValue = myclass.getMyItemValue();
Assert.Equal("hello world!", myItemValue);

Any help would be much appreciated.

Answer Source

You should distinguish Sitecore Database and FakeDb Db classes. In the production assemblies, you definitely need the first one (and only the first one). The FakeDb Db class is needed for unit testing purposes only.

Prior to Sitecore 8.2 the Sitecore.Data.Database class was static and it wasn't possible to mock it in unit tests. The using new Db() statement allows to configure the in-memory data provider in a way that allows you to use the standard Sitecore API to create and retrieve the test content. You should always keep in mind that there are two kind of API.

In your sample, the Sitecore database can be reached via db.Database property:

var database = db.Database;
myClass myclass = myClass(database);

Starting from Sitecore 8.2, the static Database class has been split into abstract Database and concrete DefaultDatabase classes. That enables database mocking without FakeDb.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download