Fake and Swap private object

0 votes

I have the following class 

 public class ExampleClass : ClassBase
    {
        private readonly Service _service;


        public ExampleClass()
            : base("Sync")
        {
            _service = new Service(_log);
        }

        protected override void ExecuteProcess()
        {
            var request = Transfer.RequestParameters;
            _service.SyncMethod(request);
        }
    }

 

I' trying to fake and swap the private readonly Service _service; because I want to ignore the call to _service.SyncMethod(request).
 
[ExpectedException(typeof(WebException))]
        public void ShouldSubscriberSynchronizeExecuteInternal()
        {
            ExampleClass Trx = ExampleClass ();
            Service faked = Isolate.Fake.Instance<Service >(Members.ReturnRecursiveFakes, ConstructorWillBe.Called);
            Isolate.Swap.NextInstance<Service >().With(faked);
            Isolate.WhenCalled(() => faked.SyncMethod(null)).IgnoreCall();

            //Reflection is used to invoke private method
            var method = typeof(ExampleClass ).GetMethod("ExecuteProcess"
                , BindingFlags.NonPublic | BindingFlags.Instance);

            method.Invoke(Trx, null);
        }

 

 
Any way I just want to ignore SyncMethod, somebody has an idea who I can do that?
asked May 12 by ronald.saborio (120 points)

1 Answer

0 votes

Hi  Ronald,

You should not use the Swap.NextInstance feature, instead you can use the Isolate.Fake.NextInstance

to fake Service instace inside the ExampleClass constructor.

And for invoking private method you should use the isolator api Isolate.Invoke.Method,

for example:

 

[ExpectedException(typeof(WebException))]
[TestMethod]
public void TestMethod1()
{
    Service faked = Isolate.Fake.NextInstance<Service>(Members.ReturnRecursiveFakes, ConstructorWillBe.Called);
    ExampleClass Trx = new ExampleClass();
    
    Isolate.WhenCalled(() => faked.SyncMethod(null)).IgnoreCall();

    Isolate.Invoke.Method(Trx, "ExecuteProcess");
}

 

Tell me if it helps.

Daniel

answered May 14 by Daniel (1,340 points)
...