1 回答

TA貢獻1797條經驗 獲得超6個贊
類似于我在此處提供的答案中采用的方法
如何在 IHttpModules 中測試 HttpApplication 事件
您可以創建一個工廠方法/函數,將當前緊密耦合的實現問題包裝在抽象中,從而實現更好的模擬和可測試性
重構模塊
public class MyModule1 : IHttpModule {
public void Dispose() {
//clean-up code here.
}
public void Init(HttpApplication application) {
// Below is an example of how you can handle LogRequest event and provide
// custom logging implementation for it
application.LogRequest += new EventHandler(OnLogRequest);
application.BeginRequest += new EventHandler(OnBeginRequest);
}
public Func<object, HttpContextBase> GetContext = (object sender) => {
return new HttpContextWrapper(((HttpApplication)sender).Context);
};
public void OnBeginRequest(object sender, EventArgs e) {
var context = GetContext(sender);
onbegin(context);
}
private void onbegin(HttpContextBase context) {
// other header stuff goes here
context.Server.TransferRequest("bobsyouruncle", true);
}
public void OnLogRequest(Object source, EventArgs e) {
//custom logging logic can go here
}
//...
}
測試GetContext時可以替換工廠函數以使用模擬。
例如
[TestMethod]
public void Server_Should_Transfer() {
//Arrange
var server = new Mock<HttpServerUtilityBase>();
var context = new Mock.<HttpContextBase>();
context.Setup(_ => _.Server).Returns(server.Object);
var sut = new MyModule1();
//replace with mock context for test
sut.GetContext = (object sender) => context.Object;
//Act
sut.OnBeginRequest(new object(), EventArgs.Empty);
//Assert
server.Verify(_ => _.TransferRequest("bobsyouruncle", true), Times.AtLeastOnce);
}
- 1 回答
- 0 關注
- 99 瀏覽
添加回答
舉報