我有以下类结构:
public class MyObj
{
public int Number;
}
public interface IService
{
int ProcessInt(MyObj obj);
}
public class Service : IService
{
public int ProcessInt(MyObj myObj)
{
return myObj.Number;
}
}
Run Code Online (Sandbox Code Playgroud)
然后是消费阶层
public class Class1
{
public void Run(IService s)
{
var obj = new MyObj {Number = 1};
Console.WriteLine(s.ProcessInt(obj));
}
}
Run Code Online (Sandbox Code Playgroud)
然后是单元测试
[TestFixture]
public class MyTest
{
private readonly Mock<IService> _service = new Mock<IService>(MockBehavior.Strict);
private readonly Class1 _sut = new Class1();
[SetUp]
public void SetUp()
{
var obj …Run Code Online (Sandbox Code Playgroud) 我使用 Moq 编写了以下类和测试类:
public class Mytest : testin
{
public int getId(int id)
{
int s = 2;
return s;
}
}
Run Code Online (Sandbox Code Playgroud)
测试类:
private Mock<testin> _mock;
[TestInitialize]
public void Setup()
{
_mock = new Mock<testin>();
}
[TestMethod]
public void returngetId()
{
// Build up our mock object
_mock.Setup(x => x.getId(It.IsAny<int>())).Returns(1)
}
Run Code Online (Sandbox Code Playgroud)
我从函数返回2,并在单元测试用例中检查值1。根据我的理解,测试用例应该失败。但我收到成功消息。我如何验证返回值正是我所期望的?如果它返回 1 以外的值,我希望测试失败。
我有一个类,其中有一个无参数构造函数。但是当这个构造函数被调用时,类的五个属性从构造函数的配置文件中获取值。类中有两个方法使用在构造函数中初始化的参数。
我想使用模拟框架为两种方法编写单元测试。但是,我不确定如何在构造函数中初始化参数,因为调用该方法不会为这些属性提供值。
public class ABC
{
public ABC()
{
a = ConfigurationManager.AppSetting["GetValue"];
b = ConfigurationManager.AppSetting["GetValue1"];
}
public int Method1(IDictionary<string, string> dict)
{
d = a + b /2; (how to mock values of a and b while writing unit tests
using mock framework. In reality, a in my case is
dictionary)
//some business logic
return d;
}
}
Run Code Online (Sandbox Code Playgroud)
提前致谢,
我想让我的模拟(使用 Moq)为其中的每个 DateTime 类型的属性返回一个给定的 DateTime。
我该怎么做?
我试过,mock.SetupAllProperties()但它不接受任何配置。
我仍在学习在我的应用程序中使用 MSTest 和 Moq 进行自动化单元测试。我已经成功地模拟了代码并运行了它。它表明测试通过,但代码覆盖率为 0%。这是我下面的代码。需要更改什么才能使代码覆盖率变为 100%。
我知道这个问题之前曾被问过几次,但似乎没有任何帮助。所以有人可以告诉我我做错了什么。
非常感谢任何帮助。谢谢。
PS:我使用 Sonarcube 来了解代码覆盖率。
using Moq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
namespace MyNameSpace
{
[TestClass]
public class ApplicationTest
{
readonly Helper moqHelper = new Helper();
[TestMethod()]
public void GetDataFromDataBaseMoq()
{
Task<bool> returnValue;
Mock<Application> mockType = new Mock<Application>();
mockType.CallBase = true;
mockType.Setup(x => x.GetDataFromDataBase()).Returns(returnValue = moqHelper.GetDataFromDataBaseMoq());
if (returnValue.Result)
{
Assert.IsTrue(true);
}
else
{
Assert.Fail();
}
}
}
[ExcludeFromCodeCoverage]
class Helper
{
internal async Task<bool> GetDataFromDataBaseMoq()
{
bool returnValue = true;
return returnValue; …Run Code Online (Sandbox Code Playgroud) 我正在尝试对一些代码进行单元测试,这些代码使用IServiceProvider和反射的组合来创建扩展抽象类的每个类的实例BaseCommand:
IEnumerable<BaseCommand> commandsInAssembly = typeof(BaseCommand)
.Assembly.GetTypes()
.Where(t => t.IsSubclassOf(typeof(BaseCommand)) && !t.IsAbstract)
.Select(t => (BaseCommand)ActivatorUtilities.CreateInstance(_serviceProvider, t))
.ToList();
Run Code Online (Sandbox Code Playgroud)
这里棘手的部分_serviceProvider是注入并且需要被模拟(我认为),以允许这段代码成功且独立地运行。每个命令都需要访问 DI 以解决其依赖关系。大多数命令看起来类似于:
public SomeCommand(IAppState appState, ILoggerAdapter<SomeCommand> logger) : base(appState)
Run Code Online (Sandbox Code Playgroud)
我能够IServiceProvider很好地模拟来解决IAppState,但我在ILoggerAdapter<>. 这是我目前的设置:
单元测试构造函数
var serviceProvider = new Mock<IServiceProvider>();
serviceProvider
.Setup(x => x.GetService(typeof(IAppState)))
.Returns(new AppState());
serviceProvider
.Setup(x => x.GetService(typeof(ILoggerAdapter<>)))
.Returns(typeof(LoggerAdapter<>));
var serviceScope = new Mock<IServiceScope>();
serviceScope
.Setup(x => x.ServiceProvider)
.Returns(serviceProvider.Object);
var serviceScopeFactory = new Mock<IServiceScopeFactory>();
serviceScopeFactory
.Setup(x => x.CreateScope())
.Returns(serviceScope.Object);
serviceProvider
.Setup(x => …Run Code Online (Sandbox Code Playgroud) 我正在使用 xUnit 和 Moq 编写测试用例。
目前我正在为遥测类编写测试用例。
public class TelemetryClientMock : ITelemetryClientMock
{
public string key { get; set; } //I want to mock key variable.
private TelemetryClient telemetry;
public TelemetryClientMock( )
{
telemetry = new TelemetryClient() { InstrumentationKey = key };
}
public void TrackException(Exception exceptionInstance, IDictionary<string, string> properties = null)
{
telemetry.TrackException(exceptionInstance, properties);
}
public void TrackEvent(string eventLog)
{
telemetry.TrackEvent(eventLog);
}
}
Run Code Online (Sandbox Code Playgroud)
在测试类中,我如何模拟关键变量。我曾经为模拟方法编写以下代码。
[Fact]
public void TrackException_Success()
{
Exception ex=null;
IDictionary<string, string> dict = null;
var reader = new …Run Code Online (Sandbox Code Playgroud) 我正在为我的控制器中的用户创建方法编写单元测试。当我运行单元测试时,它return ValidationProblem();在我的控制器方法的行中返回 NullReferenceException
。
[xUnit.net 00:00:01.16] WotkTimeManager.Tests.UsersControllerTests.PostUsers_BadResult_WhenInvalidData [FAIL]
X WotkTimeManager.Tests.UsersControllerTests.PostUsers_BadResult_WhenInvalidData [285ms]
Error Message:
System.NullReferenceException : Object reference not set to an instance of an object.
Stack Trace:
at Microsoft.AspNetCore.Mvc.ControllerBase.ValidationProblem(String detail, String instance, Nullable`1 statusCode, String title, String type, ModelStateDictionary modelStateDictionary)
at Microsoft.AspNetCore.Mvc.ControllerBase.ValidationProblem(ModelStateDictionary modelStateDictionary)
at Microsoft.AspNetCore.Mvc.ControllerBase.ValidationProblem()
at WorkTimeManager.Controllers.UsersController.Post(UserCreateDto user) in /mnt/c/Users/kubw1/WorkTimeManagerSolution/src/WorkTimeManager/Controllers/UsersController.cs:line 72
at WotkTimeManager.Tests.UsersControllerTests.PostUsers_BadResult_WhenInvalidData() in /mnt/c/Users/kubw1/WorkTimeManagerSolution/test/WotkTimeManager.Tests/UsersControllerTests.cs:line 92
--- End of stack trace from previous location where exception was thrown ---
Run Code Online (Sandbox Code Playgroud)
我的控制器方法
[HttpPost]
public async Task<ActionResult<string>> Post(UserCreateDto user)
{
var …Run Code Online (Sandbox Code Playgroud) 我正在编写一个 webAPI 单元测试,其中对类中的每个方法都有多个测试调用。我正在使用 UseInMemoryDatabase 创建数据库并加载测试数据。
我在每种测试方法之间遇到以下错误
无法跟踪实体类型“AppSettings”的实例,因为已跟踪具有相同键值 {'myId '} 的另一个实例。附加现有实体时,确保仅附加一个具有给定键值的实体实例
我添加了 context.Database.EnsureDeleted(); 这消除了 Get 方法的错误,但它仍然在删除和更新单元测试中引发错误。
当我一次运行所有测试方法时,我不知道如何消除删除和更新时的此错误。
任何帮助表示赞赏。
private MyDBContext context;
[TestInitialize]
public void SetUp()
{
var options = new DbContextOptionsBuilder<MyDBContext>()
.UseInMemoryDatabase(databaseName: "MyDB")
.Options;
context = new CACIDBContext(options);
context.Database.EnsureDeleted(); // this removed the error between the several GET test methods. but not the delete,update
context.AppSettings.Add(new AppSettings { myId = 1, MyName = "test1", MyValue = "test1" });
context.AppSettings.Add(new AppSettings { myId = 2, MyName = "test2", MyValue = "test2" });
context.AppSettings.Add(new …Run Code Online (Sandbox Code Playgroud) 我对 Java 很了解,但对 C# 很陌生。
我在为以下示例代码编写单元测试时遇到困难:
public static IDictionary<string, string> GetVaultSecretsDictionary(Uri keyVaultUrl, ChainedTokenCredential azureChainedCredential, string[] secretNames)
{
var client = new SecretClient(keyVaultUrl, azureChainedCredential);
var vaultSecrets = new Dictionary<string, string>();
foreach (var secretName in secretNames) {
Response<KeyVaultSecret> responseKeyVaultSecret = client.GetSecret(secretName);
var secretValue = responseKeyVaultSecret.Value.Value;
vaultSecrets.Add(secretName, secretValue);
}
return vaultSecrets;
}
Run Code Online (Sandbox Code Playgroud)
我想为上述函数编写单元测试,但我不知道如何模拟 SecretClient,然后以与 Java 中使用InjectMock类似的方式注入它。另外,为了获取responseKeyVaultSecret值,还会向URL发送请求,我不知道如何实现GetSecret以 返回响应模拟值。
我寻找过示例和教程,但对我来说并没有什么成果。
注意:上述函数内不能进行任何更改。