How do you test private methods with NUnit?

后端 未结 13 2430
春和景丽
春和景丽 2020-12-02 16:00

I am wondering how to use NUnit correctly. First, I created a separate test project that uses my main project as reference. But in that case, I am not able to test private m

13条回答
  •  臣服心动
    2020-12-02 17:00

    In theory of Unit Testing only contract should be tested. i.e. only public members of the class. But in practice developer usually wants to test internal members to. - and it is not bad. Yes, it goes against the theory, but in practice it can be useful sometimes.

    So you if really want to test internal members you can use one of these approaches:

    1. Make your member public. In many books authors suggest this approach as simple
    2. You can make you members internal and add InternalVisibleTo to assebly
    3. You can make class members protected and inherit your test class from your under testing class.

    Code example (pseudo code):

    public class SomeClass
    {
        protected int SomeMethod() {}
    }
    [TestFixture]
    public class TestClass : SomeClass{
    
        protected void SomeMethod2() {}
        [Test]
        public void SomeMethodTest() { SomeMethod2(); }
    }
    

提交回复
热议问题