0

I am trying to load a json file while mocking an api for testing purposes in a test project.The mock will be loading the json.

enter image description here

I am currently using File.ReadAllText and i have tried the following

System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(), "bank_response.json")

System.IO.Path.GetFullPath(Directory.GetCurrentDirectory() + @"\bank_response.json"); I am getting either the path to bin or null.

user2650277
  • 6,289
  • 17
  • 63
  • 132
  • The json file might be in your bin folder. You need to include it in the compilation files – billybob Sep 24 '19 at 18:50
  • I don't want to put in bin directory as i am running my test suite and the json is part of the project itself – user2650277 Sep 24 '19 at 18:52
  • If you are testing a Web API, you can use `ContentRootPath` variable, You can inject `IHostingEnvironment` to retrieve it. – billybob Sep 24 '19 at 18:56
  • https://stackoverflow.com/a/51293454/1504370 – billybob Sep 24 '19 at 18:57
  • 3
    Did you set for `bank_response.json` file in properties to be copied to output directory? `File Properties -> Copy to Output Directory -> Copy always` – Alexander Goldabin Sep 24 '19 at 19:01
  • @AlexanderGoldabin he seems that he does not want to copy it... – billybob Sep 24 '19 at 19:03
  • So the json file is actually a shortcut to somewhere else on the file system? Why don't you want to output it to the bin directory, since you reference it anyway? – Ralph Willgoss Sep 24 '19 at 19:06
  • 3
    The issue is that your app isn't running from the project directory; it runs from the bin directory, because that's where the compiled app goes after build. Therefore, files you want to reference relative to your app root *also* need to be copied to bin as part of the build. That's how things work. You'd have the same issue after publishing. – Chris Pratt Sep 24 '19 at 19:11
  • @billybob doesn't `ContentRootPath` point to build folder as well where won't be json file, because it not included (UPD: what @chris-pratt said)? – Alexander Goldabin Sep 24 '19 at 19:13
  • @AlexanderGoldabin and @Chris Pratt i forgot about the copy to output settings.Thanks for reminding and btw `System.AppDomain.CurrentDomain.BaseDirectory` worked for me since my app isn't a console but a API. – user2650277 Sep 24 '19 at 19:14

0 Answers0