Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jifang
Last active April 17, 2018 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jifang/26a46b3c31cf9ac20a665208ababc2f6 to your computer and use it in GitHub Desktop.
Save jifang/26a46b3c31cf9ac20a665208ababc2f6 to your computer and use it in GitHub Desktop.
Android test for creating files in multiple threads
package com.example.jifang.testio;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static junit.framework.Assert.assertFalse;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
private static final String TAG = "IO_Test";
private static final int TEST_NUMBER = 100;
private static final int TEST_THREAD = 2;
private Object lock = new Object();
@Test
public void testCreatingFiles() throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(TEST_THREAD);
final CountDownLatch signal = new CountDownLatch(TEST_THREAD);
Context appContext = InstrumentationRegistry.getTargetContext();
final File folder = new File(appContext.getExternalFilesDir(null), "test");
if (!folder.exists() && !folder.mkdirs()) {
Log.e(TAG, "Failed to create folder");
}
for (File file: folder.listFiles()) {
if (!file.delete()) {
Log.e(TAG, "Failed to delete:" + file.getAbsolutePath());
}
}
Log.i(TAG, "Testing folder:" + folder.getAbsolutePath());
final AtomicInteger index = new AtomicInteger(0);
final AtomicBoolean failed = new AtomicBoolean(false);
for (int i = 0; i < TEST_THREAD; ++i) {
executor.submit(new Runnable() {
@Override
public void run() {
while (index.get() < TEST_NUMBER && !failed.get()) {
int filename = index.getAndIncrement();
File testFile = new File(folder, String.valueOf(filename));
try {
Log.v(TAG, "Creating file: " + filename);
// synchronized (lock) { // Add a lock will make test pass
testFile.createNewFile();
// }
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Failed to create file: " + testFile.getAbsolutePath());
failed.set(true);
signal.countDown();
}
}
signal.countDown();
}
});
}
signal.await();
assertFalse("Test failed", failed.get());
Log.i(TAG, "Test finished");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment