kentico 13 | Component Test Case | Example

pankaj saxean asked on September 13, 2023 12:20

Hi Team,

Currently I'm working with Kentico 13 and creating widget/component for the site. I need a example of the unit test case for widget/component in a documentation.

Please provide me the example unit test case for the component currently I have write the unit test case for the component, as I check its only cover 69% for the code.

public ViewViewComponentResult Invoke(WidgetProperties properties) I need to write unit test case for Invoke Method of the component

Recent Answers

Jono Rickard answered on September 26, 2023 03:37

Heya Pankaj,

There's a good general approach to unit testing view components you can find here on SO

I've made a varient of that example to include the specifics of the widget properties that are in your question.

public void ExampleWidgetPropertiesViewComponentTest() {

    // Arrange
    var expected = "Title example";
    var httpContext = new DefaultHttpContext(); //You can also Mock this
    //...then set user and other required properties on the httpContext as needed

    var viewContext = new ViewContext();
    viewContext.HttpContext = httpContext;
    var viewComponentContext = new ViewComponentContext();
    viewComponentContext.ViewContext = viewContext;

    var viewComponent = new ExampleWidgetViewComponent();
    viewComponent.ViewComponentContext = viewComponentContext;

    //Create a testing instance of the widget properties as if a CMS editor had applied them.
    var widgetProperties = new ExampleWidgetProperties(){
        Title = "Title example"

    var viewModel = viewComponent.Invoke(widgetProperties).ViewData.Model as ExampleWidgetViewModel;

    Assert.AreEqual(expected, viewModel.Title);
0 votesVote for this answer Mark as a Correct answer

pankaj saxean answered on September 26, 2023 04:32

Hey Jono Rickard, Thanks for you reply I have already implemented the test cases but here you not mention any test case for exception related, when we use component code using the try catch in that case your code converge not 100% it may be 87 to 90%. To archive the 100% test code coverage you will include try catch on your test cases.

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.