0

I want to read a mock RSS feed file to test against in a Xamarin NUnit test for an Android app. The test class has no context so I can't put the file in the Assets folder and do this:

System.IO.Stream strIn = instanceOfAssetManager.Open(feedFile);

It also has no ancestor, so I can't do this:

System.IO.Stream strIn = this.Class.ClassLoader.ResourceAsStream(feedFile);

Any suggestions how I can get to the jolly thing?

This case solved a similar problem for a different platform/setup: Storing test files in the test project

Community
  • 1
  • 1
Jannie Theunissen
  • 28,256
  • 21
  • 100
  • 127
  • Have you tried to let the test class derived from `Android.Test.InstrumentationTestRunner` and then call `TargetContext.Resources.Assets.Open("feedFile)`? – Aaron He Oct 07 '13 at 17:31
  • @Aaron my test app bombs out with a "Java.Lang.NoClassDefFoundError" when I derive from `Android.Test.InstrumentationTestRunner`. It looks like it is not compatible with NUnitLite – Jannie Theunissen Oct 08 '13 at 06:28

2 Answers2

5

The test class has no context so I can't put the file in the Assets folder and do this:

Is there a reason you need to use Android Assets? Using .NET Embedded Resources by setting the file's Build action to EmbeddedResource permits greater portability -- it's present on all .NET platforms -- and neatly sidesteps the Android Context issue.

If you need to use Android Assets, then you can use the Android.App.Application.Context property, which is equivalent to the Context.ApplicationContext property, except static and available everywhere.

jonp
  • 13,512
  • 5
  • 45
  • 60
  • Thank you for the guidance, Jon. I have set the build action to `EmbeddedResource`, but I am tripping over the syntax. I can see that the following file is created: `../obj/Debug/SpotlightTests.Assets.appfeed.xml`, but if I try to read it with `Android.App.Application.Context.Resources.Assets.Open()` as either just `appfeed.xml` or with the path-dotted syntax as the MS docs says `SpotlightTests.Assets.appfeed.xml` I get a FileNotFound exception. – Jannie Theunissen Oct 08 '13 at 14:16
  • If you use `EmbeddedResource`, you need to use [Assembly.GetManifestResourceStream()](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcestream.aspx), e.g. `typeof(Something).Assembly.GetManifestResourceStream("name")`. – jonp Oct 08 '13 at 15:25
0

Check properties of the file. I had to set "Build Action" to AndroidAsset and than you can use instanceOfAssetManager.Open(feedFile);

iwanlenin
  • 210
  • 4
  • 11