Home > Net >  How would I instantiate a VSTO add-in in a unit test project?
How would I instantiate a VSTO add-in in a unit test project?

Time:12-28

While instantiate a VSTO base class in my unit test project i have got Null Reference exception. Below is the code that i have used and snapshot of the error which i have got while debug the test.

public UnitTest1(): base(Globals.Factory.GetRibbonFactory())
    {
        
    }

enter image description here

This add-in is work on Visio Application and I am actually new to this add-in development and not familiar how would i unit test my code for the add-in.

CodePudding user response:

You cannot instantiate VSTO add-in in a Unit Test project. More precisely, you can, but it's hard. There are much easier ways, for example, you can extract the functionality from the VSTO-related classes to "clean" classes and instantiate them instead. For example, if you have:

public partial class ThisAddIn {
  public void Foo(Visio.Application app) { ... }
  public void Bar() {
    this.Foo(this.Application);
  }
}

You could go for something like this instead:

pulic class ThisAddinActions {
  public void Foo(Visio.Application app) { ... } 
}

public partial class ThisAddIn {
  public ThisAddinActions _actions = new ThisAddinActions();
  public void Bar() {
    _actions.Foo(this.Application);
  }
}

//// test 

[TestClass]
public class UnitTest1 {
  [TestMethod]
  public void TestMethod1() {
    var app = new Visio.Application()
    var actions = new ThisAddinActions();
    actions.Foo(app);
  }
}

CodePudding user response:

Instantiating an add-in instance (or the ribbon part) is not really a good idea. Consider refactoring the add-in in the way that separate methods can be tested in unit tests with mocked dependencies.

There are several aspects here. You may consider the following:

  1. Introducing any mocking library, so you could mock dependencies.
  2. Use the dependency injection mechanisms to avoid direct dependencies and to be able to apply unit tests to the code without a question.

You may find a lot of existing threads there such as:

  • Related