使用 HttpCurrentContext 的单元/集成测试代码

发布于 2024-07-18 18:52:34 字数 909 浏览 3 评论 0原文

尝试让 Nunit 在 ASP.Net 中工作。

问题是,我正在测试一个自定义控件 - 它引用全局资源。

当我尝试对其进行单元测试时,

/// </summary>
        [Test]
        public void TestSetAndGetNumber()
        {
            PhoneNumber phone = new PhoneNumber(PhoneNumber.NumberType.Business, "", true, "");
            string expectedString = "1-800-Goat-Phone";
            string resultString = "1-800-Goat-Phone";
            resultString = phone.Value = resultString;
            Assert.AreEqual(expectedString, resultString, "GetNumberMatch method returned unexpected result.");
            Assert.Fail("Create or modify test(s).");
        }

我会收到“无法加载 App_GlobalResources”。

试图弄清楚我是否应该尝试模拟 HttpContext 使用 You've Been Haacked 博客文章,但没有人验证这是可行的。

Trying to get Nunit working in ASP.Net.

The problem is, I'm testing a custom control - which references a Global Resource.

When I try to unit test it

/// </summary>
        [Test]
        public void TestSetAndGetNumber()
        {
            PhoneNumber phone = new PhoneNumber(PhoneNumber.NumberType.Business, "", true, "");
            string expectedString = "1-800-Goat-Phone";
            string resultString = "1-800-Goat-Phone";
            resultString = phone.Value = resultString;
            Assert.AreEqual(expectedString, resultString, "GetNumberMatch method returned unexpected result.");
            Assert.Fail("Create or modify test(s).");
        }

I will get "cannot load App_GlobalResources".

Trying to figure out if maybe I should attempt to simulate HttpContext Using You've been Haacked blog post but nobody has verified this is do-able.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瑶笙 2024-07-25 18:52:34

这是一个典型的场景,您应该以正确的方式设置您的类以使其可测试。 如果您有外部依赖项(对全局资源的引用),那么您应该将其设为抽象,以便您可以模拟它。

我建议你看一下这本,它解释了如何设计你的类更具可测试性。 或者,您可以从 moq 下载示例。 设置单元测试主要涉及以更松散耦合的方式设计类,因此您可以有效地测试它,而无需与数据库/文件系统/其他资源交互。

This is a typical scenario that you should set up your class in a right way to be testable. If you have external dependency (references to a Global Resource), then you should make it an abstract, so you can mock it.

I suggest you take a look at this book, and it explains how to design your class be more testable. Alternative, you can download examples from moq. Set up unit testing is a lot about designing your class in more loose coupled way, so you can effectively test it without interaction with DB/File system/other resource.

寄居者 2024-07-25 18:52:34

这听起来可能很油腔滑调,但是您不能重新设计 PhoneNumber 类以使其可测试吗?

如果您想使用单元测试,这似乎是正确的选择。
如果您无法修改 PhoneNumber 类,那么测试它还有什么意义呢?

This may sound glib, but can't you just redesign the PhoneNumber class so that it is testable?

If you want to use unit testing, this would seem to be the way to go.
If you can't modify the PhoneNumber class, what's the point in testing it?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文