Moq a MEF Import?

I have a class A that has the following:

public class A { [Import(typeof(IMyService)] public IMyService MyService { get; set; } public A() { CompositionInitializer.SatisfyImports(this); } public void DoWork() { //Blah MyService.DoIt(); //Blah } } 

And a test to verify this (a separate Dll - obviously)

 [TestMethod] public void TestDoWork() { //Blah DoWork(); //Assert assert } 

This fails because trying to call "MyService" gives me a null value. I tried:

 [ClassInitialize] public void InitialiseClass() { var myService = new Mock<IMyService>(); MyService = myService.Object; } 

with 'MyService' declared as:

 [Export(typeof(IMyService))] public IMyService MyService { get; set; } 

But there is still no joy, I am missing something - is this possible?

I use SL3, MEF Preview 9 and MOQ.

Any help appreciated!

Greetings

Chris

+6
c # moq silverlight mef
source share
3 answers

Your class should look like this:

 public class A { private readonly IMyService _myService; [ImportingConstructor] public A(IMyService myService) { _myService = myService; } public void DoWork() { //Blah _myService.DoIt(); //Blah } } 

And your test should look like this:

 [TestMethod] public void DoWork_invokes_IMyService_DoIt() { // arrange mock and system under test var myService = new Mock<IMyService>(); var a = new A(myService.Object); // act a.DoWork(); // assert that DoIt() was invoked myService.Verify(x => x.DoIt()); } 

The fact that you are using MEF should not be important in unit tests. MEF enters the game only when many components are connected, which is exactly the opposite of what happens in the unit test. A unit test is, by definition, testing a component in isolation.

Change If you prefer property nesting, then your class does not need a constructor, and part of the location in your unit test should look like this:

  var myService = new Mock<IMyService>(); var a = new A(); a.MyService = myService.Object; 
+4
source share

If you added [Export] to your IMyService instance, did you add it to the composition container? If not, he will not participate in the composition. To add a marked object to the container, do the following:

  container.ComposeExportedValue<IMyService>(mock.Object); 

Or simply:

 container.ComposeExportedValue(mock.Object); // type inference. 

Doing this before you create an instance of A will include it in your instance of A.

+1
source share

You should not run MEF in your unit tests. Composition is beyond the scope of unit test, but does not differ from the IoC container.

Introduced, you must enter the necessary dependencies manually:

 [TestClass] public class ATest { Mock<IMyService> myService ; [TestInitialize] public void InitialiseClass() { myService = new Mock<IMyService>(); } [TestMethod] public void DoWorkShouldCallDoIt { A a = new A(); a.MyService = myService.Object; a.DoWork(); myService.Verify(m=>m.DoIt(), Times.Once()); } } 
0
source share

All Articles