[英]How to reach int variable that inside my controller method when i write unit test with xUnit
I am trying to write unit test for my controller. 我正在尝试为我的控制器编写单元测试。 I am using xUnit to test my methots.
我正在使用xUnit测试我的methots。
I can reach "changePasswordX" method inside my controller to test but i can not reach to my userId variable and claim value to check are they equal or not ? 我可以在控制器内部到达“ changePasswordX”方法进行测试,但无法到达userId变量和声明值以检查它们是否相等?
How can i test this code in xUnit? 如何在xUnit中测试此代码?
[HttpGet("ChangePassword")]
public async Task<IActionResult> ChangePassword(int userId, oldPassword, newPassword)
{
if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
return Unauthorized();
_repo.changePasswordX(userId, oldPassword, newPassword);
return Ok();
}
Unit testing does not test every intermediate result of every step of a method. 单元测试不会测试方法每个步骤的每个中间结果。
Unit testing is meant to test the overall output or return value of a method, given certain inputs. 单元测试旨在在给定某些输入的情况下测试方法的整体输出或返回值。
If you need to test that single line of code, then put it in a separate location (library) where it can be called and tested. 如果您需要测试单行代码,则将其放在可以调用和测试的单独位置(库)。
It's not clear what you're actually trying to achieve, but this is the wrong way to be writing unit/integration tests, regardless. 目前尚不清楚您实际上要达到什么目的,但是无论如何,这都是编写单元/集成测试的错误方法。 You don't and shouldn't test the value of
userId
versus the claim yourself in your unit test. 在单元测试中,您不应该测试
userId
的值,也不应该声明自己。 You know that if it doesn't match, your action returns and an UnauthorizedResult
, whereas if it matches, you'll get an OkResult
. 您知道,如果不匹配,则返回操作,并返回一个
UnauthorizedResult
,而如果匹配,则会得到OkResult
。 If you're unit testing, you simply stub out your user principal, call the action as a method, and verify the return. 如果您正在进行单元测试,则只需将用户主体存根,将操作作为方法调用,然后验证返回值即可。 If you're integration testing, the procedures mostly the same: you authorize the call, and verify that the status code is either 401 or 200, depending on which case you're testing.
如果您正在进行集成测试,则过程大致相同:您授权呼叫,并根据要测试的情况验证状态码是401还是200。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.