重构静态方法/静态字段以进行测试
-
05-07-2019 - |
题
我有以下遗留代码:
public class MyLegacyClass
{
private static final String jndiName = "java:comp/env/jdbc/LegacyDataSource"
public static SomeLegacyClass doSomeLegacyStuff(SomeOtherLegacyClass legacyObj)
{
// do stuff using jndiName
}
}
该类在 J2EE 容器中工作。
现在我想在容器之外测试该类。
最好的策略是什么?重构基本上是允许的。
允许访问 LegacyDataSource(测试不必是“纯”单元测试)。
编辑:不允许引入额外的运行时框架。
解决方案
只是为了使 @Robin 对策略模式的建议更加具体:(请注意,您原始问题的公共 API 保持不变。)
public class MyLegacyClass {
private static Strategy strategy = new JNDIStrategy();
public static SomeLegacyClass doSomeLegacyStuff(SomeOtherLegacyClass legacyObj) {
// legacy logic
SomeLegacyClass result = strategy.doSomeStuff(legacyObj);
// more legacy logic
return result;
}
static void setStrategy(Strategy strategy){
MyLegacyClass.strategy = strategy;
}
}
interface Strategy{
public SomeLegacyClass doSomeStuff(SomeOtherLegacyClass legacyObj);
}
class JNDIStrategy implements Strategy {
private static final String jndiName = "java:comp/env/jdbc/LegacyDataSource";
public SomeLegacyClass doSomeStuff(SomeOtherLegacyClass legacyObj) {
// do stuff using jndiName
}
}
...和 JUnit 测试。我不太喜欢进行这种设置/拆卸维护,但这是基于静态方法(或单例)的 API 的一个不幸的副作用。我什么 做 就像这个测试一样,它不使用 JNDI - 这很好,因为 (a) 它会运行得很快,并且 (b) 单元测试无论如何都应该只测试 doSomeLegacyStuff() 方法中的业务逻辑,而不是测试实际的数据源。(顺便说一句,这假设测试类与 MyLegacyClass 位于同一包中。)
public class MyLegacyClassTest extends TestCase {
private MockStrategy mockStrategy = new MockStrategy();
protected void setUp() throws Exception {
MyLegacyClass.setStrategy(mockStrategy);
}
protected void tearDown() throws Exception {
// TODO, reset original strategy on MyLegacyClass...
}
public void testDoSomeLegacyStuff() {
MyLegacyClass.doSomeLegacyStuff(..);
assertTrue(..);
}
static class MockStrategy implements Strategy{
public SomeLegacyClass doSomeStuff(SomeOtherLegacyClass legacyObj) {
// mock behavior however you want, record state however
// you'd like for test asserts. Good frameworks like Mockito exist
// to help create mocks
}
}
}
其他提示
重构代码以使用依赖注入。然后使用您首选的DI框架(Spring,Guice,...)来注入您的资源。这样可以在运行时轻松切换资源对象和策略。
在这种情况下,您可以注入数据源。
编辑:根据您的新限制,您可以通过使用策略模式在运行时设置数据源来完成相同的任务。您可以只使用属性文件来区分创建和提供数据源的策略。这将不需要新的框架,您只需手动编码相同的基本功能。在Java EE容器外部进行测试时,我们使用ServiceLocator提供了一个模拟数据源。
我认为这里最好的解决方案是将JNDI绑定到本地
旧版代码正在使用jndiName:
DataSource datasource = (DataSource)initialContext.lookup(DATASOURCE_CONTEXT);
所以,这里的解决方案是将本地(或者你拥有的任何测试数据)绑定到这样的JNDI中:
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(System.getProperty("driverClassName"));
dataSource.setUser("username");
dataSource.setPassword("password");
dataSource.setServerName("localhost");
dataSource.setPort(3306);
dataSource.setDatabaseName("databasename");
然后是绑定:
Context context = new InitialContext();
context.bind("java:comp/env/jdbc/LegacyDataSource",datasource);
或类似的东西,希望能帮到你。
祝你好运!不隶属于 StackOverflow