android


Get context of test project in Android junit test case


Does anyone know how can you get the context of the Test project in Android junit test case (extends AndroidTestCase).
Note: The test is NOT instrumentation test.
Note 2: I need the context of the test project, not the context of the actual application that is tested.
I need this to load some files from assets from the test project.
There's new approach with Android Testing Support Library (currently com.android.support.test:runner:0.3) released.
#RunWith(AndroidJUnit4.class)
#MediumTest
public class SomeClassTest {
private Context instrumentationCtx;
#Before
public void setup() {
instrumentationCtx = InstrumentationRegistry.getContext();
}
#Test
public void someTest() {
...
If you want also app context run:
InstrumentationRegistry.getTargetContext();
Look here: What's the difference between getTargetContext() and getContext (on InstrumentationRegistry)?
After some research the only working solution seems to be the one yorkw pointed out already. You'd have to extend InstrumentationTestCase and then you can access your test application's context using getInstrumentation().getContext() - here is a brief code snippet using the above suggestions:
public class PrintoutPullParserTest extends InstrumentationTestCase {
public void testParsing() throws Exception {
PrintoutPullParser parser = new PrintoutPullParser();
parser.parse(getInstrumentation().getContext().getResources().getXml(R.xml.printer_configuration));
}
}
As you can read in the AndroidTestCase source code, the getTestContext() method is hidden.
/**
* #hide
*/
public Context getTestContext() {
return mTestContext;
}
You can bypass the #hide annotation using reflection.
Just add the following method in your AndroidTestCase :
/**
* #return The {#link Context} of the test project.
*/
private Context getTestContext()
{
try
{
Method getTestContext = ServiceTestCase.class.getMethod("getTestContext");
return (Context) getTestContext.invoke(this);
}
catch (final Exception exception)
{
exception.printStackTrace();
return null;
}
}
Then call getTestContext() any time you want. :)
You should extend from AndroidTestCase instead of TestCase.
AndroidTestCase Class Overview
Extend this if you need to access Resources or other things that depend on Activity Context.
AndroidTestCase - Android Developers
If you need just access to resources of your project you can use getActivity() method of ActivityInstrumentationTestCase2 class:
//...
private YourActivityClass mActivity;
#Override
protected void setUp() throws Exception {
//...
mActivity = getActivity();
}
//...
public void testAccessToResources() {
String[] valueList;
valueList =
mActivity.getResources().getStringArray(
com.yourporject.R.array.test_choices);
}
The other answers are outdated. Right now every time that you extend AndroidTestCase, there is mContext Context object that you can use.

Related Links

Android spinner prompt
How to finish activity from service class in android?
Can't i add android-17,android-18 etc platforms in android studio?
RSA Publickey implemenation in android
What i should write in Pro-guard Files to stop reverse engineering android?
CreateProcess error=206, The filename, or extension is too long
GPS code returning last location
User Defined Target in Rajwali-Vuforia
Android widget listview swipe to remove item
my page does not display all the content on android
Passing a parameter in Raw SQL Ormlite
Android conditional permissions
FFmpeg in Android:UnsatisfiedLinkError: Cannot load library: reloc_library:cannot locat 'log2f'
LocationManager.requestLocationUpdates not responding
Retrieving data from SQLite android [duplicate]
My application has stopped sending tweets with images

Categories

HOME
notepad++
beautifulsoup
azure-stream-analytics
telegram
wakanda
github-for-windows
pagination
twig
jsf-2.2
graphics
grafana
ms-access-2016
title
bing-maps
project
commonjs
pega
android-securityexception
mod-security
redis-sentinel
cmdb
jsonpath
onedrive-api
android-intent
mongodb-csharp
screen-readers
entitymanager
null-pointer
html5-appcache
smartclient
apache2.4
googlebot
kendo-mobile
react-toolbox
jquery-callback
android-things
ceylon
gp
gitlab-api
record
deltaspike
gnat-gps
least-squares
c9.io
watchface
vmware-fusion
dcmtk
linqpad
logback-groovy
knime
wc
netbeans6.8
mach-o
mouseleave
template-toolkit
cmp
vcloud-director-rest-api
adafruit
nikeplus-api
dup
vorpal.js
observablecollection
mediametadataretriever
nss
kiosk
nullable
cycle2
assertion
opl
sciruby
dllimport
xvim
poppler
haskell-warp
sha512
fits
shopizer
theos
android-vibration
with-statement
winginx
dot42
websphere-esb
scringo
insert-id
windows-98
panda3d
os.system
stress
relative
exponentiation
tournament
umra
xui
collectionviewsource
diagrams
object-database
openfaces
cfwindow
pbcopy
appliance
commercial-application

Resources

Encrypt Message