Moq是具有另一个moq的具体类的属性

时间:2016-12-06 14:23:58

标签: c# unit-testing moq

我试图创建一个具体类的模拟,并用另一个模拟器模拟其中一个属性。

import numpy as np
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
from bokeh.layouts import column
from bokeh.io import curdoc
from bokeh.models.widgets import Select


class AppData:

    def __init__(self, n):
        self.p_source = None
        self.c_source = None
        self.x = np.linspace(0, 10, 20)
        self.n = n
        self.ys = [np.sin(self.x) - i for i in range(self.n)]
        self.line = None
        self.patch = None

    def update_module(self, a, b):
        assert b - a == 5

        p_data = dict() if self.p_source is None else self.p_source.data
        c_data = dict() if self.c_source is None else self.c_source.data

        ys = [self.ys[j] for j in range(a, b)]
        if "x" not in c_data:
            c_data["x"] = self.x
            p_data["x"] = c_data["x"].tolist() + c_data["x"][::-1].tolist()

        n_r = len(ys[0])
        n_p = 2*n_r
        if "ys" not in p_data:
            p_data["ys"] = np.empty((n_p))

        p_data["ys"][:n_r] = ys[0]
        p_data["ys"][n_r:] = np.flipud(ys[-1])
        c_data["y"] = ys[2]
        if self.p_source is None:
            self.p_source = ColumnDataSource(data=p_data)
        else:
            self.p_source.data.update(p_data)
        if self.c_source is None:
            self.c_source = ColumnDataSource(data=c_data)
        else:
            self.c_source.data.update(c_data)
        if self.line is not None:
            print(max(self.line.data_source.data["y"]))
            print(max(self.patch.data_source.data["ys"]))  # The value changes, but the figure does not!

# initialize
app_data = AppData(10)
app_data.update_module(4, 4 + 5)
s1 = figure(width=500, plot_height=125, title=None, toolbar_location="above")
app_data.line = s1.line("x", "y", source=app_data.c_source)
app_data.patch = s1.patch("x", "ys", source=app_data.p_source, alpha=0.3, line_width=0)

select = Select(title="Case", options=[str(i) for i in range(5)], value="4")
def select_case(attrname, old, new):
    a = int(select.value)
    app_data.update_module(a, a + 5)

select.on_change('value', select_case)
layout = column(select, s1)
curdoc().add_root(layout)
curdoc().title = "Example of patches not being updated"

...测试

public class MyClass
{
  public virtual IAdapter Adapter {get; internal set;}
}

它抛出以下异常: System.ArgumentException:常量与定义的类型

不匹配

我该如何解决?

修改

我改变了设计,即便如此,它仍然会抛出相同的异常

var adapter = new Mock<IAdapter>();
adapter.Setup(a => a.WaitForDigit()).Returns(1);
var myClass = new Mock<MyClass>();
myClass.Setup(c => c.Adapter).Returns(adapter.Object); //throws exception

2 个答案:

答案 0 :(得分:2)

这看起来像是一个设计问题。如果你依赖另一个类,那么这个依赖不应该公开。见这里

Should injected dependencies be publicly accessible or private?

一旦包含了依赖项并且没有外部访问权限,就没有必要对这个依赖项进行moq。你的MyClass的moq方法就足够了。

答案 1 :(得分:1)

原来这与Moq无关。报告hereCastle.Core错误。

要解决此问题,我已经安装了Castle.Core v4.0 beta版。