Seppo
Seppo

Reputation: 15

Microsoft Fakes: Trying to shim a class but dependencies are still there

Ok, so here's the deal: I have a complex, heavily dependent class LegacyClass that I'd like to shim so that I get rid of all its dependencies while unit testing other parts of the code base. That class creates dependencies already inside its default constructor, so I need to override it with something with no external dependencies, say, with an empty default constructor. And this is what I'm trying to do (using the Visual Studio 2013 Professional Test Framework):

using System;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MyApp_Unit_Tests {
    [TestClass]
    public class UnitTest1 {
        [TestMethod]
        public void TestInstantiation1() {
            using (ShimsContext.Create()) {
                MyNamespace.Fakes.ShimLegacyClass.Constructor = x => { };
                var legacyClassInstance = new MyNamespace.Fakes.ShimLegacyClass();
                var sut = new MyNamespace.Gui.ViewModels.MainWindowViewModel(legacyClassInstance);
            }
        }
    }
}

However, this does not work. When MainWindowViewModel is instantiated, for some reason all the same external dependencies are still required as with using the original class! Why?

The exception I'm getting, though, is System.BadImageFormatException, so I probably have some confusion about the target CPU settings, too, but anyway the root cause is that it's attempting to load the external DLL referred to only in the original (non-shimmed) legacy class in its default constructor, while I think it no longer should.

Obviously I've been misunderstood, but where's the mistake? Can I not override default constructors, after all, even with using Shims, or is my approach just wrong? What am I missing?

Thanks a million in advance for any advice!

-Seppo

Upvotes: 0

Views: 1470

Answers (1)

Fery
Fery

Reputation: 481

I had same problem and I solved it maybe this approach going to help you

 using (ShimsContext.Create()) 
 {

  LegacyClass obj=new LegacyClass();
  ShimLegacyClass shimobj=new ShimLegacyClass(obj);

  //
  // modify every thing you want on shimobj
  //

  shimobj.InstanceBehavior = ShimBehaviors.Fallthrough;

  //rest of test
  }

This approach helps you to break dependencies in every part you want and keep the rest same as main class

Upvotes: 1

Related Questions