问题描述
我只想处理一个特定的ErrorCode的ManagementException异常,并且在编写单元测试时遇到麻烦。通常,我会写测试,使其类似于以下内容:
I want to handle a ManagementException exception for a specific ErrorCode only and am having trouble writing the unit test for it. Ordinarily, I would write the test so that it is something like the following:
Searcher search = MockRepository.GenerateMock<Searcher>();
// wrapper for ManagementObjectSearcher
...
search.Expect(s => s.Get()).Throw(new ManagementException());
...
但是,这不会将ErrorCode设置为我特别想要的那个,实际上ManagementException没有设置这个值的构造函数。
However, this doesn't set the ErrorCode to the one that I want in particular, indeed ManagementException doesn't have a constructor which sets this value.
如何做到这一点?
(请注意,我使用RhinoMocks作为我的嘲弄框架,但我假设这是框架独立的;我需要知道的是如何创建一个ManagementException,一个特定的ErrorCode值,另外我已经找到一些引用$ System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
方法在线,但这似乎不是可公开访问的)
(Note that I am using RhinoMocks as my mocking framework but I am assuming that this is framework independent; all I need to know here is how to create a ManagementException which has a specific ErrorCode value. Also I have found some references to a System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
method online but this doesn't appear to be publicly accessible).
推荐答案
解决这个障碍的最小努力将是一个静态帮助/实用程序方法,它使用反射来进行黑客插槽所需的错误代码。使用最优秀的反射器,我看到有一个私有的errorCode字段,它只能通过在ManagementException中定义的内部ctors设置。所以:)
The least effort to get over this hurdle would be a static helper / utility method that uses reflection to hack-slot in the required error code. Using the most excellent Reflector, I see there is a private "errorCode" field, which is only set via internal ctors defined in ManagementException. So :)
public static class EncapsulationBreaker
{
public static ManagementException GetManagementExceptionWithSpecificErrorCode(ManagementStatus statusToBeStuffed)
{
var exception = new ManagementException();
var fieldInfo = exception.GetType().GetField("errorCode",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField | BindingFlags.DeclaredOnly);
fieldInfo.SetValue(exception, statusToBeStuffed);
return exception;
}
}
认证它的工作原理
[Test]
public void TestGetExceptionWithSpecifiedErrorCode()
{
var e = EncapsulationBreaker.GetManagementExceptionWithSpecificErrorCode(ManagementStatus.BufferTooSmall);
Assert.AreEqual(ManagementStatus.BufferTooSmall, e.ErrorCode);
}
虽然我通常在测试中反思这是需要/有用的罕见情况之一。
HTH
Although I generally frown upon reflection in tests, this is one of the rare cases where it is needed / useful.
HTH
这篇关于如何设置ManagementException的ErrorCode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!