如何对返回List<>的私有函数进行单元测试?私有类对象? [英] How do you unit test a private function that returns a List<> of private class objects?

查看:79
本文介绍了如何对返回List<>的私有函数进行单元测试?私有类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在类似于下面示例的代码中,单元测试必须通过A的私有访问器访问B和GetBs(),如示例单元测试中所示。但是,这不起作用,因为GetBs()返回List< B>并且运行时无法将其强制转换为List< A_Accessor.B>。我如何单元测试A.GetBs()?

公共类A
{
私人班级B
{
...
私人静态列表< B> GetBs()
{
...
}

... ...
}公共级别AUnitTest
{{br /> public void GetBsTest()
{
List< A_Accessor.B> = A_Accessor.GetBs();
}
}

In code similar to the example below, a unit test must access B and GetBs() through the private accessor for A, as shown in the example unit test.  However, this won't work, because GetBs() returns List<B> and the runtime fails to cast it to List<A_Accessor.B>.  How do I unit test A.GetBs()?

public class A
{
    private class B
    {
    ...
    }
   
    private static List<B> GetBs()
    {
    ...
    }
   
    ...
}
public class AUnitTest
{
    public void GetBsTest()
    {
        List<A_Accessor.B> = A_Accessor.GetBs();
    }
}

推荐答案

我认为这不会起作用。

我的一个大问题是,为什么要对私有方法进行单元测试?您通常希望测试您的公共功能,并且公共功能可能会使用您班级中的私有方法。

如果你想进行单元测试,但又不想在程序集之外使用方法,那么你可以标记内部并使用AssemblyInfo.cs中的InternalsVisibleTo属性来让你的测试程序集可以看到你的内部方法。
I don't think that is going to work.

My big question is why are you unit testing private methods?  you generally want to test your public functionality and that public functionality will likely use your private methods in your class. 

If you want to unit test but don't want the methods used outside of your assembly you can alwasy mark the internal and use the InternalsVisibleTo attribute in the AssemblyInfo.cs to give your test assembly visibility into your internal methods.


这篇关于如何对返回List&lt;&gt;的私有函数进行单元测试?私有类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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