我在 ASP.NET Core 项目中为 UrlHelper 编写了几个扩展方法。现在我想为他们编写单元测试。但是,我的许多扩展方法都利用了 UrlHelper 的方法(例如 Action),因此我需要将一个工作 UrlHelper 传递给参数this(或者一个工作 UrlHelper 来调用这些方法)。
如何实例化一个可用的 UrlHelper?我试过这个:
Mock<HttpContext> mockHTTPContext = new Mock<HttpContext>();
Microsoft.AspNetCore.Mvc.ActionContext actionContext = new Microsoft.AspNetCore.Mvc.ActionContext(
new DefaultHttpContext(),
new RouteData(),
new ActionDescriptor());
UrlHelper urlHelper = new UrlHelper(actionContext);
Guid theGUID = Guid.NewGuid();
Assert.AreEqual("/Admin/Users/Edit/" + theGUID.ToString(), UrlHelperExtensions.UserEditPage(urlHelper, theGUID));
Run Code Online (Sandbox Code Playgroud)
它Test method Test.Commons.Admin.UrlHelperTests.URLGeneration threw exception:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index因以下调用堆栈而崩溃 ( ):
at System.Collections.Generic.List`1.get_Item(Int32 index)
at …Run Code Online (Sandbox Code Playgroud) Visual Studio 2019 中的 MSTest v2 相对较新。该属性指示该方法应在每个测试之前TestInitialize运行。同样,指示该方法应在每次测试后运行。TestCleanup
[TestInitialize()]
public void Setup()
{
// This method will be called before each MSTest test method
}
[TestCleanup()]
public void Teardown()
{
// This method will be called after each MSTest test method has completed
}
Run Code Online (Sandbox Code Playgroud)
如果你的测试类有N个方法,上面的方法将运行N次。
有没有一种方法可以发出只运行一次的类似设置和拆卸的方法的信号?换句话说,对于所有 N 个测试的每次完整运行,每个方法将仅运行一次。
NUnit3 和 xUnit v2.4.0 是否有类似的机制?
我有以下方法,我想对其进行单元测试.可以对方法签名进行更改:
public void PrintNumber()
{
Enumerable.Range(1, 100).ToList().ForEach(x =>
{
if (x % 3 == 0 && x % 5 == 0)
Console.WriteLine("[35]");
else if (x % 3 == 0)
Console.WriteLine("[3]");
else if (x % 5 == 0)
Console.WriteLine("[5]");
else
Console.WriteLine(x.ToString());
});
}
Run Code Online (Sandbox Code Playgroud)
我有自己的解决方案,但我想知道我的版本是否最好.
谢谢!
我正在使用Selenium C#和MSTest的页面对象模式,我想声明我已经通过使用实际页面标题声明预期的页面标题来到达正确的页面.我有以下代码,但它不起作用:
框架:
public class MyAccountPage
{
public const string MyAccountPageTitle = "My Account";
public static bool IsAt()
{
return Driver.Instance.Title == MyAccountPageTitle;
}
Run Code Online (Sandbox Code Playgroud)
测试:
Assert.IsTrue(MyAccountPage.IsAt);
Run Code Online (Sandbox Code Playgroud) 我正在玩Visual Studio上的单元测试.
试着测试一个简单的电话
Assert.AreEqual(2, 1, 2);
Run Code Online (Sandbox Code Playgroud)
运行测试时,它说通过?不应该失败.
mstest ×5
c# ×4
unit-testing ×3
nunit ×2
asp.net-core ×1
assert ×1
fizzbuzz ×1
selenium ×1
xunit ×1