让我们开始与模拟的状况的一个例子:
class Config {
Properties getProps() {
def props = new Properties()
props.setProperty(Constants.SERVER_TIMEZONE, 'America/Cambridge_Bay')
props
}
}
class Constants {
static String SERVER_TIMEZONE = 'TIMEZONE'
}
Config config = new Config()
def timeZoneID = config.getProps().getProperty(Constants.SERVER_TIMEZONE)
def tz = TimeZone.getTimeZone(timeZoneID)
assert tz.ID == 'America/Cambridge_Bay'
由于方法2()没有得到一个配置实例注入其中,模拟的功能出了问题。因此,我们将在类级别使用Groovy的metaClass(因为出于同样的原因,实例级别也不存在)。您可以覆盖Config.getProps()这样的:
Config.metaClass.getProps {
def props = new Properties()
props.setProperty(Constants.SERVER_TIMEZONE, 'Etc/UTC')
props
}
所以,你可以大致写你斯波克测试是这样的:
// import Constants
// import Config class
class FooSpec extends Specification {
@ConfineMetaClassChanges
def "test stuff"() {
when:
Config.metaClass.getProps {
def props = new Properties()
props.setProperty(Constants.SERVER_TIMEZONE, 'America/Cambridge_Bay')
props
}
// Do more stuff
then:
// Check results
}
}
PS
如果你可以修改方法2()要注入Config,那么您可以使用Groovy的MockFor,这样会更好。
你真的能想出一个完整的例子吗? –