Reputation: 8761
I have a few unit tests that require files from the project to be used to run the unit tests. These files are just images. I need to get the image file using some kind of function within c#, other than pasting the full path like below.
string filePath = @"C:\Users\user1\Documents\Visual Studio 2008\Projects\app1\app1.Tests\Fakes\test_files\test-image.jpg";
I will prefer to do something like:
string filePath = app.path + "\Fakes\test_files\test-images.jpg"
How can I do that?
Thanks!
Upvotes: 2
Views: 2239
Reputation: 24167
If your question is about getting these files at runtime... you don't want to do this. You should be deploying these files somehow as part of your build process so that they end up in a predictable location, relative to your compiled binaries and other content.
In Visual Studio, you can set any project file's Copy to Output Directory property to have it place the file in your output folder.
Since it sounds like you want to get these files as part of your unit tests, you would want to use something like the MSTest attribute [DeploymentItem]
instead. This will place the files in your test directory at runtime. Read about Test Deployment on MSDN.
Upvotes: 2
Reputation: 4400
I dislike the above top-rated answer, because it doesn't answer the original question.
There are legitimate reasons to want to obtain the root path of an ASP.NET webapp, including MVC variety. For example, I need it so that I can pass in a 'URI pattern' which an XSL transform later uses to resolve a dynamically served XML document (using Xpath document function).
For the complete URI, you can perform a string operation on this.Request.Url.AbsoluteUri from within your controller/page.
Use this.Request.Path for the path to current or this.Request.ApplicationPAth for the root path of the application.
Upvotes: 0
Reputation: 639
Just to be clear, this would not be a unit test. A unit test should not rely on the environment. Anything in a database, a file system, etc. should not be used. A unit test should only be used to test a single unit of code. This is due to the fact that if anyone pulls down the source and runs the unit tests (the first thing you should do after getting the source) it will not run. They have to have the environment set up before the tests will pass. These are referred to as integration tests.
That being said, you could set up a variable if it is just in one class or an app.config if it is throughout multiple classes. You could then add a path in there as the default path and use that as "app.path".
Upvotes: 0