Search code examples
c#visual-studioenvdtevspackage

In a Visual Studio package, can I simulate (DTE) GetService(typeof (DTE)) for tests?


In my package I am using (DTE) GetService(typeof (DTE)) to get information about the currently opened solution. Is there a way to simulate this for a test, particularly so that I can build using dte.Solution.SolutionBuild?

Code in main package class:

var solutionModel = new SolutionModel(((DTE) GetService(typeof (DTE))).Solution);

SolutionModel class (stripped back):

public class SolutionModel
{
    private readonly Solution _packageSolution;

    public SolutionModel(Solution solution)
    {
        _packageSolution = solution;
    }

    public SolutionModel() {} // This constructor is used for tests so _packageSolution will be null

    public bool Build()
    {
        if (_packageSolution != null)
        {
            var buildObject = _packageSolution.SolutionBuild;
            buildObject.Build(true);
            return buildObject.LastBuildInfo == 0;
        }

        return ManualCleanAndBuild(); // current messy alternative way of doing the build for tests
    }
}

So I want to be able to use the _packageSolution build rather than ManualCleanAndBuild() in my tests.


Solution

  • The way I ended up 'solving' this was to mock EnvDTE.Solution instead (seems like it can only be done in the Package_IntegrationTests project which is created for you - you can't reference EnvDTE in any other project). I couldn't figure out how to use the methods in Utils.cs as suggested by Carlos below to open my existing solutions.