在C#单元测试私有方法 [英] Unit testing private methods in C#

查看:263
本文介绍了在C#单元测试私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Visual Studio中允许私有方法的单元测试通过自动生成的访问器类。我写了成功编译一个私有方法的测试,但它在运行时失败。在code和试验的相当小的版本是:

Visual Studio allows unit testing of private methods via an automatically generated accessor class. I have written a test of a private method that compiles successfully, but it fails at runtime. A fairly minimal version of the code and the test is:

//in project MyProj
class TypeA
{
    private List<TypeB> myList = new List<TypeB>();

    private class TypeB
    {
        public TypeB()
        {
        }
    }

    public TypeA()
    {
    }

    private void MyFunc()
    {
        //processing of myList that changes state of instance
    }
}    

//in project TestMyProj           
public void MyFuncTest()
{
    TypeA_Accessor target = new TypeA_Accessor();
    //following line is the one that throws exception
    target.myList.Add(new TypeA_Accessor.TypeB());
    target.MyFunc();

    //check changed state of target
}

运行时错误是:

Object of type System.Collections.Generic.List`1[MyProj.TypeA.TypeA_Accessor+TypeB]' cannot be converted to type 'System.Collections.Generic.List`1[MyProj.TypeA.TypeA+TypeB]'.

根据智能感知 - 因此我猜编译器 - 目标类型TypeA_Accessor的。但在运行时它的类型是类型A的,因此列表中添加失败。

According to intellisense - and hence I guess the compiler - target is of type TypeA_Accessor. But at runtime it is of type TypeA, and hence the list add fails.

有没有什么办法可以阻止这种错误?或者,也许更容易,难道其他人有什么其他方面的建议(我predict也许不测试私有方法和没有单元测试操作对象的状态)。

Is there any way I can stop this error? Or, perhaps more likely, what other advice do other people have (I predict maybe "don't test private methods" and "don't have unit tests manipulate the state of objects").

推荐答案

是的,不要测试私有方法....单元测试的想法是通过其公共API来测试单元。

Yes, don't Test private methods.... The idea of a unit test is to test the unit by its public 'API'.

如果你发现你需要测试大量的私人行为,很有可能你有一个新的类隐藏你想测试,提取它和它的公共接口测试类中。

If you are finding you need to test a lot of private behaviour, most likely you have a new 'class' hiding within the class you are trying to test, extract it and test it by its public interface.

咨询/思维工具的一个棋子.....有一个想法,没有一种方法应该永远是私有的。这意味着所有方法应该活对象的公共接口上....如果你觉得你需要使它私有的,它极有可能生活在另一个对象。

One piece of advice / Thinking tool..... There is an idea that no method should ever be private. Meaning all methods should live on a public interface of an object.... if you feel you need to make it private, it most likely lives on another object.

这忠告并没有完全在实践中锻炼,但其大多是很好的意见,并经常将人推向物体分解成更小的物体。

This piece of advice doesn't quite work out in practice, but its mostly good advice, and often it will push people to decompose their objects into smaller objects.

这篇关于在C#单元测试私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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