【问题标题】:How do I run setup and teardown code with each test in MSpec?如何在 MSpec 中的每个测试中运行设置和拆卸代码?
【发布时间】:2011-05-06 02:25:34
【问题描述】:

我有用于设置和拆除 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;
}

【问题讨论】:

    标签: .net nhibernate mspec


    【解决方案1】:

    有一个使用 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);
            }
        }
    

    【讨论】:

    • @Alistair:这不是为 each 测试执行的,而是 once 为所有测试执行的。
    • 这个答案可能不是 OP 想要的! AssemblyContext 方法对所有测试执行一次,而 NUnit 的 Setup 和 TearDown 方法对每个测试执行一次! MSpec 没有您要查找的概念。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 2018-07-11
    • 2017-05-02
    相关资源
    最近更新 更多