是否使用TestInitialize或测试类的构造函数prepa

是否使用TestInitialize或测试类的构造函数prepa

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

问题描述

此问题使用MSTest的(这是因为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?

推荐答案

唉......我现在讨厌这个问题。构造函数只是由语言提供的结构。每一个测试框架似乎有自己的生命周期控制的初始化。你也许只会惹麻烦使用构造变异的当地人。

Ugh... I hate this question now. 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:您只有一次制定因为您所有的断言( )。所以,千万不要发生变异的当地人在你的断言。而且不依赖于在基础环境当地人突变(如果你使用它们)。

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或测试类的构造函数prepare每个测试?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:31