What does “to stub” mean in programming?

后端 未结 10 943
盖世英雄少女心
盖世英雄少女心 2020-12-12 10:06

For example, what does it mean in this quote?

Integrating with an external API is almost a guarantee in any modern web app. To effectively test such i

10条回答
  •  醉梦人生
    2020-12-12 10:27

    A stub is a controllable replacement for an Existing Dependency (or collaborator) in the system. By using a stub, you can test your code without dealing with the dependency directly.

    External Dependency - Existing Dependency:
    It is an object in your system that your code under test interacts with and over which you have no control. (Common examples are filesystems, threads, memory, time, and so on.)

    Forexample in below code:

    public void Analyze(string filename)
        {
            if(filename.Length<8)
            {
                try
                {
                    errorService.LogError("long file entered named:" + filename);
                }
                catch (Exception e)
                {
                    mailService.SendEMail("admin@hotmail.com", "ErrorOnWebService", "someerror");
                }
            }
        }
    

    You want to test mailService.SendEMail() method, but to do that you need to simulate an Exception in your test method, so you just need to create a Fake Stub errorService object to simulate the result you want, then your test code will be able to test mailService.SendEMail() method. As you see you need to simulate a result which is from an another Dependency which is ErrorService class object (Existing Dependency object).

提交回复
热议问题