tonerdo / pose

Replace any .NET method (including static and non-virtual) with a delegate
MIT License
1.07k stars 75 forks source link

Question : Make my function throw an exception #65

Open gismail opened 2 years ago

gismail commented 2 years ago

I tried to make a function serialPortC.Open() throw an exception in that way :

Shim shimserialPortCOpen = Shim.Replace(() => serialPortC.Open()).With(delegate (SerialPort @this) { throw new Exception(); });

to check after if Close function is called or Not.

And my source code is :

        public  bool Open()
        {
            try
            {
                SerialPort.Open();
                return true;
            }
            catch (Exception)
            {
                SerialPort.Close();
                return false;
            }

        }

And my test Code is :

            SerialPort serialPortC = new SerialPort();
            bool isCalled = false;
            Shim shimserialPortCOpen = Shim.Replace(() => serialPortC.Open()).With(delegate (SerialPort @this) { throw new Exception(); });
            Shim shimserialPortCClose = Shim.Replace(() => serialPortC.Close()).With(delegate (SerialPort @this) { isCalled = true; });
            ISerialPortProvider serialPortProvider = new SerialPortProvider();
            serialPortProvider.SetSerialPOrtC(ref serialPortC);

            PoseContext.Isolate(() =>
            {
                serialPortProvider.Open();
            }, shimserialPortCOpen, shimserialPortCClose);
            Assert.IsTrue(isCalled);

However, the test raises an Unhandled Exception and I have got this message :

Test method SerialPortProviderTests.OpenTest_ThrowException_CloseCalled threw exception:
    System.Reflection.TargetInvocationException: An exception was thrown by the target of a call. ---> System.Exception: An exception of type 'System.Exception' was thrown.