Can I copy the implementation of Moq Mock?

I use Moq and love it, but I ran into a problem mocking some outdated code (before trying to reorganize it)

What I really want to do is have two separate layouts, with just a slightly different implementation, like the example below.

Mock<IFoo> fooMock = new Mock<IFoo>(); fooMock.SetupGet(f => f.bar).Returns(7); fooMock.SetupGet(f => f.bar2).Returns(3); Mock<IFoo> fooMockClone = new Mock<IFoo>(fooMock.Behavior); fooMockClone.SetupGet(f => f.bar).Returns(9); Debug.Assert(7 == fooMock.Object.bar); Debug.Assert(9 == fooMockClone.Object.bar); Debug.Assert(3 == fooMockClone.Object.bar2); Debug.Assert(3 == fooMock.Object.bar2); 

This is a simple example, but the real code is an object with dozens of methods, and I want a slightly different implementation for the two versions.

thanks

+5
source share
2 answers

It is interesting in this case if you are looking for behavior tests. Here's a sample in Machine.Fakes with the Moq sublayer ... it allows for nesting, it seems you want, while maintaining the logical separation of the tests. Requires NuGet packages: Machine.Fakes.Moq, Machine.Specifications.Should

 class IFoo_test_context : WithSubject<IFoo> { Establish context = () => Subject.bar2 = 3; } class When_fooing_with_seven : IFoo_test_context { Establish context = () => Subject.bar = 7; It bar_should_be_seven =()=> Subject.bar.ShouldEqual(7); It bar2_should_be_three =()=> Subject.bar.ShouldEqual(3); } class When_fooing_with_nine : IFoo_test_context { Establish context = () => Subject.bar = 9; It bar_should_be_nine = () => Subject.bar.ShouldEqual(9); It bar2_should_be_three = () => Subject.bar.ShouldEqual(3); } 

Again, the example is somewhat stupid because it tests mocking behavior, but itโ€™s hard to understand what you are ultimately trying to accomplish. As far as I can tell, there is no copy constructor, as you want, with a layout.

+1
source

You are not mocking the implementation details, you are mocking the values โ€‹โ€‹to get the code in the code that you need to check. It makes no sense to write a test that checks if the mocked dependency displays a value, then you just check moq.

Example:

 public class Stuff { IFoo _foo; IBar _bar; public Stuff(IFoo foo, IBar bar){ _foo = foo; _bar = bar; } public void DoStuff() { if(_foo.HasFooage) { _bar.Bar = 4; } } } 

Then your test:

 ... public void test_bar_does_bar() { var foo = new Mock<IFoo>(); foo.Setup(f => f.HasFooage).Returns(true); var bar = new Mock<IBar>(); var stuff = new Stuff(foo.Object, bar.Object); stuff.DoStuff(); Assert.That(bar.Bar, Is.EqualTo(4)); } 
0
source

Source: https://habr.com/ru/post/1202889/


All Articles