您是否使用 TestInitialize 或测试类构造函数来准备每个测试?为什么? [英] Do you use TestInitialize or the test class constructor to prepare each test? and why?

查看:33
本文介绍了您是否使用 TestInitialize 或测试类构造函数来准备每个测试?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是关于使用 MSTest 在 Visual Studio 中进行单元测试的(这很重要,因为 MSTest 的 执行顺序).标记为 [TestInitialize] 的方法和测试类构造函数都将在每个测试方法之前运行.

This question regards unit testing in Visual Studio using MSTest (this is important, because of MSTest's execution order). Both the method marked [TestInitialize] and the test class constructor will run before each test method.

那么,问题是,您在每个领域都倾向于做什么?您是否避免在其中进行某些活动?你的理由是什么:风格、技术、迷信?

So, the question is, what do you tend to do in each of these areas? Do you avoid performing certain activities in either? What is your reason: style, technical, superstition?

推荐答案

构造函数只是语言提供的结构.每个测试框架似乎都有自己受控的生命周期初始化".您可能只会在使用构造函数来改变本地变量时遇到麻烦.

The constructor is just a structure provided by the language. Every test framework seems has its own controlled lifecycle "initialize". You'll probably only get into trouble using the constructor to mutate your locals.

MSTest:您会为每个 TestMethod 获得一个全新的测试类实例.这可能是唯一可以在构造函数、初始值设定项或测试方法中改变本地变量而不影响其他测试方法的情况.

MSTest: You get an entire new instance of the test class for every TestMethod. This might be the only case where it's ok to mutate your locals in the constructor, initializer, or test method and not affect the other test methods.

public class TestsForWhatever
{
    public TestsForWhatever()
    {
        // You get one of these per test method, yay!
    }

    [TestInitialize] 
    public void Initialize() 
    {
        // and one of these too! 
    }

    [TestMethod]
    public void AssertItDoesSomething() { }

    [TestMethod]
    public void AssertItDoesSomethingElse() { }
}

MSpec:对于所有断言(It),您只会得到一个EstablishBecause.所以,不要在你的断言中改变你的本地人.并且不要依赖于基础上下文中局部变量的变化(如果你使用它们).

MSpec: You only get one Establish and Because for all your assertions (It). So, don't mutate your locals in your assertions. And don't depend on mutations of locals in base contexts (if you use them).

[Subject(typeof(Whatever))]
public class When_doing_whatever
{
    Establish context = () => 
    { 
        // one of these for all your Its
    };

    Because of = () => _subject.DoWhatever();

    It should_do_something;
    It should_do_something_else;
}

这篇关于您是否使用 TestInitialize 或测试类构造函数来准备每个测试?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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