【发布时间】:2017-07-18 05:36:38
【问题描述】:
我有一个需要进行单元测试的类。结构如下:
public class classToBeTested{
public returnType function1(){
//creation of variable V
return new classA(V).map();
}
}
classA类如下:
public class classA{
//Constructor
public returnType map(){
//Work
}
}
我正在使用 FunSuite、GivenWhenThen 和 EasyMock 在 Scala 中创建单元测试。
我的测试结构如下:
class classToBeTested extends FunSuite with GivenWhenThen with Matchers with EasyMockSugar {
test(""){
Given("")
val c = new classToBeTested()
expecting{
}
When("")
val returnedResponse = c.function1()
Then("")
//checking the returned object
}
}
期望中我需要写什么?
我该如何处理上述情况?
注意:不能使用 PowerMock。
回答: 谢谢,@亨利。经过大量搜索以及@Henri 重构代码提供的答案是处理这种情况的最佳方法。原因如下:
单元测试不能模拟由new 调用创建的对象(没有PowerMock)。因此,为了测试代码,我们需要根据要测试的类(这里是classToBeTested)中正在使用的类(这里是classA)中存在的条件编写单元测试。因此,在测试classToBeTested时,我们需要了解classA的功能和结构,并分别创建测试用例。
现在测试用例依赖于classA 中的方法结构,这意味着classToBeTested 和classA 是紧密耦合的。因此,通过 TDD 方法,我们需要重构代码。
在上面的例子中:
而不是使用
classA object = new classA(V);
最好将对象提供给方法(例如:在 Spring MVC 中自动装配classA object)。
接受建议。另外,如果有人可以给出更好的解释,请这样做。
【问题讨论】:
标签: scala unit-testing mocking scalatest easymock