![](/img/trans.png)
[英]How to pass parameter values from test case in TFS to test method in unit test method using MTM?
[英]Unit test case - Pass and fetch a value from a query string parameter
我正在使用 .NET Core。 我想將查詢字符串參數中的值從單元測試函數傳遞給 azure 函數。 我在傳遞和訪問查詢字符串參數值時遇到問題。
URL 為https://localhost:4300/api/RolePageMapping?EnterpriseId=xyz
我想在 Azure 函數中使用查詢字符串參數。 代碼如下。
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
ILogger log)
{
string EnterpriseId = req.Query["EnterpriseId"];
}
我想知道如何將值從我的單元測試函數傳遞到 Azure 函數?
[Fact]
public async Task Function_ReturnBadRequest()
{
var request = new Mock<HttpRequest>();
var logger = new MockLogger();
var actualResult = await
GetUserRolePageMapping.Run(request.Object, logger);
actualResult.Should().BeOfType<HttpResponseMessage>();
}
你會需要模擬HttpRequest.Query Property
的HttpRequest
[Fact]
public async Task Function_ReturnBadRequest() {
//Arrange
var expectedValue = new StringValues("Hello World"); //Or what you want
var request = new Mock<HttpRequest>();
request
.Setup(_ => _.Query["EnterpriseId"])
.Returns(expectedValue);
var logger = new MockLogger();
//Act
var actualResult = await GetUserRolePageMapping.Run(request.Object, logger);
//Assert
actualResult.Should().BeOfType<HttpResponseMessage>();
}
要構建更復雜的查詢字符串,我們可以使用 QueryCollection 類。 這是一個有點不方便的野獸,但它擁有我們從我們擁有的值構建查詢字符串所需的一切。
使用 QueryCollection 類構建查詢字符串需要三個步驟:
創建 StringValues 類的實例。 它是一個將字符串或字符串數組帶入其構造函數的類。 此類保存查詢字符串參數的值。
為查詢參數創建 Dictionary<string,StringValues>。 將查詢參數名稱和 StringValues 實例添加到字典中。 對所有查詢參數重復此操作。
創建 QueryCollection 的實例並使用字典作為構造函數參數。
[Fact] public async Task ViewPdf_returns_view_if_document_exists_and_html_was_asked()
{
var model = new ApplicationReviewModel(); var dictionary = new Dictionary<string, StringValues>(); dictionary.Add("showhtml", new StringValues("1")); dictionary.Add("showtoc", new StringValues("0")); _controller.Request.Query = new QueryCollection(dictionary); _applicationServiceMock.Setup(a => a.GetDocumentReview(It.IsAny<Guid>(), It.IsAny<string>())) .ReturnsAsync(() => model); var result = await _controller.ViewPdf(Guid.NewGuid()) as ViewResult; Assert.Same(model, result.Model); Assert.Equal("ApplicationPdf", result.ViewName);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.