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

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

问题描述

这个问题涉及Visual Studio中使用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 :您只能获得一个建立因为用于所有的断言( It )。所以,不要在你的断言中改变你的本地化。并且不依赖于基础上下文中的局部变异(如果你使用它们)。

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天全站免登陆