(无头)asp.net mvc/webapi的集成测试框架5

cs0*_*815 7 asp.net-mvc integration-testing specflow asp.net-web-api asp.net-mvc-5

我目前正在研究(理想情况下无头)asp.net mvc 5的集成测试框架(可能与同一项目中的webapi).我知道这两个:

还有其他人吗?我对任何与specflow配合良好的框架特别感兴趣.

fou*_*ght 3

我今天成功地将 SpecsFor.Mvc 与 SpecFlow 集成。它太酷了。

这里有一组类,可以帮助您开始将 SpecsFor.Mvc 与 SpecFlow 集成。当然,这些可以更好地抽象和扩展;但至少,这就是您所需要的:

namespace SpecsForMvc.SpecFlowIntegration
{
    using Microsoft.VisualStudio.TestingTools.UnitTesting;
    using SpecsFor.Mvc;
    using TechTalk.SpecFlow;

    [Binding]
    public class SpecsForMvcSpecFlowHooks
    {
        private static SpecsForIntegrationHost integrationHost;

        /// <summary>
        /// <p>
        /// This hook runs at the end of the entire test run.
        /// It's analogous to an MSTest method decorated with the
        /// <see cref="Microsoft.VisualStudio.TestingTools.UnitTesting.AssemblyCleanupAttribute" />
        /// attribute.
        /// </p>
        /// <p>
        /// NOTE: Not all test runners have the notion of a test run cleanup.
        /// If using MSTest, this probably gets run in a method decorated with
        /// the attribute mentioned above. For other test runners, this method
        /// may not execute until the test DLL is unloaded. YMMV.
        /// </p>
        /// </summary>
        [AfterTestRun]
        public void CleanUpTestRun()
        {
            integrationHost.Shutdown();
        }

        /// <summary>
        /// <p>
        /// This hook runs at the beginning of an entire test run.
        /// It's equivalent to an MSTest method decorated with the
        /// <see cref="Microsoft.VisualStudio.TestTools.UnitTesting.AssemblyInitializeAttribute />
        /// attribute.
        /// </p>
        /// <p>
        /// NOTE: Not all test runners have a notion of an assembly
        /// initializer or test run initializer, YMMV.
        /// </p>
        /// </summary>
        [BeforeTestRun]
        public static void InitializeTestRun()
        {
            var config = new SpecsForMvcConfig();

            config.UseIISExpress()
                .With(Project.Named("Your Project Name Here"))
                .ApplyWebConfigTransformForConfig("Debug");

            config.BuildRoutesUsing(r => RouteConfig.RegisterRoutes(r));

            // If you want to be authenticated for each request, 
            // implement IHandleAuthentication
            config.AuthenticateBeforeEachTestUsing<SampleAuthenticator>();

            // I originally tried to use Chrome, but the Selenium 
            // Chrome WebDriver, but it must be out of date because 
            // Chrome gave me an error and the tests didn't run (NOTE: 
            // I used the latest Selenium NuGet package as of
            // 23-08-2014). However, Firefox worked fine, so I used that.
            config.UseBrowser(BrowserDriver.Firefox);

            integrationHost = new SpecsForMvcIntegrationHost(config);
            integrationHost.Start();
        }

        /// <summary>
        /// This hook runs once before any of the SpecFlow feature's
        /// scenarios are run and stores a <see cref="SpecsFor.Mvc.MvcWebApp />
        /// instance in the <see cref="TechTalk.SpecFlow.FeatureContext" />
        /// for the feature.
        /// </summary>
        [BeforeFeature]
        public static void CreateFeatureMvcWebApp()
        {
            MvcWebApp theApp;
            if (!FeatureContext.Current.TryGetValue<MvcWebApp>(out theApp))
                FeatureContext.Current.Set<MvcWebApp>(new MvcWebApp());
        }
    }

    public class SpecsForMvcStepDefinitionBase
    {
        /// <summary>
        /// Gets the instance of the <see cref="SpecsFor.Mvc.MvcWebApp" />
        /// object stored in the <see cref="TechTalk.SpecFlow.FeatureContext" />
        /// for the current feature.
        /// </summary>
        public static MvcWebApp WebApp
        {
            get { return FeatureContext.Current.Get<MvcWebApp>(); }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,假设您有一个如下所示的 SpecFlow 功能文件(这是部分文件):

Feature: Login
    As a user of the website
    I want to be able to log on the the site
    in order to use the features available to site members.

# For the site I'm currently working with, even though it's MVC, it's more
# of a WebAPI before there was WebAPI--so the controllers accept JSON and return
# JsonResult objects--so that's what you're going to see.
Scenario: Using a valid username and password logs me on to the site
    Given the valid username 'somebody@somewhere.com'
    And the password 'my_super_secure_password'
    When the username and password are submitted to the login form
    Then the website will return a result
    And it will contain an authentication token
    And it will not contain any exception record.
Run Code Online (Sandbox Code Playgroud)

现在是上述场景的步骤:

using Newtonsoft.Json;
using OpenQA.Selenium;
using MyWebSite.Controllers;
using Should;
using TechTalk.SpecFlow;

[Binding]
public class LoginSteps : SpecsForMvcStepDefinitionBase
{
    // The base class gets me the WebApp property that allows easy
    // access to the SpecsFor.Mvc.MvcWebApp object that drives a web browser
    // via Selenium.

    private string _username;
    private string _password;
    private string _portalSessionId;
    private ServiceResponse<LoginSummary> _loginResponse;

    [Given(@"the valid username '(.*)'")]
    [Given(@"the invalid username '(.*)'")]
    public void GivenAUsername(string username)
    {
        _username = username;
    }

    [Given(@"the valid password '(.*)'")]
    [Given(@"the invalid password '(.*)'")]
    public void GivenAPassword(string password)
    {
        _password = password;
    }

    [When(@"the username and password are submitted to the " +
          @"LoginUser action method of the UserController")]
    public void WhenTheUsernameAndPasswordAreSubmitted()
    {
        WebApp.NavigateTo<UserController>(
            c => c.LoginUser(_username, _password)
        );
    }

    [Then(@"the UserController will reply with a LoginSummary")]
    public void ThenTheUserControllerWillReplyWithALoginSummary()
    {
        _loginResponse = 
            JsonConvert.DeserializeObject<ServiceResponse<LoginSummary>>(
                WebApp.Browser.FindElement(By.TagName("pre")).Text
        );
    }

    [Then(@"it will contain an authentication token")]
    public void ThenItWillContainAnAuthenticationToken()
    {
        _loginSummary.Results.Count.ShouldBeGreaterThan(0);
        _loginSummary.Results[0].AuthenticationToken.ShouldNotBeEmpty();
    }

    [Then(@"it will not contain an exception record")]
    public void THenItWillNotContainAnExceptionRecord()
    {
        _loginSummary.Exception.ShouldBeNull();
    }
}
Run Code Online (Sandbox Code Playgroud)

很酷。

BeforeTestRun关于和修饰的方法AfterTestRun,我在下面的博文中找到了代码注释中提到的信息:Advanced SpecFlow:Using Hooks to Run Extra Automation Code

当然,如果您要测试演示文稿布局,您可能仍然希望构造遵循页面对象模式的类。正如我在代码注释中所述,我正在为早于 WebAPI 的特定应用程序编写集成测试,但其功能类似于 WebAPI,但使用 ASP.Net MVC。我们只是还没有正式将其移植到 WebAPI。