如何在没有公共构造函数的情况下模拟/伪造/存根密封OracleException?

Geo*_*uer 10 .net c# oracle mocking oracleclient

在我的测试中,我需要测试抛出OracleException时会发生什么(由于存储过程失败).我正在尝试设置Rhino Mocks

Expect.Call(....).Throw(new OracleException());
Run Code Online (Sandbox Code Playgroud)

无论出于何种原因,OracleException似乎都没有公共构造函数.我该怎么做才能测试这个?

编辑:这正是我想要实例化的内容:

public sealed class OracleException : DbException {
  private OracleException(string message, int code) { ...}
}
Run Code Online (Sandbox Code Playgroud)

Kin*_*n2k 7

对于oracle的托管数据访问(v 4.121.1.0),构造函数再次更改

var ci = typeof(OracleException).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(int), typeof(string), typeof(string), typeof(string) }, null);
var c = (OracleException)ci.Invoke(new object[] { 1234, "", "", "" });
Run Code Online (Sandbox Code Playgroud)


Geo*_*uer 5

这是你如何做到的:

    ConstructorInfo ci = typeof(OracleException).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] {typeof(string), typeof(int)}, null);
    var c = (OracleException)ci.Invoke(new object[] { "some message", 123 });
Run Code Online (Sandbox Code Playgroud)

感谢所有帮助,你被投了赞成票


小智 4

看来Oracle在后来的版本中改变了他们的构造函数,因此上面的解决方案不起作用。

如果您只想设置错误代码,则以下内容适用于 2.111.7.20:

ConstructorInfo ci = typeof(OracleException)
            .GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance, 
                null, 
                new Type[] { typeof(int) }, 
                null
                );

Exception ex = (OracleException)ci.Invoke(new object[] { 3113 });
Run Code Online (Sandbox Code Playgroud)