Mocking method results

前端 未结 6 1583
情歌与酒
情歌与酒 2021-02-08 16:00

I\'m trying to find a way to fake the result of a method called from within another method.

I have a \"LoadData\" method which calls a separate helper to get some data a

6条回答
  •  忘了有多久
    2021-02-08 16:39

    I would recommend converting what you have into something like this:

    public class MyClass()
    {
        private IHelper _helper;
    
        public MyClass()
        {
            //Default constructor normal code would use.
            this._helper = new Helper();
        }
    
        public MyClass(IHelper helper)
        {
            if(helper == null)
            {
                throw new NullException(); //I forget the exact name but you get my drift ;)
            }
            this._helper = helper;
        }
    
        public void LoadData()
        {
            SomeProperty = this._helper.GetSomeData();
        }
        public object SomeProperty {get;set;}
    }
    

    Now your class supports what is known as dependency injection. This allows you to inject the implementation of the helper class and it ensures that your class need only depend on the interface. When you mock this know you just create a mock that uses the IHelper interface and pass it in to the constructor and your class will use that as though it is the real Helper class.

    Now if you're stuck using the Helper class as a static class then I would suggest that you use a proxy/adapter pattern and wrap the static class with another class that supports the IHelper interface (that you will also need to create).

    If at some point you want to take this a step further you could completely remove the default Helper implementation from the revised class and use IoC (Inversion of Control) containers. If thiis is new to you though, I would recommend focusing first on the fundamentals of why all of this extra hassle is worth while (it is IMHO).

    Your unit tests will look something like this psuedo-code:

    public Amazing_Mocking_Test()
    {
        //Mock object setup
        MockObject mockery = new MockObject();
        IHelper myMock = (IHelper)mockery.createMockObject();
        mockery.On(myMock).Expect("GetSomeData").WithNoArguments().Return(Anything);
    
        //The actual test
        MyClass testClass = new MyClass(myMock);
        testClass.LoadData();
    
        //Ensure the mock had all of it's expectations met.
        mockery.VerifyExpectations();
    }
    

    Feel free to comment if you have any questions. (By the way I have no clue if this code all works I just typed it in my browser, I'm mainly illustrating the concepts).

提交回复
热议问题