我需要存根的方法的调用方式如下:
List<DocumentInfo> documentInfosToDelete = await _documentInfoRepository.GetListByExternalIdAsync(
partyLegalEntity,
externalId,
type,
status);
Run Code Online (Sandbox Code Playgroud)
这有效,但会生成编译器警告:“此异步方法缺少‘等待’运算符”等。
testService.DocumentInfoRepos.GetListByExternalIdAsyncStringStringDocumentTypeDocumentStatus =
(async (a, b, c, d) =>
{
GetListByExternalIdAsyncCalled = true;
return new List<DocumentInfo>();
});
Run Code Online (Sandbox Code Playgroud)
我想摆脱这些警告,因为它们会淹没任何有关实际问题的警告。
返回 new Task(...) 挂起。如果我正确理解了我在 WWW 上找到的内容,Task.Run(...) 所做的事情与我们正在使用的等待异步模式完全不同。
该怎么办?
我写了一个简单的测试方法来验证一个将 long 值转换为 DateTime 的方法,以下是代码......
[TestMethod]
public void ConvertToDateTime_TestMethod()
{
long date = 1500024370374;
DateTime result = date.GetDateTime();
DateTime comparisonDate = new DateTime(2017, 07, 14, 9, 26, 10);
Assert.AreEqual(result, comparisonDate);
}
Run Code Online (Sandbox Code Playgroud)
重点是日期和时间值完全相同(也在观察窗口中验证)为什么会出现此异常?我发现这篇文章使用 delta 来比较微小的时间差异是否使比较失败,但仍然不确定为什么我仍然需要一个额外的函数来比较日期/时间断言。
编辑 1:这是我正在测试的日期转换方法
public static DateTime GetDateTime(this long milliseconds)
{
try
{
return new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(milliseconds));
}
catch { throw; }
}
Run Code Online (Sandbox Code Playgroud)
即使有一个新的日期时间(长)的替代方法,但从逻辑上讲,这有什么问题?
我已经编写了测试方法来检查场景。
[TestMethod]
public void Return_CheckJUNK_GetComperatorForConditions()
{
// Arrange
string whereClause = "This is the Test String.";
string conditionLeft = "This is";
string conditionRight = "Test String.";
object[] args = new object[3] { whereClause, conditionLeft, conditionRight };
// Act
PrivateObject objPrivate = new PrivateObject(typeof(ManageConfigurations));
var result = (string)objPrivate.Invoke("GetComperatorForConditions", args);
// Assert
object[] arg = new object[2] { "AND", "OR" };
Assert.AreEqual(arg, result);
}
Run Code Online (Sandbox Code Playgroud)
我想检查结果为“AND”或“OR”的多个条件。
我知道这一行有一些错误,它不是与选项进行比较的正确方法
object[] arg = new object[2] { "AND", "OR" };
Assert.AreEqual(arg, result);
Run Code Online (Sandbox Code Playgroud)
错误:
Message: Assert.AreEqual failed. Expected:<System.Object[ …Run Code Online (Sandbox Code Playgroud) 目前我正在使用 Visual Studio 2017 社区版。以前我一直在使用 Visual Studio 2013 Ultimate,并且有一个选项可用于在下面生成代码覆盖率结果Test>Analyze Code Coverage>All Test
在 Visual 2017 Community Edition 中,没有可用于分析代码覆盖率的选项,该选项仅可用于Test>Windows>Code Coverage results.
如何在 Visual Studio 2017 社区中找到分析代码覆盖率?
我试图测试一些使用实体框架的代码,但我无法弄清楚如何从单独的 MSTest 项目中引用 EF 上下文类。两个项目都在同一个解决方案中。
无法将 lambda 表达式转换为类型“DbContextOptions”,因为它不是委托类型
在我的测试用例中:
[TestClass]
public class GreenCardUserTest
{
[TestMethod]
public void TestAddUser()
{
// REFERENCE TO OTHER PROJECT. WORKS FINE
AppUserViewModel a = new AppUserViewModel();
//LIKELY INCORRECT attempt to duplicate code from Startup.cs in other project
using (GreenCardContext _gc = new GreenCardContext(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnection"))))
{
new GCLandingUserModel().AddUser(a,_gc);
}
}
}
Run Code Online (Sandbox Code Playgroud)
摘自主项目 Startup.cs(工作正常):
services.AddDbContext<GreenCardContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
Run Code Online (Sandbox Code Playgroud) 我想为我的控制器方法编写测试,但我在我的方法中Nullpointexceprion使用TempData["EditMember"] = false;了它。
我读过几个类似的帖子,但还没有找到解决这个问题的方法。我尝试使用模拟,但也失败了,因为没有一个示例想要编译。
这是我的控制器方法
public class MemberController : Controller
{
private readonly UnitOfWork _unitOfWork;
public MemberController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork as UnitOfWork;
}
public IActionResult CreateUpdate(string id = null, string table = null)
{
MemberViewModel model = null;
TempData["EditMember"] = false;
if (id != null)
{
TempData["EditMember"] = true;
var member = _unitOfWork.MemberRepositories.FindBySRU(id);
model = AutoMapper.Mapper.Map<Member, MemberViewModel>(member);
}
if (model == null)
model = new MemberViewModel();
TempData["HealthIssues"] = JsonConvert.SerializeObject(model.Player);
TempData["Guardians"] = JsonConvert.SerializeObject(model.Player.Junior);
return View(model); …Run Code Online (Sandbox Code Playgroud) 我在 Visual Studio 2017 C# 中创建了 REST API 框架。我已经创建了刚刚使用 MSTest Framework 创建了一个测试方法,该方法已在测试资源管理器中列出,但是当我运行它时,它会为我提供输出详细信息,如下所示-
Visual Studio 2017 Enterprise:没有可用的测试。确保测试发现者和执行者已注册,并且平台和框架版本设置合适,然后重试。
删除上述 DLL 后尝试更新并安装 Microsoft.VisualStudio.QualityTools.UnitTestFramework.Updated ,但无法安装
安装 Nuget 时出现以下错误 - 错误 NU1202 Package VS.QualityTools.UnitTestFramework 15.0.27323.2 与 netcoreapp2.0 (.NETCoreApp,Version=v2.0) 不兼容。包 VS.QualityTools.UnitTestFramework 15.0.27323.2 支持:microsoftvisualstudioqualitytoolsunittestframeworkdll (Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll,版本 = v0.0) REST.API.Automation.Framework
即使我使用的是 MSTest Framework,也尝试添加 NunitTest、NunitTestAdapter3
看起来可能存在 SDK ASP.Net.Core2 兼容性问题或
我正在尝试构建我的第一个单元测试,并且有一个类可以分别在其构造函数和析构函数中递增和递减实例计数器。我有一个测试来确保它有效但它失败了,似乎我的其他测试中的其他类实例在超出范围时没有调用它们的析构函数。
public class Customer
{
public Customer()
{
++InstanceCount;
}
public Customer(int customerId)
{
CustomerId = customerId;
++InstanceCount;
}
~Customer()
{
--InstanceCount;
}
public static int InstanceCount { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)
[TestClass]
public class CustomerTest
{
[TestMethod]
public void FullNameLastNameEmpty()
{
//--Arrange
Customer customer = new Customer {FirstName = "John"};
const string expected = "John";
//--Act
string actual = customer.FullName;
//--Assert
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void StaticTest()
{
//--Arrange
Customer[] customers =
{
new Customer {FirstName = …Run Code Online (Sandbox Code Playgroud) 在我们的 .Net Core 3.1 项目中,我们使用 Serilog 进行日志记录
在我的测试设置中,我创建了一个 ServiceCollection,以便我可以使用服务集合 \ - 提供程序来更新我在测试中使用的类。我有一个同时使用 DbContext 和 Serilog 记录器的存储库。
using Serilog;
using Microsoft.EntityFrameworkCore;
namespace MyApp.Persistency
{
public class MyRepository : IMyRepository
{
private readonly DataContext _dataContext;
private readonly ILogger _logger;
public OpvragenOnbekendeBurgerRegistratieRepository(DataContext dataContext, ILogger logger)
{
_dataContext = dataContext;
_logger = logger;
}
...
}
Run Code Online (Sandbox Code Playgroud)
在我的测试课中:
[TestInitialize]
public void Initialize()
{
var diCollection =
new ServiceCollection()
.AddSingleton(new SqlConnectionOption(_connectionstring))
.AddDbContext<DataContext>(
options =>
{
options.UseSqlServer(_connectionstring);
}
)
...
xxx Add some kind of Serilog registration …Run Code Online (Sandbox Code Playgroud) 我试图模拟一个统一容器 - 我使用Moq并得到这个错误
System.ArgumentException: Invalid setup on a non-overridable member:
c => c.Resolve<ILogisticsAdapter>(new [] {})
Run Code Online (Sandbox Code Playgroud)
这是我测试的设置部分的代码.
var mockContainer = new Mock<IUnityContainer>();
mockContainer.Setup(c => c.Resolve<ILogisticsAdapter>()).Returns(logicsticsAdapter);
IUnityContainer container = mockContainer.Object;
Run Code Online (Sandbox Code Playgroud)
我错过了什么?我不是一般的模拟或单元测试的主人,但从我能说的这应该工作......
以防万一我使用VS2010和MS测试...
谢谢
这是整个测试夹具 - 你可以看到我已经改变它以使用真正的统一容器,但理想情况下我不想创建一个真正的统一容器 - 它不是我正在测试的.但是你可以看到我注释掉的代码......
[TestMethod]
public void WhenContructed_AdapterGetsSet()
{
//Prepare
ILogisticsAdapter logicsticsAdapter = new Mock<ILogisticsAdapter>().Object;
var mockEventAggregator = new Mock<IEventAggregator>();
mockEventAggregator.Setup(x => x.GetEvent<SetHelpMessageEvent>()).Returns(new SetHelpMessageEvent());
IEventAggregator eventAggregator = mockEventAggregator.Object;
IRegionManager regionManager = new Mock<IRegionManager>().Object;
//var mockContainer = new Mock<IUnityContainer>();
//mockContainer.Setup(c => c.Resolve<ILogisticsAdapter>(null)).Returns(logicsticsAdapter);
//IUnityContainer container = mockContainer.Object;
IUnityContainer container = …Run Code Online (Sandbox Code Playgroud) mstest ×10
c# ×9
.net-core ×2
unit-testing ×2
asp.net ×1
asp.net-core ×1
asp.net-mvc ×1
async-await ×1
dbcontext ×1
destructor ×1
moq ×1
serilog ×1
stub ×1