简体   繁体   中英

Directory.GetCurrentDirectory Throwing System.IO.DirectoryNotFoundException in unit tests

Im reinciving the following error: System.IO.DirectoryNotFoundException when the function that i am testing uses Directory.GetCurrentDirectory()

I would like to know if exists a way to mock the method or change the Directory.GetCurrentDirectory() return. Im open to suggestions..

I can't post the complete code but its something like this:

[Fact]
public async Task someMethod()
{
    // Arrange
    var userData = new userData
    {
        Email = "test@test.com"
    };

    _someRepository.Setup(x => x.GetSomething(It.IsAny<string>())).ReturnsAsync(Faker());

    var service= new Service();

    // Act
    var result = await service.TestedMethod(userData);

    // Assert
    Assert.False(result.Success);
}

public class Service
{

    public async Task<ReponseViewModel> TestedMethod(userData vm)
    {
        var anything = await _someRepository.GetSomething(vm.Email);
        
        var template = GetTemplate(url);

        return something;
    }

    private string GetTemplate(string url)
    {
        var template = File.ReadAllText(
                        Path.Combine(
                            Directory.GetCurrentDirectory(),
                            "wwwroot",
                            "html",
                            "myfile.html"));

        return template;
    }
}

The issue might be that the unit test runner is executed from a different location than the project output directory. That's why Directory.GetCurrentDirectory() method can return a path that is not expected by your code.

If the test assembly is located in the same folder as the production one, you can try to modify your GetTemplate(string url) method to fetch the executing assembly location instead of trying to fetch current directory:

private string GetTemplate(string url)
{
    var assemblyPath = Assembly.GetExecutingAssembly().Location;
    var template = File.ReadAllText(
                    Path.Combine(
                        assemblyPath,
                        "wwwroot",
                        "html",
                        "myfile.html"));

    return template;
}

If the executing assembly does not help, try Assembly.GetAssembly(Type type) version. For the type argument, you can try any type from the production assembly.

Another suggestion would be to get and provide a relative or an absolute path to the template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM