我必须在一些现有的已设置代码中添加功能
class A(foo: Foo, bar: Bar) {
// stuff
def aMethod(){
// some setup
bMethod()
}
private def bMethod() {
// do some stuff
}
}
class ATest() {
val mockA = new ExtendsA(instance, foo, bar)
val results = mockA.aMethod()
// validate some stuff
}
class ExtendsA(instance: Instance, foo: Foo, bar: Bar) extends A(foo: Foo, bar: Bar) {
// override some stuff
}
我添加了一些必须在bMethod()期间执行的功能。这要求访问不受我们的代码控制并且无法在调试期间正确设置的数据,因此将其放入新类并进行了模拟。
class MoreFunctionality() {}
class A(foo: Foo, bar: Bar, moreFunctionality : MoreFunctionality = new MoreFunctionality()) {
// stuff
def aMethod(){
// some setup
bMethod()
}
private def bMethod() {
moreFunctionality.doNewStuff()
// do some stuff
}
}
class ATest() {
val mockMoreFunctionality = mock[MoreFunctionality]
doNothing().when(mockMoreFunctionality).doNewStuff()
val mockA = new ExtendsA(instance, foo, bar, mockMoreFunctionality)
val results = mockA.aMethod()
// validate some stuff
}
class ExtendsA(instance: Instance, foo: Foo, bar: Bar, mockMoreFunctionality: MoreFunctionality) extends A(foo, bar, mockMoreFunctionality) {
// override some stuff
}
我遇到的问题是,我似乎尝试的所有操作都忽略了MoreFunctionality类已被模拟并尝试使用实际方法的事实。我已经使用ockingDetails(obj).isMock()测试了该实例实际上是一个模拟实例。
我也尝试过重新排列它,以便该方法本身接受新类作为参数,这也行不通。
class MoreFunctionality() {}
class A(foo: Foo, bar: Bar) {
// stuff
def aMethod(moreFunctionality: MoreFunctionality){
// some setup
bMethod(moreFunctionality)
}
private def bMethod(moreFunctionality: MoreFunctionality) {
moreFunctionality.doNewStuff()
// do some stuff
}
}
class ATest() {
val mockMoreFunctionality = mock[MoreFunctionality]
doNothing().when(mockMoreFunctionality).doNewStuff()
val mockA = new ExtendsA(instance, foo, bar)
val results = mockA.aMethod(mockMoreFunctionality)
// validate some stuff
}
class ExtendsA(instance: Instance, foo: Foo, bar: Bar) extends A(foo, bar)
{
// override some stuff
}
我这里缺少什么吗?