代码之家  ›  专栏  ›  技术社区  ›  MortenMoulder

使用NSubstitute模拟在出错时引发异常的方法

  •  1
  • MortenMoulder  · 技术社区  · 6 年前

    我在.NET核心应用程序中实现了一个服务,我调用它来验证我的模型。不幸的是,如果服务(不是我的)无效,它会抛出一个异常,如果它是有效的(因为它是一个void方法),它只会以200ok响应。

    所以基本上我是这样做的:

    try {
        await _service.ValidateAsync(model);
        return true;
    } catch(Exception e) {
        return false;
    }
    

    我试着嘲笑里面的方法 ValidateAsync ,将请求发送到我实现的服务。 验证同步 只将控制器的输入从前端的某个对象转换为 Validate 方法理解。

    然而,我真的看不出我应该如何测试这个。这是我试过的,但对我来说没有任何意义。

    [TestMethod]
    public void InvalidTest() {
        var model = new Model(); // obviously filled out with what my method accepts
    
        _theService.Validate(model)
            .When(x => { }) //when anything
            .Do(throw new Exception("didn't work")); //throw an exception
    
        //Assert should go here.. but what should it validate?
    }
    

    所以基本上: When this is called -> throw an exception

    我怎么能用NSubstitute来嘲笑呢?

    1 回复  |  直到 6 年前
        1
  •  4
  •   Nkosi    6 年前

    根据目前的解释,假设是

    public class mySubjectClass {
    
        private ISomeService service;
    
        public mySubjectClass(ISomeService service) {
            this.service = service;
        }
    
        public async Task<bool> SomeMethod(Model model) {
            try {
                await service.ValidateAsync(model);
                return true;
            } catch(Exception e) {
                return false;
            }
        }
    
    }
    

    为了掩盖 SomeMethod

    [TestMethod]
    public async Task SomeMethod_Should_Return_False_For_Invalid_Model() {
        //Arrange
        var model = new Model() { 
            // obviously filled out with what my method accepts
        };
    
        var theService = Substitute.For<ISomeService>();
        theService
            .When(_ => _.ValidateAsync(Arg.Any<Model>()))
            .Throw(new Exception("didn't work"));
    
        var subject = new mySubjectClass(theService);
    
        var expected = false;
    
        //Act
        var actual = await subject.SomeMethod(model);
    
        //Assert
        Assert.AreEqual(expected, actual);
    }