在没有反射的情况下模拟受保护的成员 [英] Mocking a protected member without reflection

查看:49
本文介绍了在没有反射的情况下模拟受保护的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个成员从资源文件中返回一个字符串,我想对此进行单元测试,因为有很多并且它们可能会被错误地更改.我知道这可以使用反射来实现,但我被要求以不使用反射的方式来实现.

I have a member that returns a string from a resource file, and I want to unit test this, as there's quite a few and they could be changed by mistake. I understand that this is achievable using reflection but I've been asked to do it in a way that doesn't use reflection.

成员长这样;

protected override string StringOne
    {
        get
        {
            return Resources.String;
        }
    }

我了解可以为会员设置退货;

I understand that setting up the return for the member can be done as;

 mock.Protected()
            .Setup<string>("StringOne")
            .Returns("Returned string.");

和 .verifiable() 可以添加到此末尾.但是我找不到如何验证是否正在返回字符串.或者我认为通过使用 .verifiable() 设置它, .returns("") 值是预期的,并调用

and .verifiable() can be added to the end of this. But I can't find how to verify that a string is being returned. Or am I right in thinking that the by setting this up with .verifiable(), that the .returns("") value is the expected, and calling

mock.Verify();

将验证成员是否返回了正确的字符串,或者只是在测试期间的某个时刻调用了该成员?

will verifying that the member has returned the correct string or simply that the member was called at some point during the test?

推荐答案

您在此处遇到的问题是您正在尝试测试无法从课堂外部获得的内容.测试应该只测试你的类的公共接口,这样只要公共行为保持不变,类的内部就可以改变.

The problem that you are encountering here is that you are trying to test something that isn't available from outside of the class. Tests should only test the public interface of your class so that the internals of the class can change as long as the public behaviour remains the same.

在这种情况下,我认为您有两个选择:

In this instance, I think that you have two options:

一个是将这段代码移动到另一个类中,这些属性是公共的,这样你的测试就可以调用新的公共属性并检查返回值,需要使用该属性值的类可以调用你的新类.无论如何,继承通常都不是共享代码的好方法(解释此概念的博客文章:http://www.blinkingcaret.com/2016/04/13/composition-superior-inheritance/)

One is to move this code into another class with these properties being public, that way your test can just call the new public properties and check the return and the classes that need to use the value of the property can call your new class. Inheritance is generally not a great way of sharing code anyway (a blog post explaining this concept: http://www.blinkingcaret.com/2016/04/13/composition-superior-inheritance/)

另一个是测试这些属性最终被用在什么地方.例如,如果您有一些方法将 StringOne 的值传递给另一个模拟类,您可以检查是否传递了正确的值,或者它是否最终在文件路径中使用,您应该测试文件路径最终是否正确等

The other is to test where these properties end up being used. For example, if you have some method that passes the value of StringOne into another mocked class, you can check that the correct value is passed through or if it ends up being used in a file path, you should test that the file path ends up being correct etc

这篇关于在没有反射的情况下模拟受保护的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆