对依赖于请求的 URL 参数的控制器属性进行单元测试 (ASP.NET MVC)
我基本上有一个控制器基类,它通过验证网址中的令牌来处理身份验证,例如:
http://example/Home/Index 将未经身份验证
http://example/Home/Index?token=293029420932422823 将进行身份验证
我想为此编写单元测试,但不确定如何进行。我有:
[TestMethod]
public void NonsecureConnection()
{
var controller = new EONSecureController();
Assert.IsTrue(string.IsNullOrEmpty(controller.EONToken));
Assert.IsTrue(controller.tokenMode == EONSecureController.EONTokenModeEnum.None);
}
很容易。测试安全连接是我陷入困境的地方。
[TestMethod]
public void SecureConnection()
{
var controller = new EONSecureController();
// What to put here?
Assert.IsTrue(!string.IsNullOrEmpty(controller.EONToken));
Assert.IsTrue(controller.tokenMode==EONSecureController.EONTokenModeEnum.Client);
}
我尝试过各种方法,例如:
controller.RequestContext.RouteData.Values[Config.RawTokenName] = "12312342123";
controller.Request = new System.Web.HttpRequest("", "http://localhost/example", "token=2342342");
controller.Request.RawUrl = "http://localhost/example?token=234234234234234";
由于各种原因,这些方法都不起作用。是否有一种“正确”的方法来处理依赖于所请求的特定 URL 的控制器的测试?
我看到一些暗示使用 Moq 的内容,但我无法完全连接起来......
注意: 请不要提出“不要那样进行身份验证,您应该{etc etc etc}”之类的答案。该示例被有意简化,以保持对这里主要问题的关注,即如何开发单元测试。
I basically have a controller base class which handles authentication by validating a token in the url, eg:
http://example/Home/Index would be unauthenticated
http://example/Home/Index?token=293029420932422823 would be authenticated
I want to write unit tests for this but not sure how to go about it. I have:
[TestMethod]
public void NonsecureConnection()
{
var controller = new EONSecureController();
Assert.IsTrue(string.IsNullOrEmpty(controller.EONToken));
Assert.IsTrue(controller.tokenMode == EONSecureController.EONTokenModeEnum.None);
}
Easy enough. Testing secure connections is where I'm stuck.
[TestMethod]
public void SecureConnection()
{
var controller = new EONSecureController();
// What to put here?
Assert.IsTrue(!string.IsNullOrEmpty(controller.EONToken));
Assert.IsTrue(controller.tokenMode==EONSecureController.EONTokenModeEnum.Client);
}
I've tried various approaches like:
controller.RequestContext.RouteData.Values[Config.RawTokenName] = "12312342123";
controller.Request = new System.Web.HttpRequest("", "http://localhost/example", "token=2342342");
controller.Request.RawUrl = "http://localhost/example?token=234234234234234";
None of which work for various reasons. Is there a "correct" way to handle testing a controller that relies on the specific URL being requested?
I've seen some things hinting at using Moq but I can't quite join the dots...
NOTE:
Please don't suggest answers along the lines of "don't do authentication like that, you should {etc etc etc} instead". The example is intentionally simplified to maintain focus on the main issue here, which is how to develop the unit tests.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
自行测试属性 - 而不是使用控制器。
Test the attribute by itself - not with the controller.