示例#1
0
        private object CompileAndCreateTest(string fileName, Feature feature)
        {
            string       className       = Path.GetFileNameWithoutExtension(fileName);
            const string targetNamespace = "Target.Namespace";
            // the row test generation has to be set to false, because our verifications support the old style test generation only
            SpecFlowUnitTestConverter converter = new SpecFlowUnitTestConverter(new NUnitTestConverter(), new CodeDomHelper(CodeDomProviderLanguage.CSharp), true, false);
            var codeNamespace = converter.GenerateUnitTestFixture(feature, className, targetNamespace);
            var compileUnit   = new CodeCompileUnit();

            compileUnit.Namespaces.Add(codeNamespace);

            Dictionary <string, string> providerOptions = new Dictionary <string, string>();

            providerOptions["CompilerVersion"] = "v3.5";

            CSharpCodeProvider codeProvider = new CSharpCodeProvider(providerOptions);

            CompilerParameters compilerParameters = new CompilerParameters();

            compilerParameters.GenerateInMemory    = true;
            compilerParameters.TempFiles.KeepFiles = true;

            compilerParameters.ReferencedAssemblies.Add(
                TestFileHelper.GetAssemblyPath(typeof(GeneratedCodeAttribute))); //System
            compilerParameters.ReferencedAssemblies.Add(
                TestFileHelper.GetAssemblyPath(typeof(TestAttribute)));          //NUnit
            compilerParameters.ReferencedAssemblies.Add(
                TestFileHelper.GetAssemblyPath(typeof(ITestRunner)));            //TechTalk.SpecFlow

            var results = codeProvider.CompileAssemblyFromDom(compilerParameters, compileUnit);

            if (results.NativeCompilerReturnValue != 0)
            {
                throw new InvalidOperationException("Test cannot be compiled: " +
                                                    string.Join(Environment.NewLine, results.Errors.Cast <CompilerError>().Select(ce => ce.ToString()).ToArray()));
            }

            Type testType = results.CompiledAssembly.GetType(targetNamespace + "." + className, true);

            return(Activator.CreateInstance(testType));
        }