DataSource objects are ideal for unit testing. Here's how to do it.
This is part of the series on custom data sources. If you haven't read the other ones yet, I recommend you check those out first:
- Part 1: The most basic DataSource delivering 1 item
- Part 2: Creating lists which come from elsewhere
- Part 3: Unit Testing DataSources
- Part 4: Creating a distributable DNN package with your DataSource
- Part 5: Giving the admin a configuration UI
Let's start Testing!
DataSource objects are ideal for testing, because:
- They can have clearly defined input and output
- They work in an isolated way
- Usually at runtime you don't see them, to testing them manually takes a lot of work
Because of this, all our standard datasources have many tests to increase quality and reliability. For our Tutorial #1 and #2 we created some basic tests for demo. You'll find the test-project as part of the git-solution here. So here's an example of test-code which tests the List solution in the second part of this tutorial:
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ToSic.Tutorial.DataSource;
namespace ToSic.Tutorial.Datasource.Tests
{
[TestClass]
public class TestDateTime_BasicList
{
[TestMethod]
public void DateTimeDataSource_HasManyItems()
{
var dtmDs = new DateTimeDataSourceBasicList();
Assert.AreEqual(DateTimeDataSourceBasicList.ItemsToGenerate, dtmDs.List.Count(), $"make sure it has exactly {DateTimeDataSourceBasicList.ItemsToGenerate} item in the list");
var item = dtmDs.List.First();
Assert.IsNotNull(item, "the item must be a real object");
}
[TestMethod]
public void DateTimeDataSource_HasTwoAttributes()
{
var dtmDs = new DateTimeDataSourceBasicList();
var item = dtmDs.List.First();
Assert.AreEqual(2, item.Attributes.Count, "has only 2 property");
}
[TestMethod]
public void DateTimeDataSource_HasDateFieldWhichIsDate()
{
var dtmDs = new DateTimeDataSourceBasicList();
var item = dtmDs.List.First();
var dateAsObject = item.GetBestValue(DateTimeDataSourceBasicList.DateFieldName);
Assert.IsNotNull(dateAsObject);
var dateAsDate = dateAsObject as DateTime?;
Assert.IsNotNull(dateAsDate);
}
}
}
As you can see, we have 3 trivial tests here:
- Check that it works and returns exactly 7 items
- Check that the first item has 2 attributes
- Check that the relevant field we care about is a date
This is just an example. You'll also find many more examples in the EAV test projects.
Hope this helps :)
Daniel