【问题标题】:Constructor and Unit Testing构造函数和单元测试
【发布时间】:2015-09-02 11:59:32
【问题描述】:

我有一堂课XmlRecord。此类将处理读取/写入 xml 文件。目前,我对该课程有以下内容:

class XmlRecord {
   private val _file = new File("file.xml")
}

如果文件不存在,我希望这个类以某种方式创建文件。我知道如何实现这一点,但我不确定如何以面向对象的方式设计它。我想我有两个选择:

  1. 我是否向构造函数(或对私有方法的调用)添加代码,如果该文件不存在,它将自动创建该文件。我对这种方法的问题是我如何对它进行单元测试,因为这段代码实际上是私有代码?我是否必须注入 File 依赖项以便在测试期间对其进行模拟?

  2. 我是否让构造函数返回异常或实现类的公共方法,以便调用者可以使用它来检查是否需要创建文件?如果是这样,调用者将调用另一个创建文件的公共方法。我再次认为我需要注入依赖项。

我希望这是有道理的。我只是想更好地掌握如何设计我的课程。

【问题讨论】:

  • 不确定 ctor 是不是最好的地方

标签: scala class unit-testing


【解决方案1】:
The presence of abstractions to accomplish DIP have other design
implications in an Object Oriented program:

All member variables in a class must be interfaces or abstracts.
All concrete class packages must connect only through interface/abstract classes packages.
No class should derive from a concrete class.
No method should override an implemented method.[5]
All variable instantiation requires the implementation of a Creational pattern as the Factory Method or the Factory pattern, or the more complex use of a Dependency Injection framework.

Dependency inversion principle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多