【问题标题】:Nsubstitute Returns is not overriden in an other test case?Nsubstitute Returns 在另一个测试用例中没有被覆盖?
【发布时间】:2015-04-06 12:56:19
【问题描述】:

如果我有我想要检查的方法,并且出于某种原因,我想将测试用例分成 2 个单独的用例,我很乐意这样做:

    [Test]
    public void EditCustomerShouldReturnExceptionWhenCustomerIsNotCreated()
    {
        var c = new CustomerViewModel();
        _customerRepositoryMock.Update(Arg.Any<Customer>()).Returns(x => { throw new Exception(); });
        Assert.Throws<Exception>(() => _customerService.EditCustomer(c));
    }

    [Test]
    public void EditCustomerShouldReturnTrueWhenCustomerIsCreated()
    {
        var c = new CustomerViewModel();
        _customerRepositoryMock.Update(Arg.Any<Customer>()).Returns(true);
         Assert.IsTrue(_customerService.EditCustomer(c));
    }

但这里的问题是,当第一个测试用例通过时。更新返回值是一个异常,所以当第二个测试用例想要获取返回值时,它也得到了 new Exception();作为返回值?为什么会这样?如何覆盖相同方法的返回值?

【问题讨论】:

    标签: c# asp.net-mvc model-view-controller nunit nsubstitute


    【解决方案1】:

    发生这种情况是因为您的 _customerRepositoryMock 是您的测试类中的一个字段,您正在 SetUp 方法中对其进行初始化。我不确定为什么每次测试通过后都会保留设置值,因为SetUp 方法应该在每个测试方法之前运行。你也实现了TearDown吗?

    但总的来说,我强烈建议您使用局部变量而不是字段。尤其是在测试中,当您为每种测试方法以不同的方式设置模拟时更是如此。

    如果你使用局部变量,你不会得到这种行为。

    编辑:试试这个:

    [Test]
    public void EditCustomerShouldReturnExceptionWhenCustomerIsNotCreated()
    {
        var c = new CustomerViewModel();
        var customerRepositoryMock = Substitute.For<ICustomerRepository>();
        var customerService = new CustomerService(customerRepositoryMock);
        customerRepositoryMock.Update(Arg.Any<Customer>()).Returns(x => { throw new Exception(); });
        Assert.Throws<Exception>(() => customerService.EditCustomer(c));
    }
    
    [Test]
    public void EditCustomerShouldReturnTrueWhenCustomerIsCreated()
    {
        var c = new CustomerViewModel();
        var customerRepositoryMock = Substitute.For<ICustomerRepository>();
        var customerService = new CustomerService(customerRepositoryMock);
        customerRepositoryMock.Update(Arg.Any<Customer>()).Returns(true);
         Assert.IsTrue(customerService.EditCustomer(c));
    }
    

    或者,查看a similar question,您可能只需将第二个方法的返回值更改为 lambda:

    _customerRepositoryMock.Update(Arg.Any<Customer>()).Returns(x => true);
    

    我认为你更喜欢哪个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多