简体   繁体   English

如何使用Rhino模拟仅模拟测试对象中的一个值?

[英]How can I use Rhino mocks to mock just one value in a test object?

Been making some changes to our code, and now I need to re-factor some unit tests to make sure they're compatible with the new code. 正在对我们的代码进行一些更改,现在我需要重构一些单元测试,以确保它们与新代码兼容。 I've come up against a problem. 我遇到了一个问题。 In this: 在此:

            ChannelLoad loader = new ChannelLoad(_customerDbMock, _bulkCopyMock);
            loader.Execute(taskId);

The "loader" object is now trying to connect to another object in order to get a string value whereas before the string was returned automatically. 现在,“加载程序”对象正在尝试连接到另一个对象,以获取字符串值,而在自动返回字符串之前。 So the obvious solution is to mock that object to return a suitable value for the test. 因此,显而易见的解决方案是模拟该对象以返回适合测试的值。 However for various reasons I can't easily do this. 但是由于种种原因,我不能轻易做到这一点。

Ideally what I'd like to be able to do is to get a "real" (ie as specified in code) loader object that performs a "real" Execute method but which has a "mock" value for that particular string. 理想情况下,我希望能够执行的操作是获取一个“真实”(即,如代码中所指定)的加载程序对象,该对象执行“真实” Execute方法,但对于该特定字符串具有“模拟”值。 But I'm really not sure how to do this - even if it's possible - with Rhino Mocks. 但是我真的不确定如何使用Rhino Mocks做到这一点-即使有可能。 The string property in question isn't abstract or anything - it's protected and it's actually read-only. 有问题的字符串属性不是抽象的或任何东西,它是受保护的,实际上是只读的。 This is how it looks inside "loader": 这是“加载程序”内部的外观:

    protected string DbConnectionString
    {
        get
        {
            return _Service.GetLocalDatabase().GetConnectionString(_Service);
        }
    }

And the problem is that for the test environment "GetLocalDatabase" returns nothing. 问题是对于测试环境“ GetLocalDatabase”什么也不返回。

Anyone help me out here? 有人帮我吗? Is there a way I can mock this up using Rhino Mocks or is my only option to refactor the code to make it not rely on an external object? 有没有办法我可以使用Rhino Mocks进行模拟,还是我唯一的选择来重构代码以使其不依赖外部对象? If the latter, pointers would also be helpful. 如果是后者,则指针也将有所帮助。

Cheers, Matt 干杯,马特

Two other options if you don't want to inject _Service: 如果您不想注入_Service,则还有两个选择:

Create a class that inherits from ChannelLoad (call it "TestableChannelLoader" or something) and 创建一个从ChannelLoad继承的类(将其称为“ TestableChannelLoader”或诸如此类),然后

  1. overwrite the DbConnectionString-Property or 覆盖DbConnectionString-Property或

  2. extract a method "GetConnectionString" that you can override in your new class and call it in the DbConnectionString-Property 提取可以在新类中覆盖的方法“ GetConnectionString”,然后在DbConnectionString-Property中调用它

I see that loader has dependency to _Service. 我看到加载程序具有对_Service的依赖。 So, you need to inject mock of this dependency to loader in order to change DbConnectionString property behavior. 因此,您需要将此依赖关系的模拟注入到加载器,以更改DbConnectionString属性的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM