gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:50:47 26 4
gpt4 key购买 nike

我目前正在研究(最好是 headless 的)asp.net mvc 5 集成测试框架(可能与同一项目中的 webapi 一起)。我知道这 2 点:

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

最佳答案

我今天成功地将 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>(); }
}
}
}

然后,假设您有一个如下所示的 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.

现在是上述场景的步骤:

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();
}
}

非常酷。

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

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

关于asp.net-mvc - asp.net mvc/webapi 5 的( headless )集成测试框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25033371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com