如何做单元测试的HttpContext.Current.Server.MapPath [英] How to do unit test for HttpContext.Current.Server.MapPath

查看:622
本文介绍了如何做单元测试的HttpContext.Current.Server.MapPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 HttpContext.Current.Server.MapPath()在我的方法来获取文档。

I'm using HttpContext.Current.Server.MapPath() in my method to fetch document.

要编写单元测试这种方法,

To write unit test for this method,

什么我在做的事:


  1. 的App.config

  2. 在我的单元测试方法

我如何莫克呢?

我承受做一个单元测试只对 Current.Server.Mappath()不是 Path.Combine()

I subjected to do a unit test only for Current.Server.Mappath() not for Path.Combine()

推荐答案

这是典型的以code调用静态方法,这是非常困难的,而测试的关注和避免preserving分离紧密耦合。这里是一个通用的方法来测试和模拟不可验证code:写了一个立面包装将它

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)

创建该包装类的接口

而不是直接调用客户端code不可测的方法,使用包装(依赖注入的使用在步骤2中提供的接口),并调用它的正常方法。

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.

这篇关于如何做单元测试的HttpContext.Current.Server.MapPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆