簡體   English   中英

NSubstitute 使用 FORPartsOf 配置 void 方法不做任何事情

[英]NSubstitute using FOrPartsOf to configure void method to do nothing

我有一個簡單的例子,我想測試一個方法是否在與調用方法相同的類上被調用:

    public class MyClass
    {
        public void SomeMethod()
        {
            SomeSubMethod();
        }

        public virtual void SomeSubMethod()
        {
            // do a lot of weird stuff
        }

    }

    public class UnitTest1
    {
        [Fact]
        public void Test1()
        {
            var target = Substitute.ForPartsOf<MyClass>();
            target.Configure().SomeSubMethod(); // <---- please just do nothing

            target.SomeMethod();

            target.Received(1).SomeSubMethod();
        }
    }

我的問題是SomeSubMethod實際上是在單元測試中調用的,在我的真實代碼中我想避免這種情況。

一個簡單的工作是讓SomeSubMethod返回一些東西,但現在我正在污染我的真實代碼

    public class MyClass
    {
        public void SomeMethod()
        {
            SomeSubMethod();
        }

        public virtual int SomeSubMethod()
        {
            // do a lot of weird stuff
            return 0;
        }

    }

    public class UnitTest1
    {
        [Fact]
        public void Test1()
        {
            var target = Substitute.ForPartsOf<MyClass>();
            target.Configure().SomeSubMethod().Returns(0); // <--- Now the real SomeSubMethod won't be invoked

            target.SomeMethod();

            target.Received(1).SomeSubMethod();
        }
    }

有沒有辦法將 void 方法配置為什么都不做?

你的/彼得

您可以使用When..Do語法來處理void方法:

public void Test1() {
    var target = Substitute.ForPartsOf<MyClass>();
    target.When(x => x.SomeSubMethod()).DoNotCallBase(); // <- do not invoke real code

    target.SomeMethod();

    target.Received(1).SomeSubMethod();
}

假設我們將SomeMethod virtual ,另一種選擇是使用標准Substitute.For<T>所有成員,並選擇僅根據您要測試的方法進行調用。

public void Test2() {
    var target = Substitute.For<MyClass>(); // <- substitute all members
    target.When(x => x.SomeMethod()).CallBase(); // <- except this one, call the real base implementation for SomeMethod 

    target.SomeMethod();
    target.Received(1).SomeSubMethod();

    Assert.Equal(0, target.counter);
}

文檔鏈接:

根據你的描述,我重寫了代碼:

Public class MyClass
{
    public int x = 0;   // to verify whether the unit test really execute SomeSubMethod()

    public void SomeMethod()
    {
        SomeSubMethod();
    }

    public virtual void SomeSubMethod()
    {
        // do a lot of weird stuff
        int x = 10; 
    }
}

測試是(請注意,我使用的是 NUnit 框架):

    [TestFixture]
    public class UnitTest1
    {
        [Test]
        public void Test2()
        {
            var myClass = Substitute.For<MyClass>();
            myClass.SomeMethod();
            myClass.Received(1).SomeSubMethod();
            Assert.That(myClass.x, Is.EqualTo(0));
        }
    }

由於目標測試方法 SomeSubMethod() 是一個虛方法,因此您不需要模擬 MyClass 類的部分。

這是你想要的嗎?

暫無
暫無

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

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