pose
pose copied to clipboard
Question : Make my function throw an exception
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.