C #: How is a unit test method that relies on another method within the same class?

I have a class similar to the following:

public class MyProxy : ClientBase<IService>, IService
{
    public MyProxy(String endpointConfiguration) :
        base(endpointConfiguration) { }

    public int DoSomething(int x)
    {
        int result = DoSomethingToX(x); //This passes unit testing

        int result2 = ((IService)this).DoWork(x)

        //do I have to extract this part into a separate method just
        //to test it even though it only a couple of lines?
        //Do something on result2
        int result3 = result2 ...

        return result3;
    }

    int IService.DoWork(int x)
    {
        return base.Channel.DoWork(x);
    }
}

The problem is that when testing, I don’t know how to mock the result2 element without extracting the part that gets result3 using result2 into a separate method. And, since this is unit testing, I don’t want to go deeper to check which result2 is returned ... I would rather mock the data somehow ..., could call a function and replace it with one call.

+3
source share
5 answers

Follow these steps:

Set the IService property, for example:

public IService MyService { get; set; }

: int result2 = MyService.DoWork(x) , - -, MyService = this;

, accessors.

+1

. :

  • MyProxy DoWork,
  • "", ,
  • DoWork , ,
+2

, Microsoft Research

Once you run it, you can do the following

MMyProxy.DoWork32 = () => put your mock result here.

Remember to set moleBehavior to fail for uncommitted methods.

0
source

I believe that you have a design problem, your IService.DoWork should most likely live in a different class, it looks like a thin shell for something else. Have you considered refactoring it?

Then, if he lives in a different class, you do not need special treatment for ridicule.

0
source

Source: https://habr.com/ru/post/1784187/


All Articles