getMockContext().getFilesDir()="/dev/null" 导致测试用例出错
getMockContext().getFilesDir()="/dev/null" causing error in test case
我在 ContentProvider 中有一个方法可以将文件保存到 getFilesDir() 基本路径。
但是,在测试中:
getMockContext().getFilesDir()="/dev/null"
这会导致错误,因为 /dev/null 不是目录(我想文件不能保存在那个垃圾路径下)。
我可以模拟 getFilesDir() 到磁盘上的其他路径吗?
您可以使用 TemporaryFolder
在您的系统上生成一个临时文件夹,仅用于您的测试生命周期(它会在您的测试结束后自动删除)。
这是一个使用 Mockito 生成模拟的示例。
import org.junit.Before;
import org.junit.rules.TemporaryFolder;
import org.junit.Rule;
import static org.mockito.MockitoAnnotations.initMocks;
public class SampleTest {
@Rule public TemporaryFolder mTempFolder = new TemporaryFolder();
@Mock private Context mMockContext;
@Before
public void setUp() throws IOException {
initMocks(this);
when(mMockContext.getFilesDir()).thenReturn(mTempFolder.newFolder());
}
}
我在 ContentProvider 中有一个方法可以将文件保存到 getFilesDir() 基本路径。
但是,在测试中: getMockContext().getFilesDir()="/dev/null" 这会导致错误,因为 /dev/null 不是目录(我想文件不能保存在那个垃圾路径下)。
我可以模拟 getFilesDir() 到磁盘上的其他路径吗?
您可以使用 TemporaryFolder
在您的系统上生成一个临时文件夹,仅用于您的测试生命周期(它会在您的测试结束后自动删除)。
这是一个使用 Mockito 生成模拟的示例。
import org.junit.Before;
import org.junit.rules.TemporaryFolder;
import org.junit.Rule;
import static org.mockito.MockitoAnnotations.initMocks;
public class SampleTest {
@Rule public TemporaryFolder mTempFolder = new TemporaryFolder();
@Mock private Context mMockContext;
@Before
public void setUp() throws IOException {
initMocks(this);
when(mMockContext.getFilesDir()).thenReturn(mTempFolder.newFolder());
}
}