如何避免全局状态? [英] How can I avoid global state?

查看:89
本文介绍了如何避免全局状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在阅读Google测试博客,它说全局状态不好,很难编写测试.我相信-我的代码现在很难测试.那么如何避免全局状态?

So, I was reading the Google testing blog, and it says that global state is bad and makes it hard to write tests. I believe it--my code is difficult to test right now. So how do I avoid global state?

我使用全局状态(据我了解)最大的用途是管理开发,验收和生产环境之间的关键信息.例如,我有一个名为"Globals"的静态类,其静态成员为"DBConnectionString".当应用程序加载时,它确定要加载的连接字符串,并填充Globals.DBConnectionString.我在Globals类中加载文件路径,服务器名称和其他信息.

The biggest things I use global state (as I understand it) for is managing key pieces of information between our development, acceptance, and production environments. For example, I have a static class named "Globals" with a static member called "DBConnectionString." When the application loads, it determines which connection string to load, and populates Globals.DBConnectionString. I load file paths, server names, and other information in the Globals class.

我的某些功能依赖于全局变量.因此,在测试功能时,我必须记住首先设置某些全局变量,否则测试将失败.我想避免这种情况.

Some of my functions rely on the global variables. So, when I test my functions, I have to remember to set certain globals first or else the tests will fail. I'd like to avoid this.

是否有管理状态信息的好方法? (还是我对全球状态的理解不正确?)

Is there a good way to manage state information? (Or am I understanding global state incorrectly?)

推荐答案

依赖注入是您想要的.而不是让那些函数消失并寻找它们的依赖关系,而是将依赖关系注入到函数中.也就是说,当您调用函数时,将它们想要的数据传递给它们.这样一来,就可以轻松地围绕类放置测试框架,因为您可以在适当的地方简单地注入模拟对象.

Dependency injection is what you're looking for. Rather than have those functions go out and look for their dependencies, inject the dependencies into the functions. That is, when you call the functions pass the data they want to them. That way it's easy to put a testing framework around a class because you can simply inject mock objects where appropriate.

很难避免某些全局状态,但是做到这一点的最佳方法是在应用程序的最高级别使用工厂类,而低于该最高级别的所有内容都基于依赖项注入.

It's hard to avoid some global state, but the best way to do this is to use factory classes at the highest level of your application, and everything below that very top level is based on dependency injection.

有两个主要好处:一,测试要容易得多,二,应用程序之间的连接松散得多.您依赖于能够针对类的接口进行编程,而不是针对其实现.

Two main benefits: one, testing is a heck of a lot easier, and two, your application is much more loosely coupled. You rely on being able to program against the interface of a class rather than its implementation.

这篇关于如何避免全局状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆