簡體   English   中英

使用 NSubstitute 模擬一個方法兩次,首先拋出錯誤,然后返回相同的調用簽名請求的值

[英]Mock a method twice with NSubstitute to first throw error and later return value for the same called signature request

我想用 NSubstitute 模擬一個方法兩次,首先拋出錯誤,然后返回相同的調用簽名請求的值。

public interface IMyAction
{
    public Task<MyDto> Upsert(CreateRequest requestDto);
}

public class MyAction : IMyAction
{

    private readonly IMyRepository _repository;
    
    public MyAction(IMyRepository repository)
    {
        _repository = repository;
    }
    
    public Task<MyDto> Upsert(CreateRequest requestDto){
    {
        var domainEntity = await _repository.Get(requestDto.Param1);
        if(domainEntity == null)
        {
            try
            {
                // try to create entity
            }
            catch(RecordExistsException) // Throws when another concurrent request creates the same entity. Need to test this catch block scenario
            {
                domainEntity = await _repository.Get(requestDto.Param1);
                // 
                //...perform update operation using the domainEntity and requestDto
                //
            }
            catch(Exception ex)
            {
                throw
            }
        }
    }
}

我有一個邊緣情況,我希望第一次調用應該拋出異常,第二次調用應該返回 dto。 兩個調用的參數值相同。

我正在使用 NSubstitute 來模擬 xunit 測試中的依賴項。

我的設置:

IMyRepository _repository = Substitute.For<IMyRepository>();
var myAction = new MyAction(_repository);

_repository.Get(Arg.Any<string>()).Throws<NotFoundException>();
_repository.When(x => x.Get(Arg.Is<string>(r => r == "id1")))
           .Do(x => _repository.Get(Arg.Is<string>(r => r == "id1")).Returns(new MyDto()));

期待:

_repository.Get("id1").Throws<NotFoundException>(); // first call invocation
_repository.Get("id1").Returns(new MyDto()); // second call invocation

但是當myAction.Upsert(new CreateRequest()); 調用domainEntity在第一次調用中返回而不是拋出異常。

在深入研究 SO 之后,我在這里找到了一個解決方案。

對於我的情況,我通過 mocking 解決了以下問題 -

_repository.Get("id1").Returns(x => throw new NotFoundException(), x => new MyDto());

Returns()還支持傳遞多個函數以從其返回,這允許序列中的一個調用引發異常或執行一些其他操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM