在VS测试项目中维护单元测试方法之间的上下文 [英] Maintain context between unit test methods in VS Test Project

查看:82
本文介绍了在VS测试项目中维护单元测试方法之间的上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要按顺序运行以下单元测试:

I want to run the following unit tests, in order:

  1. 使用名称,密码等随机数创建新客户.
  2. 检索刚刚创建的客户,并断言其属性包含相同的随机数
  3. 使用相同的用户名随机数在同一用户上调用ForgotPassword函数

很明显,我需要一次生成一个随机数,并在3种测试方法中共享它.
我似乎找不到办法.

As seen clearly, I need to generate a random number once, and share it across 3 test methods.
I cannot seem to find a way to do that.

  • 我考虑过使用TestContext对象,但这是为每个实例创建的.
  • 我尝试使用ClassInitialize()方法无济于事,因为它是静态的,因此其他方法无法访问该数字.

有什么想法可以实现我的目标吗?

Any idea how to achieve my goal?

推荐答案

能否将共享数据放入静态变量中?

Can you just place your shared data into static variables?

像这样简单的事情

    private static string testValue = "something";

    [TestMethod]
    public void TestMethod1()
    {
        Assert.AreEqual(testValue, "something");
        testValue = "something2";
    }

    [TestMethod]
    public void TestMethod2()
    {
        Assert.AreEqual(testValue, "something2");
        testValue = "something3";
    }

    [TestMethod]
    public void TestMethod3()
    {
        Assert.AreEqual(testValue, "something3");
    }

更新:总结关于此问题的其他评论,我认为每个人都完全同意保持单元测试之间的状态是一个坏主意.我的答案只是执行此操作的一种方法(如有必要).正如我在另一条评论中提到的那样,过去我必须这样做,但对于单元测试则不必.在不一定要模拟对象或隔离应用程序各部分的集成/回归测试之间保持状态有时是有益/必要的.作为软件测试人员,您并不总是具有影响力/能力/权限来立即重构或重新构造应用程序以使其最适合此测试.

Update: To summarize other comments on this question, I think that everyone is in complete agreement that keeping state between unit tests is a bad idea. My answer was simply a way to do this, if necessary. As I mentioned in another comment, I have had to do this in the past, but not for unit tests. It is sometimes beneficial/necessary to keep state between integration/regression tests where you don't necessarily want to mock objects or isolate parts of the application. As a software tester, you do not always have the influence/ability/permission to immediately refactor or rearchitect an application to be optimal for this testing.

这篇关于在VS测试项目中维护单元测试方法之间的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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