Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用于单元测试的Castle类代理_C#_Unit Testing_Castle Dynamicproxy - Fatal编程技术网

C# 用于单元测试的Castle类代理

C# 用于单元测试的Castle类代理,c#,unit-testing,castle-dynamicproxy,C#,Unit Testing,Castle Dynamicproxy,我在琢磨怎么做 假设我有一个包含两个虚拟方法的具体类Foo,Execute()和GetFile()Execute()将调用GetFile。我想确保当它执行时,GetFile()将抛出两个不同的异常,Foo应该以可测试的方式优雅地处理这些异常 对于我的单元测试,我设想实例化一个来自castle的DynamicProxy项目,在该项目中我截获GetFile()以抛出异常,然后调用DynamicProxy对象的Execute()方法,并测试结果,但我看不到如何做到这一点 这可行吗?如果是这样,动态代理

我在琢磨怎么做

假设我有一个包含两个虚拟方法的具体类
Foo
Execute()
GetFile()
Execute()
将调用
GetFile
。我想确保当它执行时,
GetFile()
将抛出两个不同的异常,
Foo
应该以可测试的方式优雅地处理这些异常

对于我的单元测试,我设想实例化一个来自castle的DynamicProxy项目,在该项目中我截获
GetFile()
以抛出异常,然后调用DynamicProxy对象的
Execute()
方法,并测试结果,但我看不到如何做到这一点


这可行吗?如果是这样,动态代理对象的创建会是什么样子?

您不需要手工编写自己的代理,因为大多数模拟框架都支持您的场景

下面是一个使用的示例(Moq将在内部为您创建一个动态代理):

public类SomeException:Exception{}
公开课Foo
{
公共虚拟int-Execute()
{
尝试
{
GetFiles();
}
捕获(某些例外)
{
返回1;
}
返回0;
}
公共虚拟void GetFiles()
{
//...
}
}
[测试]
公共空间
{
var foooundertest=新模拟();
foooundertest.CallBase=true;
Setup(f=>f.GetFiles()).Throws(newsomeexception());
var result=fooUnderTest.Object.Execute();
断言。等于(1,结果);
}
您只需小心设置
Callbase=true
,它将:

如果没有期望覆盖 成员(也称为Rhino Mocks中的“部分模拟”):默认值为false


杰出的。正是我想要的。
public class SomeException : Exception { }

public class Foo
{
    public virtual int Execute()
    {
        try
        {
            GetFiles();
        }
        catch (SomeException)
        {
            return 1;
        }
        return 0;
    }

    public virtual void GetFiles()
    {
        //...
    }
}

[Test]
public void FooTest()
{
    var fooUnderTest = new Mock<Foo>();
    fooUnderTest.CallBase = true;
    fooUnderTest.Setup(f => f.GetFiles()).Throws(new SomeException());
    var result = fooUnderTest.Object.Execute();
    Assert.AreEqual(1, result);
}