I am just starting with unit testing and have a script. I am not sure how to evaluate, and my decision does not seem to be correct.
I have some code that does something if it fails, that is, it throws an exception, the exception gets caught and is logged as shown below.
public T CreateTypedObjectInstance<T>()
{
T o = default(T);
try
{
o = Activator.CreateInstance<T>();
}
catch (Exception ex)
{
LogError(ex);
throw ex;
}
return o;
}
private void LogError(Exception ex)
{
if (logger != null)
{
logger.LogError(ex);
}
}
I want to check that on error, the LogError () method is called, which in turn calls another object.
I approached this using the mock for the logger and catching the first exception, and then I approved the LogError method. However, this does not seem right to catch an exception? I remember reading something bad to try and catch in tests? Is there any other way to run this test or should I reorganize the logic? Any ideas would be great!
[Test]
public void CreateTypedObjectInstance_GivenTypeWithoutPrivateContructor_LogErrorToLogger()
{
MockRepository mockery = new MockRepository();
ILogger mockedLogger = mockery.StrictMock<ILogger>();
genericObjectFactoryInstance.Logger = mockedLogger;
Expect.Call( delegate { mockedLogger.LogError(null); } ).IgnoreArguments();
mockery.ReplayAll();
try
{
genericObjectFactoryInstance.CreateTypedObjectInstance<String>();
}
catch { }
mockery.VerifyAll();
}
EDIT
Mark Rushakoff , .
[Test]
public void CreateTypedObjectInstance_GivenTypeWithoutPrivateContructor_LogErrorToLogger()
{
MockRepository mockery = new MockRepository();
ILogger mockedLogger = mockery.StrictMock<ILogger>();
genericObjectFactoryInstance.Logger = mockedLogger;
Expect.Call( delegate { mockedLogger.LogError(null); } ).IgnoreArguments();
mockery.ReplayAll();
Assert.Throws<MissingMethodException>(() => genericObjectFactoryInstance.CreateTypedObjectInstance<String>());
mockery.VerifyAll();
}