不能嘲笑_db。在 C# MVC 应用中进行 XUnit 测试的用户



我有一个MVC应用程序,我试图做单元测试和注入所有相关的代码到测试应用程序。这是我的实际应用程序的一部分(称为amaranth),我目前正在测试Index()函数(返回一个视图)在一个控制器称为amaranth/Controllers/AdminController.cs:

using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using amaranth.Data;
using amaranth.Models.ViewModels;
using amaranth.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using amaranth.Models;
using NBitcoin;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace amaranth.Controllers
{
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
private ApplicationDbContext _db;
private UserManager<IdentityUser> _manager;
private BitcoinHelper _btcHelper;
public AdminController(ApplicationDbContext ctx, UserManager<IdentityUser> manager, BitcoinHelper bitcoinHelper) : base()
{
_db = ctx;
_manager = manager;
_btcHelper = bitcoinHelper;
}
public IActionResult Index()
{
var users = _db.Users
.OrderBy(p => p.Id)
.ToList();
return View(users);
}

我想测试Index()。所以我有一个与amaranth在同一目录下的并行项目amaranth.Tests。我在amaranth.Tests/Controllers/AdminControllerTest.cs中构造了以下测试:

using Moq;
using amaranth.Data;
using Microsoft.AspNetCore.Identity;
using Xunit;
using Microsoft.EntityFrameworkCore;
namespace amaranth.Tests.Controllers
{
public class AdminControllerTest
{
private Mock<ApplicationDbContext> _db = new Mock<ApplicationDbContext>();
private Mock<UserManager<IdentityUser>> _manager = new Mock<UserManager<IdentityUser>>();
[Fact]
public void Test1()
{
var options = new DbContextOptionsBuilder<Users>()
.UseInMemoryDatabase(databaseName: "amaranth_test_dbone")
.Options;
using (var context = new UserContext(options))
{
context.Users.Add(new User { UserName = "example@gmail.com", NormalizedUserName = "EXAMPLE@GMAIL.COM", Email = "EXAMPLE@GMAIL.COM" });
context.SaveChanges();
}
using (var context = new UserContext(options))
{
var users = _db.Users
.OrderBy(p => p.Id)
.ToList();
Assert.NotEmpty(users);
}
}
}
}

这个测试只是想看看users条目是否包含任何它应该包含的实际条目,因为我" mock "一个叫做example@gmail.com."编译器在UseInMemoryDatabase上抛出'DbContextOptionsBuilder<Users>' does not contain a definition for 'UseInMemoryDatabase' and no accessible extension method 'UseInMemoryDatabase' accepting a first argument of type 'DbContextOptionsBuilder<Users>', could be found (are you missing a using directive or an assembly reference?)错误,并且找不到UsersUserContext。那么我做错了什么呢?

您需要添加Microsoft.EntityFrameworkCore.InMemory nuget包

另外,由于您创建的是内存数据库,因此不需要mock _db,因为mock _db也将不起作用,因为您模拟的是接口,而不是实际的类。

对于UserManager,因为它不是一个接口,你不能控制它,看这里如何模拟它:如何在。net核心测试中模拟UserManager ?

相关内容

  • 没有找到相关文章

最新更新