Search code examples
c#configurationmstest

c# mstest test the method that query database throws a FileNotFoundException when it was reading config


i want to create a test project and import a solution(solution A) so that i don't need to add a test project in the solution. I want to separate the test project and others because i don't want SVN know I have created it.

When I test a method that query data from database by Entity Framwork. It throws an Exception:

Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=*************'. The system cannot find the file specified.

But i check the Dependencies->SDK->Microsoft.NETCore App(2.1) , i found System.Configuration.dll.

What's happening to me? I search in stack overflow, and try to copy the config to test project from the solution A. But it doesn't work.


Solution

  • I found two reason:

    1. I use a .net core project(the test project) to call a method in standard ,net framework project.
    2. All test project need to install ConfigurationManager in Nuget.

    ====================== UPDATE MY ANSWER ABOVE =================

    I gave up to use mstest to do it.

    I found another way to do but it seems a bit stupid.I directly wrote test method in controller.

    First, declare a TestBean.

    public TestBean(string name, string suppose, string fact, object msg = null)
    {
        this.name = name;
        this.suppose = suppose;
        this.fact = fact;
        pass = suppose == fact;
        if (SHOW_MSG)
            this.msg = msg;
        else
            this.msg = null;
    }
    

    Use the bean like this in controller:

    [HttpGet]
    public string TestAll(){
        JObject obj = (JObject)JsonConvert.DeserializeObject(TestMethod());
        TestBean beans = new TestBean[]{
            new TestBean('TestMethod',true+"",obj+"",obj)
        };
        return JsonConvert.SerializeObject(beans);
    }
    
    

    When I visit the url localhost:.../TestAll, I will get json

    [
        {
            "pass":true,
            "name":"TestMethod",
            "suppose":"True",
            "fact":"True",
            "msg":"True"
        }
    ]
    

    Honestly, it's not easy to use, especially when the test case change frequently.