MakeDirectoryObservable { public Observable<File> create(final File rootDirectory, final String directoryName) { return Observable.create(new ObservableOnSubscribe<File>() { @Override public void subscribe(@NonNull ObservableEmitter<File> e) throws Exception { if (!rootDirectory.canWrite()) { e.onError(new PermissionDeniedException()); } File newDirectory = new File(rootDirectory, directoryName); if (newDirectory.exists()) { e.onError(new DirectoryExistsException()); } else { boolean isDirectoryCreated = newDirectory.mkdir(); if (isDirectoryCreated) { e.onNext(newDirectory); e.onComplete(); } else { e.onError(new IOException()); } } } }); }  Observable<File> create(final File rootDirectory, final String directoryName);  }
@Test public void shouldThroughPermissionDeniedExceptionIfRootFolderNotWritable() throws Exception { File stubRootDirectory = mock(File.class); when(stubRootDirectory.canWrite()).thenReturn(false); sut.create(stubRootDirectory, "fileName") .subscribeOn(Schedulers.trampoline()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(mockObserver); verify(mockObserver).onError(any(PermissionDeniedException.class)); verify(mockObserver, never()).onComplete(); }
@Test public void shouldThroughDirectoryExistsException() throws Exception { File rootDirectory = ShadowEnvironment.getExternalStorageDirectory(); String folderName = "folderName"; createDirectory(rootDirectory, folderName); sut.create(rootDirectory, folderName) .subscribeOn(Schedulers.trampoline()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(mockObserver); verify(mockObserver).onError(any(DirectoryExistsException.class)); verify(mockObserver, never()).onComplete(); }
@Test public void shouldMakeDirectory() throws Exception { File rootDirectory = ShadowEnvironment.getExternalStorageDirectory(); String folderName = "folderName"; sut.create(rootDirectory, folderName) .subscribeOn(Schedulers.trampoline()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(mockObserver); ArgumentCaptor<File> argumentCaptor = ArgumentCaptor.forClass(File.class); verify(mockObserver).onNext(argumentCaptor.capture()); verify(mockObserver).onComplete(); assertEquals(rootDirectory.toString() + File.separator + folderName, argumentCaptor.getValue().getAbsolutePath()); }