我的第一个编程工作向我介绍了单元测试和模拟对象的概念,但总觉得有些问题。如何编写模拟对象?
比方说,我们正在编写一个银行应用程序,并嘲笑一个的BankAccount对象所需:
// boilerplate code
public interface IBankAccount {
void Deposit(int amount);
void Withdrawal(int amount);
int getBalance();
int getAccountNumber();
}
public interface IBankAccountFactory {
IBankAccount getAccount(int accountNumber);
}
public class ProductionBankAccountFactory implements IBankAccountFactory {
public IBankAccount getAccount(int accountNumber) {
return new RealBankAccount(accountNumber);
}
}
public class MockBankAccountFactory implements IBankAccountFactory {
public IBankAccount getAccount(int accountNumber) {
return new MockBankAccount(accountNumber);
}
}
public static class BankAccountFactory {
// ewww, singletons!
public static IBankAccountFactory Instance;
}
// finally, my actual business objects
public class MockBankAccount implements IBankAccount {
public MockBankAccount(int accountNumber) { ... }
// interface implementation
}
public class RealBankAccount implements IBankAccount {
public RealBankAccount(int accountNumber) { ... }
// interface implementation
}
每个类都有一个目的:
- 工厂和工厂接口存在的收官构造函数给我们的模拟和实物。
- 静态BankAccountFactory类允许我们在生产应用程序或测试的开始分别分配
BankAccountFactory.Instance
IRealBankAccountFactory或MockBankAccountFactory的实例。 - 一旦一切都设置正确,任何类可以简单地通过调用抢IBankAccount的一个实例:
BankAccountFactory.Instance.getAccount(accountNum);
这工作,但它在导致的样板代码很多。我不应该为每个我想模拟的课程写5个新课程。我相信有一个更简单的方法,所以我必须问SO社区:
有没有更好的或首选的方式来编写模拟对象?
[编辑补充:]我很欣赏的联系,以嘲讽和DI框架,但现在我正在一个500 KLOC应用,以及代码的至少60%由样板模拟的上述风格的类。
我只是想减少代码库的大小,而不需要为Yet-Another-Framework™重新编写大块代码,所以它可以帮助我更多地看到手工编写的模拟类。 :)