Showing posts with label Dependency. Show all posts
Showing posts with label Dependency. Show all posts

Sunday, January 4, 2015

Unit testing smells: The method is not public

A recurring pattern emerge often when unit testing, you find an interesting method you want to test but that method is private. Of course you could call that method through other public methods on the class but it might not be easy to cover all cases. This usually is a design smell for a Single Responsibility Principle violation. More on this later.

For now, to properly test the private method we have the following options:
  • Use reflection
  • Change the method visibility to public or internal
  • Extract the method to another class

Again, if you previously read my other post on non public class and inaccessible constructor you know you should avoid using reflection in tests.

Let's take a look at the other options

Change the method visibility to public or internal

The first thing we should do is to challenge why that method is private in the first place. Why can't we just change its visibility to public or internal (and use the InternalsVisibleTo attribute)?

This breaks encapsulation of the class and will let developers call the method directly in production code. That might not be what you intended to do but can help you in the short term. Abusing this technique will burn you in the long run so be careful with it.

Fortunately, there is a simpler way: extract the method to another class.

Extract the method to another class

If you are lucky, the method you want to extract is static and don't call any other method on the original class. You should be able to extract that method to a static utility class.

But what to do when the method calls other methods and use fields or properties on the class? For that we must analyze the class to extract responsibilities using the Single Responsibility Principle.

Single Responsibility Principle

Can you tell what is the purpose of your class in one sentence without using words like: and, but, also, or, etc.? If not then your class is doing more than one thing. Each segments of the sentence could be in different classes that only have one responsibility each. If the method you want to extract use the same fields than other methods you may want to push them by parameter instead before extraction to the other class.

Find more about the Single Responsibility Principle in an old post of mine.

Saturday, October 4, 2014

Unit testing smells: The class constructor is not easy to call

When we want to test an instance method on a class the first challenge is to create an instance of that class. Hopefully the class constructor is easy to call but that's not always the case.

Let's review a few cases where the constructor might prevent us to write tests easily:
  • The constructor is private or internal
  • It requires too many arguments or it is too hard to create/provide those arguments
  • The constructor calls external dependencies

The case of the internal or private constructor

For this we can follow the same advices than with testing non-public class. But whatever you do please don't use reflection to call the constructor.

Also stated in testing non-public class, you should ask yourself if it would be better to test this class via another public class that use it. A private constructor usually means that there is a factory somewhere you should use to instantiate the class. You should figure out a way to use that factory or redesign it in case you have difficulties to work with it in unit tests.

When dealing with internal access modifier I usually use the InternalVisibleTo attribute for my test project.

[assembly: InternalsVisibleTo("Contoso.MyApp.UnitTests.dll")]

The case of the difficult constructor arguments

If the problem is that the constructor requires too many arguments then you should ask yourself if this class is too big, maybe it has too many responsibilities and don't follow the Single Responsibility Principle? In that case the class should be splitted into two or more classes. This way it will be easier to test the smaller class because its constructor should require less arguments.

Another case is when the arguments are difficult to create or provide. Maybe that in order to create one object to pass as parameter we need to create yet more objects. Micheal Feathers calls it the Onion Parameter in his book Working Effectively with Legacy Code. In that case I usually invest into a bit of testing infrastructure like factory methods or Test Data Builder in order to help me write tests faster afterwards.

Finally some parameters could be classes that wrap services or external dependencies. In that case I abstract the dependency using an interface and the Inversion of Control Principle. First extract an interface from the class. Next change the constructor to use this interface instead of the class. Finally use a mocking framework like Moq to create a fake (or create your own by hand if you don't like mocking frameworks) and pass it to the constructor.

public class MyService
{
    // public MyService(SomeDataAccessLayer dal, SomeExternalService externalService)
    public MyService(ISomeDataAccessLayer dal, ISomeExternalService externalService)
    {
        // ...
    }

    // ...
}

The case of the external dependencies calls

When the constructor itself calls an external dependency I usually refactor the constructor to inject this dependency via a parameter instead, this is called dependency injection and usually comes with the Inversion of Control Principle. This is also a good occasion to take a look at a IoC Container like Unity.

public class MyService
{
    // public MyService()
    public MyService(ISomeExternalService externalService)
    {
        // ...
        // var externalService = new ExternalService();
        externalService.CallService();
    }

    // ...
}

Sunday, June 22, 2014

Visualizing Nuget packages dependencies without Visual Studio Ultimate

In my previous post I've shown the Package Visualizer tool. Unfortunately, it's only available in the Ultimate version of Visual Studio. But all is not lost because even with a Pro version with can open DGML files.

I've created a LinqPad query that analyse packages.config files and create a DGML diagram like Package Visualizer does. I've also added things like GAC libraries and normal file based library to the mix. You can get the full Gist here. Now let's take a look at some code…

Main

Here we set a few options for our query: some file extensions to ignore when scanning for projects and more importantly the root folder path to start scanning for project files.

private string[] projectExtensionExclusions = new[] { ".vdproj", ".ndproj" };
private string rootFolder = @"C:\Users\Pascal\Dev\MyProject";

void Main()
{
  LoadAllProjects();
  LoadAllPackagesConfig();
  GenerateDGML(Path.Combine(rootFolder, "Dependencies.dgml"));
}

Data structures to uses

Then we define some fields and basic classes to help us gather the information

private List<Project> projects = new List<Project>();
private List<Package> packages = new List<Package>();
private List<Library> libraries = new List<Library>();

public class Project
{
  public Project()
  {
    this.Projects = new List<Project>();
    this.Libraries = new List<Library>();
    this.Packages = new List<Package>();
  }
  public string Path { get; set; }
  public string Name { get; set; }
  public List<Project> Projects { get; private set; }
  public List<Library> Libraries { get; private set; }
  public List<Package> Packages { get; private set; }
}

public class Package
{
  public string Name { get; set; }
  public string Version { get; set; }
}

public class Library
{
  public string Name { get; set; }
  public bool IsGAC { get; set; }
}

LoadAllProjects

Now we can start scanning for projects to load. Next we open each project files and extract all dependencies like other project, a local library or a GAC reference. We keep all this info in the project instances for later.

private void LoadAllProjects()
{
  XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
 
  var projectFiles = Directory.GetFiles(rootFolder, "*.*proj", 
    SearchOption.AllDirectories)
    .Where (pf => !projectExtensionExclusions.Any(ex => pf.EndsWith(ex)));
 
  foreach (var pf in projectFiles)
    this.projects.Add(
      new Project { Path = pf, Name = Path.GetFileNameWithoutExtension(pf) });

  // Get all projects, local libraries and GAC references
  foreach (var project in this.projects)
  {
    var projectDoc = XDocument.Load(project.Path);

    foreach (var pr in projectDoc.Descendants(ns + "ProjectReference"))
    {
      var prj = projects.SingleOrDefault(p => 
        p.Name == pr.Element(ns + "Name").Value);
      if (prj != null) 
        project.Projects.Add(prj);
      else
        (pr.Element(ns + "Name").Value 
          + " project reference not found in file " + project.Path).Dump();
    }

    foreach (var r in projectDoc.Descendants(ns + "Reference")
      .Where (r => !r.Value.Contains(@"\packages\")))
      project.Libraries.Add(GetOrCreateLibrary(
        r.Attribute("Include").Value, !r.Elements(ns + "HintPath").Any()));
  }
}

LoadAllPackagesConfig

Finally we scan for packages.config files, the ones responsible for maintaining the NuGet packages dependencies for a project. Again we extract the dependencies information from the files and keep it for later.

private void LoadAllPackagesConfig()
{
  foreach (var pk in Directory.GetFiles(rootFolder, "packages.config",
    SearchOption.AllDirectories)
    .Where (pc => !pc.Contains(".nuget")))
  {
    var project = this.projects.SingleOrDefault(p =>
      Path.GetDirectoryName(p.Path) == Path.GetDirectoryName(pk));
    if (project == null)
      ("Project not found in same folder than package " + pk).Dump();
    else
    {
      foreach (var pr in XDocument.Load(pk).Descendants("package"))
      {
        var package = GetOrCreatePackage(
          pr.Attribute("id").Value, pr.Attribute("version").Value);
        project.Packages.Add(package);
      }
    }
  }
}

GenerateDGML

Here we generate the final DGML file which is simply an XML file. The schema is quite simple: a root element DirectedGraph, a Nodes section and a Links section, all of which are mandatory. We also add a Styles section to colorize the different kind of nodes: projects, packages, libraries and GAC libraries.

private XNamespace dgmlns = "http://schemas.microsoft.com/vs/2009/dgml";

private void GenerateDGML(string filename)
{
  var graph = new XElement(dgmlns + "DirectedGraph", 
    new XAttribute("GraphDirection", "LeftToRight"),
    new XElement(dgmlns + "Nodes",
      this.projects.Select (p => CreateNode(p.Name, "Project")),
      this.libraries.Select (l => CreateNode(l.Name, 
        l.IsGAC ? "GAC Library" : "Library", l.Name.Split(',')[0])),
      this.packages.Select (p => CreateNode(p.Name + " " + p.Version, "Package")),
      CreateNode("AllProjects", "Project", label: "All Projects", @group: "Expanded"),
      CreateNode("AllPackages", "Package", label: "All Packages", @group: "Expanded"),
      CreateNode("LocalLibraries", "Library", label: "Local Libraries", @group: "Expanded"),
      CreateNode("GlobalAssemblyCache", "GAC Library", label: "Global Assembly Cache", @group: "Collapsed")),
    new XElement(dgmlns + "Links",
      this.projects.SelectMany(p => p.Projects.Select(pr => new { Source = p, Target = pr } ))
        .Select (l => CreateLink(l.Source.Name, l.Target.Name, "Project Reference")),
      this.projects.SelectMany(p => p.Libraries.Select(l => new { Source = p, Target = l } ))
        .Select (l => CreateLink(l.Source.Name, l.Target.Name, "Library Reference")),
      this.projects.SelectMany(p => p.Packages.Select(pa => new { Source = p, Target = pa } ))
        .Select (l => CreateLink(l.Source.Name, l.Target.Name + " " + l.Target.Version, "Installed Package")),
      this.projects.Select (p => CreateLink("AllProjects", p.Name, "Contains")),
      this.packages.Select (p => CreateLink("AllPackages", p.Name + " " + p.Version, "Contains")),
      this.libraries.Where (l => !l.IsGAC).Select (l => CreateLink("LocalLibraries", l.Name, "Contains")),
      this.libraries.Where (l => l.IsGAC).Select (l => CreateLink("GlobalAssemblyCache", l.Name, "Contains"))),
    // No need to declare Categories, auto generated
    new XElement(dgmlns + "Styles",
      CreateStyle("Project", "Blue"),
      CreateStyle("Package", "Purple"),
      CreateStyle("Library", "Green"),
      CreateStyle("GAC Library", "LightGreen")));

  var doc = new XDocument(graph);
  doc.Save(filename);
}

Conclusion

All that is left is to open the Dependencies.dgml file in Visual Studio


I've left a few utility methods out of the inline code in this post but you can get all the code from the Gist. Feel free to grab a copy of the file and adapt it to your heart's content. It would be easy to create a small Console Application and call it from command line if you don't like LinqPad.

There is still a lot more I could add to the query like extracting projects and library versions from the DLL, dependencies between NuGet packages from .nupkg files and highlighting duplicates NuGet packages with different version. Still, it's enough for me in it's current form.

I hope this will help you figure out your NuGet packages usage and dependencies in your solution.

Saturday, May 24, 2014

Managing NuGet packages dependencies with the Package Visualizer tool

If you ever used NuGet on a large enough solution you know you can get into trouble when projects reference different versions of the same NuGet package. That happens a lot in Azure projects as the libraries/packages get updated all the time.

I'm really surprise when I talk to people using NuGet everyday that they don't know about the Package Visualizer tool. (update: I've been told that this feature requires VS Ultimate and is not available in the Pro version. I'm still going to show it to you but stay tune for another post with a free alternative later)

NuGet Package Visualizer in Visual Studio


Once you open up a solution in Visual Studio you can go to the Tools menu, NuGet Package Manager and Package Visualizer.


This will analyse all the packages.config files in the solution and generate a DGML diagram of all NuGet packages and projects of the solution.  The diagram will help us see packages usage in the solution and find the ones with different versions.  Below you can see that I've tried this on the Roslyn (open source C# compiler) solution.


The first thing to note (and a surprise to me!) is that Roslyn use the XUnit testing framework and not MsUnit! More seriously we can quickly see that we have no duplicate packages with different versions. If we compare that to this sample solution I created we can see I'm using two versions of the Json.NET library. Now I know I should update the ClassLibrary1 project to use the new version of the package.


Of course, this only work for NuGet packages but it would be useful to have something like this for regular DLL references.  I'll try to work on a LinqPad query to generate such a DGML graph with all projects, libraries and packages.  Stay tune till next time.