the*_*man 7 java unit-testing guava
番石榴中的许多功能都是由静态方法提供的.我还没有弄清楚如何合并使用番石榴库和良好的依赖注入实践.
例如,如果我要使用
Files.readLines(File, Charset)
Run Code Online (Sandbox Code Playgroud)
然后我发现我很难编写一个不接触文件系统的单元测试,我只想进行集成测试.
我想我可以为我感兴趣的所有人写一个适配器吗?但这可能最终会成为很多工作......
我觉得很奇怪,番石榴库来自同一组提供吉斯人,写博客帖子喜欢这
您可以将静态依赖项隔离到它自己的方法中(然后可以出于测试目的覆盖该方法,如下所示)。通常,隔离方法具有“受保护”的可见性。
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
public class FileUtilsTest {
private static final String[] TEST_LINES = { "test 1", "test 2", "test 3" };
private static final File TEST_FILE = new File("/foo/bar");
private FileUtils fileUtils;
/**
* Configure reusable test components
*/
@Before
public void setUp() {
fileUtils = spy(new FileUtils());
when(fileUtils.getLines(any(File.class))).thenReturn(TEST_LINES);
}
/**
* Ensure the {@link FileUtils#countLines(File)} method returns the correct line count (without hitting the
* file-system)
*/
@Test
public void testCountLines() {
assertEquals(3, fileUtils.countLines(TEST_FILE));
}
/**
* The class we want to test
*/
public static class FileUtils {
/**
* Method that we want to test
*/
public int countLines(final File file) {
return getLines(file).length;
}
/**
* Static dependency isolated to a method (that we can override, for test purposes)
*/
public String[] getLines(final File file) {
return Files.readLines(file);
}
}
/**
* Poorly written utility class with hard-to-test static methods
*/
public static class Files {
public static String[] readLines(final File file) {
// In reality, this would hit the file-system
return new String[] { "line 1" };
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2110 次 |
| 最近记录: |