简体   繁体   English

从当前运行的单元测试中获取信息

[英]Getting info from currently running unit test

I have to find info about the currently running UnitTest from a helper class' static method. 我必须从助手类的静态方法中找到有关当前正在运行的UnitTest的信息。 The Idea is getting a unique key from each test. 这个主意是从每个测试中获得唯一的密钥。

I thought about using TestContext , not sure if it is possible. 我考虑过使用TestContext ,不确定是否可行。

Exemple 例子

[TestClass]
public void MyTestClass
{
    public TestContext TestContext { get; set; }

    [TestMethod]
    public void MyTestMethod()
    {
        TestContext.Properties.Add("MyKey", Guid.NewGuid());

        //Continue....
    }
}


public static class Foo
{

    public static Something GetSomething()
    {
        //Get the guid from test context.
        //Return something base on this key
    }

}

We are currently storing this key on the thread with Thread.SetData , but it is problematic if the tested code spawn multiple thread. 目前,我们正在使用Thread.SetData将密钥存储在线程中,但是如果测试的代码产生了多个线程,则会出现问题。 For each thread I need to get the same key for a given unit test. 对于每个线程,对于给定的单元测试,我需要获取相同的密钥。

Foo.GetSomething() is not called from the unittest itself. Foo.GetSomething()不是从单元测试本身调用的。 The code calling it is a mock injected by Unity. 调用它的代码是Unity注入的一个模拟。

Edit 编辑

I'll explain the context a little bit, because it seems to be confusing. 我将稍微解释一下上下文,因为这似乎令人困惑。

The object created via unity is entity framework's context. 通过统一创建的对象是实体框架的上下文。 When running unit tests, the context get its data in a structure that is created by Foo.GetSomething . 运行单元测试时,上下文将在Foo.GetSomething创建的结构中获取其数据。 Let's call it DataPersistance . 我们称之为DataPersistance

DataPersistance cannot be a singleton, because unit tests would impact each others. DataPersistance不能为单例,因为单元测试会相互影响。

We currently have one instance of DataPersistance per thread, witch is nice as long as the tested code is single threaded. 当前,每个线程有一个DataPersistance实例,只要测试的代码是单线程的, DataPersistance很好。

I want one instance of DataPersistance per unit test. 我需要每个单元测试一个DataPersistance实例。 If a could get an unique guid per test, I could resolve the instance for this test. 如果每个测试都能获得唯一的GUID,我可以为此测试解析该实例。

public static class Foo
{   
    public static Something GetSomething(Guid guid)
    {
        //Return something base on this key
        return new Something();
    } 
}

Test: 测试:

[TestClass]
public void MyTestClass
{
    public TestContext TestContext { get; set; }

    [TestMethod]
    public void MyTestMethod()
    {
        Guid guid = ...;
        Something something = Foo.GetSomething(guid);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM