Typically, this isn't done by mocking those classes directly, but
rather by wrapping those classes in interfaces and then mocking said
interfaces. For example, consider the following code (I'm not claiming
this is good code - just a way to use and fix things that you're
trying):
public boolean DeleteTemporaryFiles()
{
boolean result = false;
File rootDir = Environment.getRootDirectory(); // This line sucks
because it can't be mocked
File[] files = rootDir.listFiles();
for(File file : files)
{
if (file.getName() == "tmp.txt")
{
result = file.delete();
}
}
return result;
}
So how do you get around the issue of having the
Environment.getRootDirectory() call in there? The easiest way is to
create a simple interface like so:
public interface EnvironmentWrapper
{
File getRootDirectory();
// ... other required functions
}
public boolean DeleteTemporaryFiles(EnvironmentWrapper
environment)
{
boolean result = false;
File rootDir = environment.getRootDirectory(); // Now you depend
on an interface, not the static class. This is called dependency
inversion, because you're pushing the dependency to the caller of the
function, which is "above" this one.
File[] files = rootDir.listFiles();
for(File file : files)
{
if (file.getName() == "tmp.txt")
{
result = file.delete();
}
}
return result;
}
You can take this further, such as with mocking the File calls and
what not, but it may not be necessary in your particular case.
Kyle
On Jun 13, 8:46 am, Sunil Chandra <[email protected]> wrote:
> Hi All,
>
> > I am pretty new to Android and trying to write an application that stores
> > some data on external storage.
> > I figure that Environment.getxxxState are the functions to check before
> > assuming their presence.
>
> > Now, since these are system enforced objects, how do I mock them for
> > testing various scenarios without actually using a phone.
> > (Another reason to not rely on physical device is that certain phone e.g.
> > Nexus S do not support removal of external storage and I have already made
> > that choice :( )
>
> > Regards,
> > Sunil
--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en