我可以通过反射为Castle.Proxy对象属性赋值吗?

时间:2012-08-21 16:56:37

标签: .net vb.net reflection rhino-mocks castle

我有一个控制器测试库,我用它来处理测试中的大量冗余代码。在内部,它采用通用TDataSource参数,该参数应该是首先包含EF代码IDbSet的接口。在运行时,测试基础使用RhinoMocks _MockDataSource = MockRepository.GenerateMock(Of TDataSource)()构建模拟TDataSource。然后我使用反射来获取接口的所有IDbSet属性并为它们分配模拟数据库集。 (注意:这适用于虚拟类,只是接口不起作用)。

当我尝试通过调用IDbSet(Of TEntity)设置其中一个propertyInfo.SetValue(dataSource, mockDbSet, Nothing)属性的值时,它不会设置实际值。没有例外,它只是不起作用。我假设这是因为对象dataSource实际上不是类型指定的TDataSource,而是Castle.Proxies.IFakeDataSourceForTestingProxyf53f1730dba4492f8cafb9c731133d32,它以某种方式拦截了我对SetValue的调用。我该如何解决这个问题呢?

以下失败方法的完整代码:

    Protected Sub InjectTestData(ParamArray data() As IEnumerable)
        Dim dataSourceType As Type = GetType(TDataSource)
        Dim dataSourceProperties() As PropertyInfo = dataSourceType.GetProperties(BindingFlags.Public Or BindingFlags.Instance)

        'match up supplied data and required data sets
        For i As Integer = LBound(data) To UBound(data) Step 1
            Dim [set] As IEnumerable = data(i)
            Dim setType As Type = [set].GetType()
            If Not setType.IsGenericType Then
                Throw New ArgumentException(String.Format("Parameter {0} of the data array was not a generic IEnumerable, could not add to any IDbSet.", i))
            End If

            Dim modelType As Type = setType.GetGenericArguments(0)
            Dim dbSetType As Type = GetType(IDbSet(Of )).MakeGenericType({modelType})

            Dim foundDbSet As Boolean
            For Each [property] As PropertyInfo In dataSourceProperties
                If dbSetType.IsAssignableFrom([property].PropertyType) Then
                    Dim fakeDbSet As Object = CreateFakeDbSet(modelType, [set])
                    [property].SetValue(_MockDataSource, fakeDbSet, Nothing)
                    foundDbSet = True
                End If
            Next
            If Not foundDbSet Then Throw New ArgumentException(String.Format("Could not find an IDbSet(Of {0}) property on {1} to match parameter {2}", modelType.Name, dataSourceType.Name, i))
        Next

        'add empty lists to any data sets which are still null
        For Each [property] As PropertyInfo In dataSourceProperties
            If [property].GetValue(_MockDataSource, Nothing) Is Nothing Then
                Dim modelType As Type = [property].PropertyType.GetGenericArguments(0)
                Dim fakeDbSet As Object = CreateFakeDbSet(modelType)
                [property].SetValue(_MockDataSource, fakeDbSet, Nothing)
            End If
        Next
    End Sub

0 个答案:

没有答案