0%

【UnitTest】Mock Controller Request

寫單元測試測試Controller的時候,有時候程式中會用到Controller.Request Property,但單元測試並不是真的Web連線行為,所以呼叫到Request的時候會是Null , 想要做一個假的塞給他,這個屬性卻是只能讀取不能寫入的

[![](https://2.bp.blogspot.com/-4_O_yEIRJeA/WKJdDhYR0MI/AAAAAAAAIEk/pa8aYvPcJw4jt62eTTSYrp6h-hK98eP1ACLcB/s1600/1.png)](https://2.bp.blogspot.com/-4_O_yEIRJeA/WKJdDhYR0MI/AAAAAAAAIEk/pa8aYvPcJw4jt62eTTSYrp6h-hK98eP1ACLcB/s1600/1.png)

每次寫完沒多久碰到就又會忘記,所以筆記下來方便以後查找,這邊一樣用NSubstitute套件做處理

[![](https://4.bp.blogspot.com/-dMNVp94tO1Y/WKJeLHnEa8I/AAAAAAAAIEs/7yAUVlh29F0wsXsmTjh_UcSZUdoC8MfpgCLcB/s1600/1.png)](https://4.bp.blogspot.com/-dMNVp94tO1Y/WKJeLHnEa8I/AAAAAAAAIEs/7yAUVlh29F0wsXsmTjh_UcSZUdoC8MfpgCLcB/s1600/1.png)
1
2
3
4
5
6
7
8
9
YourController Sut = new YourController();
var request = Substitute.For<HttpRequestBase>();
var context = Substitute.For<HttpContextBase>();
request.HttpMethod.Returns("Get");
context.Request.Returns(request);

Sut.ControllerContext = new ControllerContext(context, new RouteData(), Sut);