Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question : Make my function throw an exception #65

Open
gismail opened this issue Jul 20, 2021 · 0 comments
Open

Question : Make my function throw an exception #65

gismail opened this issue Jul 20, 2021 · 0 comments

Comments

@gismail
Copy link

gismail commented Jul 20, 2021

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.
@gismail gismail changed the title Make my function throw an exception Question : Make my function throw an exception Jul 20, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant