我参考下面的博客来理解紧耦合/松耦合。 我理解给出的例子,
interface PaymentGateway {
fun authenticate()
fun processPayment(amount: Double)
fun sendConfirmation()
}
class PayPalGateway: PaymentGateway {
// Implementation of PayPalGateway
}
class PaymentProcessor(private val paymentGateway: PaymentGateway) {
fun processPayment(amount: Double) {
paymentGateway.authenticate()
paymentGateway.processPayment(amount)
paymentGateway.sendConfirmation()
}
}
但我不明白它如何帮助博客中的状态进行单元测试,
- 更好的可测试性:松散耦合的组件更容易独立隔离和测试,从而实现更全面的单元 测试和更轻松的集成测试。
人们可以从接口名称
PaymentGateway
推断出该接口的方法将通过网络执行操作,甚至可能是第三方调用甚至不在您控制范围内的东西。如果该组件不是松散耦合的,而是硬编码到 PaymentProcessor
中,那么为 PaymentProcessor
创建单元测试基本上是不切实际的。但由于松散耦合的设计,您可以自由创建单元测试,在其中传递模拟 PaymentGateway
,该模拟要么 (a) 不执行任何操作,或者更有用的是 (b) 执行有助于测试的操作。作为后者的一个例子,比如说你有这个单元测试:Confirm authentication is done before processing payment
然后在您的
PaymentGateway
模拟中,您可以使
authenticate
方法将其名称“authenticate”压入堆栈,并类似地使
processPayment
将其名称“processPayment”压入同一堆栈。
然后,在调用 PaymentProcessor.processPayment
后,您只需要检查堆栈中这些项目的顺序即可。