Mocking HttpContext.server.MapPath in ASP.NET unit testing

前端 未结 3 1027
抹茶落季
抹茶落季 2021-02-04 21:29

I have working in unit testing in ASP.Net web application, now I have accessing my constructor in the model file to test which has Server.MapPath code for uploading my XMLfile,

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 22:16

    This is typical with code that calls static methods, it's very difficult to test while preserving separation of concern and avoiding tight coupling. Here is a generic approach to test and mock "untestable code": write a "facade wrapper" to it.

    • Create a wrapper for these methods. A simple class that contains methods named sensibly, and only delegates to the untestable calls (typically static calls)

    • Create an interface to that wrapper class

    • Instead of directly calling the untestable methods in your client code, use the wrapper (dependency-injected using the interface provided in step 2) and call normal methods on it.

    • In your unit-test, mock the wrapper with the behaviour you want.

    This approach effectively reduces the coupling and separates the concerns that need to be separated. Of course, you still can't test the behaviour of the wrapper itself, but if it's simple enough (only delegating to the original calls) then it's not as big a problem.

    Update:

    Using shims to isolate your application from other assemblies for unit testing

    Shim types are one of two technologies that the Microsoft Fakes Framework uses to let you easily isolate components under test from the environment. Shims divert calls to specific methods to code that you write as part of your test. Many methods return different results dependent on external conditions, but a shim is under the control of your test and can return consistent results at every call. This makes your tests much easier to write. Use shims to isolate your code from assemblies that are not part of your solution. To isolate components of your solution from each other, we recommend that you use stubs.

提交回复
热议问题