}
// OuterObjects.java
package com.factorymethod.demo;
public class OuterObjects implements BaseObjects {
public void func() {
System.out.println("OuterObjects.func");
}
}
// LogicToBeTested.java, code to be tested
package com.factorymethod.demo;
public class LogicToBeTested {
public void doSomething() {
BaseObjects b = createBase();
b.func();
}
public BaseObjects createBase() {
return newOuterObjects();
}
}
以下则是对应的 MockOuterObjects、MockFactory 以及单元测试的实现: // MockOuterObjects.java
package com.factorymethod.demo;
public class MockOuterObjects implements BaseObjects {
public void func() {
System.out.println("MockOuterObjects.func");
}
}
// MockLogicToBeTested.java
package com.factorymethod.demo;
public class MockLogicToBeTested extends LogicToBeTested {
public BaseObjects createBase() {
return new MockOutterObjects();
}
}
// LogicTest.java
package com.factorymethod.demo;
import junit.framework.TestCase;
public class LogicTest extends TestCase {
LogicToBeTested c;
protected void setUp() {
c =new MockLogicToBeTested();
}
public void testDoSomething() {
c.doSomething();
}
}
文章来源于领测软件测试网 https://www.ltesting.net/