Pergunta

Estou usando o MSTEST no Visual Studio 2008. Como posso ter cada método de teste de unidade em uma determinada classe de teste agir como se fosse o primeiro teste a ser executado para que todo o estado global seja redefinido antes de executar cada teste? Não quero limpar explicitamente o mundo usando testinacionalização, classinitialize, AssemblyInitialize etc. por exemplo:

[TestClass]
public class MyClassTests
{
    [TestMethod]
    public void Test1()
    {
       // The "Instance" property creates a new instance of "SomeSingleton"
       // if it hasn't been created before.
       var i1 = SomeSingleton.Instance;
       ...
    }
    [TestMethod]
    public void Test2()
    {
       // When I select "Test1" and "Test2" to run, I'd like Test2
       // to have a new AppDomain feel so that the static variable inside
       // of "SomeSingleton" is reset (it was previously set in Test1) on
       // the call to ".Instance"
       var i2 = SomeSingleton.Instance;
       // some code
    }

Embora a pergunta semelhante Apareceu neste tópico, apenas esclareceu que os testes não são executados em paralelo. Sei que os testes são executados em série, mas não parece haver uma maneira de forçar explicitamente um novo aplicativo para cada método (ou algo equivalente a limpar todo o estado).

Idealmente, eu gostaria de especificar esse comportamento apenas para um pequeno subconjunto dos meus testes de unidade, para que não precise pagar a penalidade de uma nova criação de appdomain para testes que não se importam com o estado global (a grande maioria de meus testes).

Foi útil?

Solução

No final, escrevi um ajudante que usou AppDomain.CreateDomain e depois usei a reflexão para chamar o teste de unidade em um aplicativo diferente. Ele fornece o isolamento que eu precisava.

Esta postagem Nos fóruns do MSDN, mostra como lidar com a situação se você tiver apenas algumas estágias que precisam ser redefinidas. Isto menciona algumas opções (por exemplo, usando reflexão e Privatetype ).

Continuo recebendo mais idéias, especialmente se estou perdendo algo óbvio sobre o MSTEST.

Outras dicas

Add a helper in your tests that uses reflection to delete the singleton instance (you can add a reset method to the singleton as well, but I would be concerned about its use). Something like:

public static class SingletonHelper {
            public static void CleanDALFactory() 
            {
                    typeof(DalFactory)
                        .GetField("_instance",BindingFlags.Static | BindingFlags.NonPublic)
                        .SetValue(null, null);
            }
}

Call this in your TestInitialize method. [ I know this is "cleaning up the world", but you only have to write the method once in a helper per singleton, its very trivial and gives you explicit control ]

I think you are looking for the TestIntialize attribute and the TestCleanUp attribute. Here is an MSDN blog showing the execution orderlink text

We had a similar issue arise with our MSTests. We handled it by calling a function at the beginning and end of the specific tests that needed it.

We are storing a test expiration date in our app configuration. Three tests needed this date to fall into a specific range to determine the appropriate values. The way our application is set up, the configuration values would only be reset if there was not a value assigned in session. So, we created two new private static functions - one to explicitly set the configuration value to a specified date and one to clear that date from session after the test runs. In our three tests, we called these two functions. When the next test runs, the application sees an empty value for the date and refetches it from the configuration file.

I'm not sure if that's helpful, but that was how we worked around our similar issue.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top