Writing Unit Test for Custom Sitefinity Widgets

Starting point

[ControllerToolboxItem(Name = "Books", Title = "Books", SectionName = "Custom Widgets")]
public class BooksController: Controller
{
public ActionResult Index()
{
var model = new BooksModel();
model.ListOfBooks = DynamicModuleManager.GetManager().GetDataItems(TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.BooksModule.Book"));
return View("Index", model);
}
}

Creating the first unit test

using SitefinityWebApp.Mvc.Controllers;public class BooksControllerTests
{
[Test]
public void Index_WhenCalled_ReturnsIndexViewResult()
{
//arrange
var controller = new BooksController();
//act
var result = controller.Index() as ViewResult;

//assert
Assert.AreEqual("Index", result.ViewName);
}
}

Step 1: Introduce an adapter class to wrap the external dependency

public class BookService: IBookService
{
public IEnumerable<DynamicContent> GetBooks()
{
DynamicModuleManager.GetManager().GetDataItems(TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.BooksModule.Book"));
}
}
public interface IBookService
{
IEnumerable<DynamicContent> GetBooks();
}

Step 2: Inject the dependency to the constructor of controller class

public class InterfaceMappings: NinjectModule
{
public override void Load()
{
this.Bind<IBookService>().To<BookService>();
}
}
public class BooksController: Controller
{
private readonly IBookService _bookService;
public BooksController(IBookService bookService)
{
_bookService = bookService;
}
public ActionResult Index()
{
var model = new BooksModel();
model.ListOfBooks = _bookService.GetBooks();
return View("Index", model);
}
}

Step 3: Create the test double for the dependency

[Test]
public void Index_WhenCalled_ReturnsIndexViewResult()
{
//arrange
var bookService = Mock.Create<IBookService>();
Mock.Arrange(() => bookService.GetBooks()).Returns(new List<DynamicContent>());
var controller = new BooksController(bookService);
//act
var result = controller.Index() as ViewResult;

//assert
Assert.AreEqual("Index", result.ViewName);
}

Creating the second unit test

[Test]
public void Index_WhenCalled_ReturnsIndexViewResult()
{
//arrange
var bookService = Mock.Create<IBookService>();
Mock.Arrange(() => bookService.GetBooks())
.Returns(new List<DynamicContent>())
.MustBeCalled();
var controller = new BooksController(bookService);
//act
var result = controller.Index();

//assert
Mock.Assert(bookService);
}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Teng Wei Song

Teng Wei Song

6 Followers

My journey as a self-taught developer. Feel free to drop by my online profile at tengweisong.com as well!