public class A {
public void action() {
....
//findSomeThingThroghClassB logic;
....
}
}
先把A中需要B的部分findSomeThingThroghClassB logic提取成一个protected方法
public class A {
public void action() {
....
findSomeThingThroghClassB();
....
}
protected void findSomeThingThroghClassB() {
//findSomeThingThroghClassB logic;
}
}
然后在TestCase中创建A时
A a = new A() {
protected void findSomeThingThroghClassB() {
mockIt();
}
}
这样在测试中就可以直接使用mock了。
相比其它方法,这种方法对A类的改动较小,而且不需要新增类变量。
public void action() {
....
//findSomeThingThroghClassB logic;
....
}
}
先把A中需要B的部分findSomeThingThroghClassB logic提取成一个protected方法
public class A {
public void action() {
....
findSomeThingThroghClassB();
....
}
protected void findSomeThingThroghClassB() {
//findSomeThingThroghClassB logic;
}
}
然后在TestCase中创建A时
A a = new A() {
protected void findSomeThingThroghClassB() {
mockIt();
}
}
这样在测试中就可以直接使用mock了。
相比其它方法,这种方法对A类的改动较小,而且不需要新增类变量。
博客介绍了优化类A测试的方法。先将类A中依赖类B的逻辑提取成protected方法,再在测试用例中创建类A的实例时重写该方法实现Mock。此方法对类A改动小,且无需新增类变量,便于测试。
18

被折叠的 条评论
为什么被折叠?



