【问题标题】:Why does a TestMethod has access to internal properties?为什么 TestMethod 可以访问内部属性?
【发布时间】:2015-08-06 19:58:17
【问题描述】:

我对测试非常陌生,我遇到了一个特定场景,其中测试项目的测试方法可以访问内部属性。这是否按设计工作,或者有人可以向我解释为什么会这样吗?

测试类的片段:

/// <summary>This class contains parameterized unit tests for NWatchSystemConfiguration</summary>
    [PexClass(typeof(NWatchSystemConfiguration))]
    [PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))]
    [PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)]
    [TestClass]
    public partial class NWatchSystemConfigurationTest
    {
        [TestMethod]
        public void CreateEncryptedPropertyTest()
        {
            const string propertyName = "createdEncryptedProperty";
            const string propertyValue = "testValue";

            const string expected = propertyValue;

            target.CreateProperty(propertyName, propertyValue, true); 

            var actual = target.AppSettings.Settings[propertyName].Value;  // AppSettings is an internal property

            Assert.IsNotNull(actual);
            Assert.AreEqual(expected, actual);
        }
    }

正在测试的类的片段:

public class NWatchSystemConfiguration : NWatchConfigurationBase
    {
        internal AppSettingsSection AppSettings;

        // Output emitted for brevity
    }

【问题讨论】:

  • 在 NWatchSystemConfiguration 类所在的程序集中搜索 InternalsVisibleTo 属性。测试程序集很可能已被标记为能够查看产品代码的内部结构。
  • 在测试的程序集中查找[assembly: InternalsVisibleTo("TestAssemblyName")] 属性。
  • 你们是对的。请回答,以便我标记为答案!
  • 如果它们位于两个不同的程序集中,您将无法从 NWatchSystemConfiguration 访问 AppSettings。也许您已将 [assembly: InternalsVisibleTo("TestAssemblyName")] 添加到您的 assemblyinfo。

标签: c# unit-testing mstest pex


【解决方案1】:

如果您没有在 AssembnlyInfo.cs 中使用 InternalsVisibleTo attribute,您将无法访问它。 看看你的 assemblyinfo.cs。我想你会在那里找到类似[assembly: InternalsVisibleTo("TestAssemblyName")] 的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    相关资源
    最近更新 更多