小编And*_*and的帖子

我如何模拟User.Identity.GetUserId()?

我正在尝试对我的代码进行单元测试,其中包括以下行:

UserLoginInfo userIdentity = UserManager.GetLogins(User.Identity.GetUserId()).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

因为我无法得到,我只是被困在一点上:

User.Identity.GetUserId()
Run Code Online (Sandbox Code Playgroud)

返回一个值.我一直在设置控制器时尝试以下操作:

var mock = new Mock<ControllerContext>();
mock.Setup(p => p.HttpContext.User.Identity.GetUserId()).Returns("string");
Run Code Online (Sandbox Code Playgroud)

但是它给出了"NotSupportedException未被用户代码处理"的错误.我也尝试过以下方法:

ControllerContext controllerContext = new ControllerContext();

string username = "username";
string userid = Guid.NewGuid().ToString("N"); //could be a constant

List<Claim> claims = new List<Claim>{
    new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", username), 
    new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userid)
};
var genericIdentity = new GenericIdentity("Andrew");
genericIdentity.AddClaims(claims);
var genericPrincipal = new GenericPrincipal(genericIdentity, new string[] { });
controllerContext.HttpContext.User = genericPrincipal;
Run Code Online (Sandbox Code Playgroud)

基于我在stackoverflow上找到的一些代码,但这会返回相同的错误"NotSupportedException未被用户代码处理".

任何有关我如何进行的帮助将不胜感激.谢谢.

.net c# unit-testing moq asp.net-mvc-5

30
推荐指数
3
解决办法
2万
查看次数

如何使用Linq查询Azure存储表?

我不确定到底在哪里,但我对此有错误的想法.

我试图在第一个实例中使用linq查询azure存储表.但我无法弄清楚它是如何完成的.从各种来源看,我有以下几点:

List<BlogViewModel> blogs = new List<BlogViewModel>();

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("BlogConnectionString"));
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable blogTable = tableClient.GetTableReference("BlogEntries");

try
{
   TableServiceContext tableServiceContext = tableClient.GetTableServiceContext();
   TableServiceQuery<BlogEntry> query = (from blog in blogTable.CreateQuery<BlogEntry>()
   select blog).AsTableServiceQuery<BlogEntry>(tableServiceContext);
   foreach (BlogEntry blog in query)
   {
      blogs.Add(new BlogViewModel { Body = blog.Body });
   }
}
catch { }
Run Code Online (Sandbox Code Playgroud)

在我搞砸之前,我可能已经把它靠近了.要不然,或者我误解了TableService是什么.以下代码对我有用,但我试图将其切换为使用Linq.

List<BlogViewModel> blogs = new List<BlogViewModel>();

var storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("BlogConnectionString"));
var tableClient = storageAccount.CreateCloudTableClient();
CloudTable blogTable = tableClient.GetTableReference("BlogEntries");

TableRequestOptions reqOptions = new TableRequestOptions()
{
   MaximumExecutionTime = TimeSpan.FromSeconds(1.5),
   RetryPolicy …
Run Code Online (Sandbox Code Playgroud)

c# linq azure azure-storage azure-table-storage

16
推荐指数
2
解决办法
2万
查看次数

如何在单元测试中模拟控制器上下文,以便我对字符串函数的部分视图有效?

我正在尝试为我的控制器创建一个单元测试,但我正在测试的操作使用部分视图来查看字符串函数,该函数不希望在我的测试中工作.

private string RenderPartialViewToString(string viewName, object model = null)
{
   if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetRequiredString("action");

   ViewData.Model = model;

   using (System.IO.StringWriter sw = new System.IO.StringWriter())
   {
      ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
      ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
      viewResult.View.Render(viewContext, sw);

      return sw.GetStringBuilder().ToString();
   }
}
Run Code Online (Sandbox Code Playgroud)

这给了我一行错误"对象引用未设置为对象的实例" ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);

我在控制器的单元测试中的设置是(删除了几个位以简化它):

var mock = new Mock<ControllerContext>();
mock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName);
if (userName != null)
{
   mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);
   mock.SetupGet(p => p.HttpContext.User.Identity.IsAuthenticated).Returns(true);
}
else
{
   mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(false);
}
var controller …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq asp.net-mvc-5

14
推荐指数
1
解决办法
9488
查看次数

我应该如何在Controller中模拟SignalR HubContext以进行单元测试?

我在MVC5项目中使用SignalR.我在控制器内进行调用,如下所示:

private Microsoft.AspNet.SignalR.IHubContext blogHubContext = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<BlogHub>();
blogHubContext.Clients.All.addNewBlogToPage(RenderPartialViewToString("Blog", model));
Run Code Online (Sandbox Code Playgroud)

我正在尝试对此控制器中的操作进行单元测试.单元测试工作正常,直到我添加了SignalR功能.现在我想弄清楚如何模拟HubContext.我有两种可能性.

  1. 我在构造函数中设置了集线器,所以我有类似以下内容:

    private Microsoft.AspNet.SignalR.IHubContext blogHubContext;
    public BlogController(Microsoft.AspNet.SignalR.IHubContext topicHub = null){
         blogHubContext = (blogHub != null) ? blogHub : Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<BlogHub>();
    }
    
    Run Code Online (Sandbox Code Playgroud)

    然后我可以以某种方式模拟HubContext并在单元测试中创建它时将其发送到控制器.到目前为止我只有这个:

    Mock<IHubContext> blogHub = new Mock<IHubContext>();
    
    Run Code Online (Sandbox Code Playgroud)

    (注意:我已将所有内容简化为仅关注SignalR方面.控制器中也使用了存储库等)

  2. 或者,我考虑创建另一个类来包装集线器,然后只需从中调用函数来调用集线器.我认为我的单元测试更容易模拟,但不确定它是否是个好主意.

方向赞赏.或者都是可以接受的前进方式?谢谢.

c# unit-testing moq signalr asp.net-mvc-5

6
推荐指数
1
解决办法
2708
查看次数

JQuery Mobile转换停止在长页面上工作

我遇到了从长页面底部运行时不再出现页面转换的问题.

这是一个jsfiddle:http://jsfiddle.net/7WVHA/7/

如果打开示例并单击黑色导航按钮,则转换将按预期运行.但是,如果您返回到长页面,请滚动到底部并再次运行它,不再发生转换,第二页就会立即显示.

任何帮助将不胜感激.

<div data-role="page" id="long">
    <div data-role="header" data-position="fixed" data-theme="a">
        <h1>Long Page</h1>
        <a href="#short" data-transition="flip" data-role="button" data-theme="b">DO TRANSITION</a>

    </div>
    <div data-role="content" data-theme="a">
        <div class="box">TEST BOX 1</div>
        <div class="box">TEST BOX 2</div>
        <div class="box">TEST BOX 3</div>
        <div class="box">TEST BOX 4</div>
        <div class="box">TEST BOX 5</div>
        <div class="box">TEST BOX 6</div>
        <div class="box">TEST BOX 7</div>        
    </div>
</div>
<div data-role="page" id="short">
    <div id="gridheader" class="header" data-role="header" data-position="fixed" data-theme="a">
        <h1>Short Page</h1>
        <a href="#long" data-transition="flip" data-role="button" data-theme="b"> Back</a>

    </div>
    <div data-role="content" data-theme="a">
        Short page
    </div> …
Run Code Online (Sandbox Code Playgroud)

jquery jquery-mobile

6
推荐指数
1
解决办法
227
查看次数

如何模拟存储库以用作Controller的参数?

我正在使用Entity Framework 6为C#MVC5项目构建单元测试.我正在尝试使用Moq模拟我的BlogRepository,然后将其用作我试图测试的BlogController的参数.我实际上单元测试工作正常,但为了做到这一点,我创建了一个Fake BlogRepository类,当我更愿意使用Moq来解决它.

我得到的问题是Controller希望参数是IBlogRepository类型,但只是将其视为模拟.所以我得到一个无效的参数错误.我认为这就是它的用法.

这是我尝试创建模拟:

Mock<IBlogRepository> blogRepo = new Mock<IBlogRepository>();
blogRepo.Setup(t => t.GetBlogByID(It.IsAny<int>())).Returns<Blog>(blog => new Blog());
Run Code Online (Sandbox Code Playgroud)

这是控制器的开始:

public class BlogController : Controller
{
    IBlogRepository blogRepo;

    public BlogController(IBlogRepository repoBlog)
    {
        blogRepo = repoBlog;
    }
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?或者我在这里得到了错误的想法.任何帮助,将不胜感激.谢谢.

c# asp.net-mvc unit-testing entity-framework moq

5
推荐指数
1
解决办法
225
查看次数

如何在EF设置中仅从Web.Config获取提供者连接字符串?

我正在开发一个使用Entity Framework的项目.但是,我需要执行一些SQL查询(不使用EF),并希望从Web.Config中检索连接字符串.使用以下方法获取完整的连接字符串很好

System.Configuration.ConfigurationManager.ConnectionStrings["DatabaseName"].ConnectionString;
Run Code Online (Sandbox Code Playgroud)

这会返回EF的完整连接字符串.

metadata=res://*/NameDB.csdl|res://*/NameDB.ssdl|res://*/NameDB.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=name-db;Initial Catalog=Name;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient
Run Code Online (Sandbox Code Playgroud)

我只要求提供"提供者连接字符串"部分.这有什么聪明的方法吗?或者我只需要使用像正则表达式这样的字符串搜索字符串?

任何帮助/建议表示赞赏.谢谢.

c# sql asp.net-mvc entity-framework

4
推荐指数
1
解决办法
3484
查看次数

Angular.js - ng-model在文本输入上覆盖我的ng值

我首先提到我对Angular很新,所以我可能没有用正确的"Angular方式"做事.

我有以下ng-repeat循环一些数据 - 正在返回正确的数据.

<tr ng-repeat="attribute in attributeCategory.attributes">
    <td>
        {{attribute.name}}
    </td>
    <td>
        <input type="checkbox" ng-model="attr.enabled" ng-checked="{{attribute.parameters.enabled}}" ng-change="updateAttribute(attr, {{attribute.attribute_id}})"/>
    </td>
    <td>
        <input type="checkbox" ng-model="attr.normalise" ng-checked="{{attribute.parameters.normalise}}" ng-change="updateAttribute(attr, {{attribute.attribute_id}})"/>
    </td>                
    <td>
        <input type="checkbox" ng-model="attr.reverse" ng-checked="{{attribute.parameters.reverse}}" ng-change="updateAttribute(attr, {{attribute.attribute_id}})"/>
    </td>
    <td>
        <input type="text" ng-model="attr.min_threshold" ng-value="{{attribute.parameters.min_threshold}}" ng-change="updateAttribute(attr, {{attribute.attribute_id}})"/>                    
    </td>
    <td>
        <input type="text" ng-model="attr.max_threshold" ng-value="{{attribute.parameters.max_threshold}}" ng-change="updateAttribute(attr, {{attribute.attribute_id}})"/>                    
    </td>
<tr>
Run Code Online (Sandbox Code Playgroud)

由于某种原因,input ="text"字段上的ng值未显示.我需要将字段中的数据传递给updateAttribute()函数,这就是我将模型绑定到我正在传递的attr变量的原因.然后,此变量用于API调用.

如果我从文本字段中取出模型,我有正确的值,但我需要有人获得该值并将其传递给函数.

如果还有其他方式我应该这样做,请告诉我:)

javascript angularjs angularjs-scope angular-ngmodel

2
推荐指数
1
解决办法
8288
查看次数