Hi @Anonymous thanks for the reply, I am gonna share some more code.
LookupController
[ApiController]
[Route("api/[controller]")]
public class LookupController : ControllerBase
{
private readonly ILogger<LookupController> _logger;
private readonly IWebHostEnvironment _hostEnvironment;
public LookupController(ILogger<LookupController> logger, IWebHostEnvironment hostEnvironment)
{
_logger = logger;
_hostEnvironment = hostEnvironment;
}
[HttpPost("city-info")]
public ActionResult<IEnumerable<CityInfoResource>> LookupCityInfo([FromBody] IEnumerable<string> ips)
{
//...
using var reader = new DatabaseReader(Path.Combine(_hostEnvironment.ContentRootPath, "Data/my-file.mmdb"));
//...
}
}
LookupControllerTests
[TestFixture]
public class LookupControllerTests
{
private readonly Mock<ILogger<LookupController>> _logger;
private readonly Mock<IWebHostEnvironment> _hostEnvironment;
public LookupControllerTests()
{
_logger = new Mock<ILogger<LookupController>>();
_hostEnvironment = new Mock<IWebHostEnvironment>();
}
[Test]
public void Test_CityLookup_With_Valid_IPs()
{
//...
var controller = new LookupController(_logger.Object, _hostEnvironment.Object);
var response = controller.LookupCityInfo(ips);
//...
}
}
The problem is with Path.Combine(_hostEnvironment.ContentRootPath, "Data/my-file.mmdb")
When I run the app, the ContentRootPath
is "R:\\Demos\\1\\ip-lookup-app"
and the file is found.
When I run the tests, the ContentRootPath
is always null.
I already found that thread yesterday, but I could not solve it, I always got it null.
So for now I just copied the same file and folder under the Tests project and changed the controller to using var reader = new DatabaseReader("./Data/GeoLite2-City.mmdb");
so basically the path is relative to either project, but of course it's a bad solution.