标签: moq

最小起订量重新抛出错误传递到安装程序

所以我有一个使用该接口的错误处理类:

public interface IEventLogger
  {
    void WriteError(Exception ex, string message);
  }
Run Code Online (Sandbox Code Playgroud)

所以我用Moq来模拟这个以进行单元测试。此方法通常只会将错误记录到事件查看器中,但对于我的单元测试,我希望它重新抛出传递到该方法中的异常,即,如果将错误传递到此模拟类中,我希望单元测试失败。我有什么想法可以做到这一点吗?

我到目前为止:

 var moqIEventLogger = new Mock<IEventLogger>();
 moqIEventLogger.Setup(s => s.WriteError(It.IsAny<Exception>(), 
                                           It.IsAny<string>()));
Run Code Online (Sandbox Code Playgroud)

但我不确定如何访问原始异常(如果可能的话)?

c# nunit unit-testing moq

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

用于更改每次调用行为的 Moq 语法是什么?

我需要一个接口在第一次传递参数时返回某个值,但为每个后续调用抛出异常。

我怎样才能做到这一点 ?

即如果我有这样的接口:

namespace TradingInterface
{
    public interface IBackOffice
    {
        void Buy(string stock, int amount);
        void Sell(string stock, int amount);
    }
}
Run Code Online (Sandbox Code Playgroud)

以及以下模拟对象:

public class MockBackOffice: IBackOffice
{
    private bool _firstcall = true; 
    public void Buy(string stock, int amount)
    {
        if (_firstcall && stock == "AAPL")
        {
            _firstcall = false;
            return;
        }
        else
        {
            throw new Exception("second call");
        }
    }

    public void Sell(string stock, int amount)
    {
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我定义以下内容,它不会引发“AAPL”上的第二次购买调用:

Mock<IBackOffice> mockBackOffice = new Mock<IBackOffice>();
mockBackOffice.Setup(x => x.Buy(It.IsAny<string>(), …
Run Code Online (Sandbox Code Playgroud)

c# tdd moq

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

自动夹具用值初始化列表

请看下面的截图:

在此输入图像描述

这是完整的代码:

using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;

    namespace MyNamespace.TestFixtures
    {
        [TestFixture]
        public class Tests
        {      
            [OneTimeSetUp]
            public void OneTimeSetUp()
            {

                var Fixture = new Fixture().Customize(new AutoMoqCustomization());
                List<Product> products;
                products = Fixture.Create<List<Product>>();
                Console.WriteLine("Got here");
           }
        }
    }
Run Code Online (Sandbox Code Playgroud)

为什么列表中有三个产品(全部为空)。肯定应该没有(0)吧?

更新

继续下面的答案。假设我想使用 Autofixture 创建一个列表:

List<Product> products = new List<Product>();
var Product1 = new Product() { id=1, description='Product1' };
var Product2 = new Product() { id=2, description='Product2' };
products.add(Product1);
products.Add(Product2);
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

c# unit-testing moq

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

模拟 Url.RouteUrl

我使用Asp.netCore并且以下代码是我需要测试的操作的一部分XUnit。问题是URL在我测试操作方法时哪个为空。我如何模拟URL及其功能RoutUrl来返回URL我期望的。

var callbackUrl = Url.RouteUrl("ConfirmEmail", new { userId = user.Id, token }, Request.Scheme);
Run Code Online (Sandbox Code Playgroud)

我也试过这段代码,但它根本不起作用。

string locationUrl = "http://location/";
var mockUrlHelper = new Mock<IUrlHelper>();
mockUrlHelper
    .Setup(x => x.RoutUrl("ConfirmEmail", It.IsAny<object>(), It.IsAny<string>()))
    .Returns(locationUrl);

_accountController.Url = mockUrlHelper.Object;
Run Code Online (Sandbox Code Playgroud)

这是我正在测试的操作方法:

[HttpPost]
public async Task<JsonResult> SendEmailConfirmation(string email)
{
    if (string.IsNullOrEmpty(email)) throw new Exception("Inavlid parameter");

    var user = await _userManager.GetUserAsync(User);

    if (user.Email.ToLower() == email.ToLower().Trim())
        return Json(false);

    user.EmailConfirmed = false;
    user.Email = email;
    await _userManager.UpdateAsync(user);

    var token …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq xunit asp.net-core-mvc

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

我如何模拟 sqlconnection 还是应该重构代码?

我有下面的代码,我已经阅读了Moq 和 SqlConnection? 以及如何存根 IDBconnection,但我仍然不知道如何模拟以下 sqlconnection。

public class SqlBulkWriter : ISqlBulkWriter
{
    private readonly string _dbConnectionString;;

    public SqlBulkWriter(string dbConnectionString)
    {
        this._dbConnectionString = dbConnectionString;
    }

    public void EmptyTable(string schema, string tableName)
    {
        using (var connection = new SqlConnection(this._dbConnectionString))
        {
            try
            {
                connection.Open();
                using (var truncate = new SqlCommand($"TRUNCATE TABLE [{schema}].[{tableName}] ", connection))
                {
                    truncate.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex);
            }
            finally
            {
                connection.Close();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我要为EmptyTable做单元测试,我想我应该先模拟sqlconnection?或者如何对 EmptyTempTable 进行单元测试?

谢谢!许多欣赏!

ado.net unit-testing sqlconnection moq xunit

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

模拟 while 循环

我需要模拟一个 while 循环只运行一次,但是我的设置使它运行无限次,因为我认为它总是返回 true。

我的设置:

var loginName = "12345";

cacheRepository.Setup(m => m.AddString(string.Format("{0}_{1}", Resources.ResetCodeCacheKey, randomCode), loginName)).Returns(true);
Run Code Online (Sandbox Code Playgroud)

while 循环方法:

while (_cacheRepository.AddString(string.Format("{0}_{1}", Resources.ResetCodeCacheKey, code), userLoginName))
{
    //.........
}
Run Code Online (Sandbox Code Playgroud)

添加字符串实现:

public virtual bool AddString(string key, string value)
{
    if (!ExistsKey(key))
    {
        Cache.AddString(key, value);
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

如何设置我的方法只返回 true 一次?代码片段会有所帮助。感谢您对此进行调查。

.net c# unit-testing moq

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

Mocking MongoDb 方法,例如 Xunit 中的 Find、FindAsync 方法

我正在尝试模拟 mongodb 的 findasync,在 Xunit 和 .net 核心中查找方法。

当我试图模拟 InsertOne 时,

mockcollection.setup(x=>x.InsertOneAsync(_newitem,null,It.IsAny<CancellationToken>()).Returns(task.CompletedTask);

but the find is throwing error "Extension Method FindAsync may not be used in setup/verify process.

mockcollection.setup(x=>x.FindAsync(It.IsAny<FilterDefinition<mytbl>>(),null,It.IsAny<CancellationToken>()).Returns(Task.FromResult(mockasyncursor.Object));

Run Code Online (Sandbox Code Playgroud)

当我在网上冲浪时,它说的是扩展方法不能被模拟,上面的方法[FindAsync]是一个扩展方法,其中作为InsertOne并非如此。

我如何模拟该findasync方法?

注意:我尝试使用Mongo2go模拟数据库并能够得出积极的结果,但想知道如何使用模拟?

方法:

public async Task<IEnumerable<XX>> abc()
{
_logger.LogInformation("XXX");

var result = _context
        .XX.FindAsync(_ => true, null, CancellationToken.None);

return ( await _context.XX.FindAsync(_ => true) ).ToList<XX>();
}
Run Code Online (Sandbox Code Playgroud)

单元测试方法:

public async Task XXX()
{
    // Arrange
    var XX = this.XX();
                < IAsyncCursor < XX …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq xunit mongodb

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

C# Moq 方法未返回指定的布尔值

我正在使用下面的代码。我对其他方法使用相同的方法,它工作正常。这里IExportJobAdapter 被模拟的适配器方法应该返回布尔类型值的任务。

从代码中我期望获得真正的价值,但我从我的模拟方法中得到了错误。在控制器内部,我调用了IExportJobAadapter返回 false的模拟方法。我从堆栈溢出中尝试了很多东西,但无法解决。我想重复一遍,只有在返回 bool 方法的情况下才会发生这种情况。所有其他地方我都使用相同的方法并且工作正常。

var controller = mocker.CreateInstance<ExportJobController>();
Run Code Online (Sandbox Code Playgroud)

模拟适配器方法

mocker.GetMock<IExportJobAdapter>()
    .Setup(x => x.CreateExportJob(null))
    .Returns(Task.FromResult(true));

// Act
var result = await controller.CreateExportJob(new ExportJobRequest { ProfileId = profileId, Request = request,DttmCreated= dttmCreated });
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq

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

Moq 框架对返回任务的方法进行单元测试

我是这个 MOQ 框架的新手,老实说,我很难运行我的单元测试。基本上,我有一个 C# 应用程序,它基本上使用 PostAsync 上传到 API。

现在,由于我不能(也不应该)在我的单元测试期间调用 API(否则它将是一个集成测试),我在它周围添加了一个包装器方法,并允许该方法通过模拟它返回 true。但无论我做什么,它都返回 false。我已经解决了SO问题,但我不确定我错过了什么。我没有使用过接口,但使用了带有虚方法的类。

这是我想要测试的示例代码

public async Task<bool> CreateNoteBookDirectory (string url ,string bearertoken, JavaScriptSerializer jser,RestPostClass rest)
        {
            NoteBookDirectory jsnbdir = new NoteBookDirectory();
            jsnbdir.path = "/JobNotebooks/ClientScoreDataInput";

            var directorycreate = jser.Serialize(jsnbdir);
            var content = new StringContent(directorycreate, Encoding.UTF8, @"application/json");


            bool result=await rest.HttpPost(url, content, bearertoken);

            return result;
        }
Run Code Online (Sandbox Code Playgroud)

这个方法在主类中。

RestPostClass 类有虚方法 HttpPost,它的骨架有点像这样

 public async virtual Task<bool> HttpPost(String url, StringContent content, string bearertoken)
        {
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bearertoken);
            // Add an …
Run Code Online (Sandbox Code Playgroud)

.net c# unit-testing moq

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

模拟控制器返回 NULL

我正在使用 xUnit,当我调用控制器的方法时,我得到null. 当我调试时,它不会执行RemovePrimeNumbers方法而是返回null

发生这种情况有什么原因吗?

测试方法

public void ControllerTest()
{
    PrimeNumberViewModel returnObject = new PrimeNumberViewModel();
    returnObject.Result = new PrimeNumberModel();

    Mock<IPrimeNumberOperations> _mockService = new Mock<IPrimeNumberOperations>();
    var _controller = new PrimeNumberOperationsController(_mockService.Object) ;

    _mockService.Setup(x => x.RemovePrimeNumbers("Test123")).Returns(returnObject);

    var result = _controller.RemovePrimeNumbers("HAHAHA 2");

    Assert.Equal("HAHAHA 2", result);   
}
Run Code Online (Sandbox Code Playgroud)

控制器

[HttpGet()]
public string RemovePrimeNumbers(string plainText)
{
    PrimeNumberViewModel result = _primeNumberService.RemovePrimeNumbers(plainText);
    return result.Result.removedPrimeNumbersText; // *result* is getting NULL 
}
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq asp.net-core-webapi

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