Dot-Net

如何在 MSpec 中為每個測試執行設置和拆卸程式碼?

  • December 3, 2012

我有用於設置和拆除 NHibernate 的通用程式碼,我幾乎所有的測試都需要它。有沒有辦法將“需要所有測試”程式碼包含在一個地方,然後將其應用於所有測試?(即像 Nunit 的setupteardown方法)

[Subject("Accessing the TAE allocation page")]
public class when_a_request_to_the_tae_allocation_page_is_made
{
   Establish context = () => NHTestHelper.StartTest(); //need for all tests

   Because of = () => result = new AllocationController(true).Index();

   It should_display_the_page = () => result.ShouldBeAView();

   Cleanup nh = () => NHTestHelper.EndTest(); //need for all tests

   static ActionResult result;
}

有一個使用 IAssemblyContext 介面的類。您的規範類不繼承自此。

public class DataSpecificationBase : IAssemblyContext
   {
       public static Configuration configuration;

       void IAssemblyContext.OnAssemblyComplete()
       {

           NHibernateSession.CloseAllSessions();
           NHibernateSession.Reset();

       }

       void IAssemblyContext.OnAssemblyStart()
       {
           HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();

           string[] mappingAssemblies = RepositoryTestsHelper.GetMappingAssemblies();
           configuration = NHibernateSession.Init(new SimpleSessionStorage(),
                                                  mappingAssemblies,
                                                  new AutoPersistenceModelGenerator().Generate(),
                                                  "database.config");

           InitializeUserSession();            

           Console.WriteLine("OnAssemblyStart");
       }

       void InitializeUserSession()
       {
           ITWEntityRepo entityRepo = new TWEntityRepo();
           // TWEntity entity  = entityRepo.GetByUserName("1EB6472B-965B-41D5-8D77-3880D02FF518");
           TWEntity entity = entityRepo.GetByUserName("87BCA093-0B8C-4FDF-ABE8-1A843BA03608");

           UserSession.Instance().User = UserFactory.Create(entity);
       }
   }

引用自:https://stackoverflow.com/questions/5906174