gpt4 book ai didi

c# - 对使用 Azure 云服务的代码进行单元测试

转载 作者:行者123 更新时间:2023-12-03 02:57:18 26 4
gpt4 key购买 nike

我有一个代码,我必须为其编写单元测试。由于我是单元测试的新手,因此我正在寻求您的帮助。我想测试 IsAdmin 方法,该方法获取 CloudTableClient 和字符串作为输入,但我真的不知道如何处理它。我尝试了下面的代码,但失败并显示消息:

Message: Test method UnitTestMatan.UserControllerTests.IsAdmin_NotOnTheList_ReturnFalse threw exception: System.MethodAccessException: Attempt by method 'MatanWebServer.Controllers.UserController.IsAdmin(Microsoft.WindowsAzure.Storage.Table.CloudTableClient, System.String)' to access method 'Microsoft.WindowsAzure.Storage.Table.CloudTable.ExecuteQuery(Microsoft.WindowsAzure.Storage.Table.TableQuery, Microsoft.WindowsAzure.Storage.Table.TableRequestOptions, Microsoft.WindowsAzure.Storage.OperationContext)' failed.

基本上,我要测试的第一件事是,当 IsAdmin 收到不在表中的电子邮件或只是一个随机字符串时,它会返回 false。在测试部分,我想使用 UserController 中生成的表,而不是新建一个表。

以下是我需要测试的类:

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using ParseMatanDataWebJob;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MatanWebServer.Controllers
{
public class UserController : ApiController
{
// GET: api/user
[AdminAuthorizeAttribute]
public IEnumerable<string> Get()
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=matandata;AccountKey=myconnectionstringthatidontwantyoutoknow");
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

IEnumerable<string> EmailsList = GetAllEmails(tableClient);

return (EmailsList);
}

// GET: api/user/5
[UserAuthorizeAttribute]
public ReturnObjectValuescontroller Get(string email)
{
// Retrieve the storage account from the connection string.p
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("myconnectionstringthatidontwantyoutoknow");

// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

var result = new ReturnObjectValuescontroller();

result.isAdmin = IsAdmin(tableClient, email);

// Create the CloudTable object that represents the "people" table.
CloudTable donationsTable = tableClient.GetTableReference("userdonationsdata");

// Create the table query.
TableQuery<DonationData> userDonationsQuery = new TableQuery<DonationData>().Where(
TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, email.ToString()));

var DonationsResult = donationsTable.ExecuteQuery(userDonationsQuery).ToList();

result.DonationsList = DonationsResult;

return result;
}

public static bool IsAdmin(CloudTableClient tableClient, string email)
{
CloudTable AdminsTable = tableClient.GetTableReference("matanadminusers");

TableQuery AdminsListQuery = new TableQuery();

AdminsListQuery.SelectColumns = new List<string>() { "AdminEmail" };

var TableEntityAdminsList = AdminsTable.ExecuteQuery(AdminsListQuery).ToList();

List<string> AdminsEmailList = new List<string>();
foreach (var item in TableEntityAdminsList)
{
AdminsEmailList.Add(item.Properties["AdminEmail"].StringValue);
}

return (AdminsEmailList.Contains(email, StringComparer.OrdinalIgnoreCase));
}

private IEnumerable<string> GetAllEmails(CloudTableClient tableClient)
{
CloudTable donationsTable = tableClient.GetTableReference("useremails");

TableQuery EmailsListQuery = new TableQuery();

EmailsListQuery.SelectColumns = new List<string>() { "RowKey" };

var DynamicEntityEmailsList = donationsTable.ExecuteQuery(EmailsListQuery).ToList();

List<string> EmailList = new List<string>();
foreach (var item in DynamicEntityEmailsList)
{
EmailList.Add(item.RowKey);
}
return EmailList.Distinct();
}

// POST: api/Rony
public void Post([FromBody]string value)
{
}

// PUT: api/Rony/5
public void Put(int id, [FromBody]string value)
{
}

// DELETE: api/Rony/5
public void Delete(int id)
{
}
}
}

这是我为 IsAdmin 尝试的测试:

using System;
using MatanWebServer.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;

namespace UnitTestMatan
{
[TestClass]
public class UserControllerTests
{
[TestMethod]
public void IsAdmin_NotOnTheList_ReturnFalse()
{
var userController = new UserController();

CloudStorageAccount storageAccount = CloudStorageAccount.Parse("myconnectionstringthatidontwantyoutoknow");
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
var result = UserController.IsAdmin(tableClient, "str");

Assert.IsFalse(result);
}
}
}

最佳答案

这更多的是“increddibelly”给出的关于使用接口(interface)的答案的后续。

让我们看下面的例子:

我有一个名为 Person 的类,它需要向数据库发送一些信息。然后,我将不在 Person 类中使用该逻辑,而是将其放在另一个类中。该类负责包含 Person 类与数据库通信所需的所有逻辑,这样的类通常称为数据访问层 (DAL) 或存储库。好的,举个例子:

Person 类:

public Person(IDALPerson d)
{
dal = d;
}

private IDALPerson dal;

public void SendOrder()
{
(Other logic...)
dal.SendOrder("Bananas");
}

所以这里Person类通过它的构造函数从程序中的另一个地方获取这个DAL(依赖),这是一种依赖注入(inject)。该 DAL 实现了 IDALPerson 接口(interface),因此具体的 DAL 类可以是:

public class PersonDAL : IDALPerson
{
public void SendOrder()
{
(logic for adding order)
}
}

然后,在执行测试时,您可以创建 IDALPerson 的模拟对象,这样在测试时,您的 Person 类实际上不使用数据库,然后您可以使用 Moq 框架获取一些信息,如“increddibelly”所述”,从而在不依赖数据库的情况下测试 SendOrder 函数。您的测试可能如下所示:

    [Test]
public void SendOrderTest()
{
//Arrange
Mock<IDALPerson> MockDAL = new Mock<IDALPerson>();
Person p = new Person(MockDAL);

//Act
p.SendOrder();

//Assert
//Assert something.
}

关于c# - 对使用 Azure 云服务的代码进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51878840/

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