【问题标题】:When using a mocking framework and MSPEC where do you set your stubs使用模拟框架和 MSPEC 时,您在哪里设置存根
【发布时间】:2010-03-29 19:26:37
【问题描述】:

我对使用 MSpec 比较陌生,随着我编写越来越多的测试,很明显可以减少重复,您通常必须根据 Rob Conery's article 为您的设置使用基类

我很高兴使用 AssertWasCalled 方法来验证我的期望,但是您在哪里设置存根的返回值,我发现在注入我的依赖项的基类中设置上下文很有用,但是(我认为)意味着我需要在因为感觉错误的委托中设置我的存根。

我还缺少更好的方法吗?

【问题讨论】:

    标签: unit-testing rhino-mocks bdd mspec


    【解决方案1】:

    存根的初始化/设置属于排列阶段。安排阶段用于在您运行之前让系统进入已知状态。

    在 MSpec 中,排列阶段在Establish 字段中执行。例如:

    public class When_the_temperature_threshold_is_reached
    {
        static ITemperatureSensor Sensor;
        static Threshold Threshold;
    
        Establish context = () =>
            {
                Sensor = MockRepository.GenerateStub<ITemperatureSensor>();
                Sensor
                    .Stub(x => x.GetTemperature())
                    .Return(42);
    
                Threshold = new Threshold(Sensor);
            };
    
        Because of = () => Reached = Threshold.IsReached(40);
    
        It should_report_that_the_threshold_was_reached =
            () => Reached.ShouldBeTrue();
    }
    

    当您使用这种ITemperatureSensor 编写更多测试时,您应该提取一个执行复杂或重复设置的基类。

    public abstract class TemperatureSpecs
    {
        protected static ITemperatureSensor CreateSensorAlwaysReporting(int temperature)
        {
            var sensor = MockRepository.GenerateStub<ITemperatureSensor>();
            sensor
                .Stub(x => x.GetTemperature())
                .Return(temperature);
    
            return sensor;
        }
    }
    
    public class When_the_temperature_threshold_is_reached : TemperatureSpecs
    {
        // Everything else cut for brevity.
        Establish context = () =>
            {
                Sensor = CreateSensorAlwaysReporting(42);
    
                Threshold = new Threshold(Sensor);
            };
    }
    

    这为您提供了一个优势,即您可以从上下文本身影响存根的返回值:您可以通过将尽可能多的信息保留在上下文中来做到这一点,并为基类中的“设置”方法提供一个好名字.

    没有必要在Because 中指定或期望任何与存根相关的内容。当Because运行时,您的系统应该处于无需进一步准备即可运行的状态。

    【讨论】:

    • 谢谢亚历山大,这很有意义。我希望避免在每个派生类中设置上下文,但我想那是不可能的
    • Because 字段在您构建类层次结构时以正确的顺序执行。你可以完美地做到这一点,但这不是一个好习惯。请记住,您希望尽可能多地保留正在执行的上下文附近的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 2010-11-20
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多