์ ์ฐํ ์ฝ๋๋ฅผ ์ํด HttpContext ๋์ HttpContextBase ์ฌ์ฉํ๊ธฐ
๋ท๋ท ๊ธฐ๋ฐ ์น์ฌ์ดํธ ๊ฐ๋ฐ์ ํญ์ ์ฐ๋ ๊ฐ์ฒด๋ HttpContext ๊ฐ์ฒด์ด๋ค. ์๋ฒ ์์ฒญ, ์๋ฒ ์๋ต, ํ์ฌ ์ฌ์ฉ์, ์ธ์ , ์ฟ ํค ๋ฑ๋ฑ... ์ด HttpContext ๊ฐ์ฒด๊ฐ ๋ด๋นํ๋ ์ผ์ ๋ฌด๊ถ๋ฌด์งํ๋ค. ํ์ง๋ง, ์ด ๊ฐ์ฒด๋ HttpContext.Current์ ์ฑ๊ธํค ์ธ์คํด์ค๋ก๋ง ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋ฐ, ์ด๊ฒ์ ๊ตฌ์ ํด๋ผ์ค(Concrete Class)์ฌ์ ๋จ์ ํ ์คํธ๋ฅผ ํ ๋์๋ ์ฌ์ฉ์ ํ ์๊ฐ ์๋ค. ์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ณ ์ ๋ท๋ท ํ๋ ์์ 3.5๋ถํฐ ์๋กญ๊ฒ ๋ํ๋ ๊ฒ์ด ๋ฐ๋ก HttpContextBase๋ผ๋ ์ถ์ ํด๋ผ์ค(Abstract Class)์ด๋ค.
์ด HttpContextBase๋ผ๋ ์ถ์ ํด๋ผ์ค๋ฅผ ํตํด ๋จ์ ํ ์คํธ๋ผ๋ ๊ฐ ํ ์คํธ ์ฃผ๋ ๊ฐ๋ฐ ๋ฐฉ๋ฒ๋ก (TDD)์์ ์ฃผ๋ก ์ฌ์ฉํ๋ Mocking์ ์์ ๋กญ๊ฒ ๊ตฌํํ ์ ์๋ค. ์๋ ์ฝ๋๋ฅผ ๋ณด๋ฉด ๋๋ต์ ๊ฐ์ ์ก์ ์ ์์ ๊ฒ์ด๋ค.
HttpContextBase contextBase = new HttpContextWrapper(HttpContext.Current);
์์ ์์ ์ฝ๋๋ HttpContextWrapper ํด๋ผ์ค๋ฅผ ์ด์ฉํ์ฌ HttpContextBase ๊ฐ์ฒด๋ฅผ ๋ฆฌํดํ๋ ๊ฒ์ด๋ค. ์ค์ ๋์ํ๋ ์ฝ๋๋ ์ด๋ ๊ฒ ์์ฑํ ์ ์๊ณ , ๋จ์ ํ ์คํธ์์๋ ์๋์ ๊ฐ์ด ์์ฑํ ์๋ ์๋ค. Nunit๊ณผ NSubstitue๋ฅผ ์ฌ์ฉํ๋ค๊ณ ๊ฐ์ ํ์.
public class HomeControllerTest { private HttpContextBase _context; [SetUp] public void Init() { this._context = Substitute.For<HttpContextBase>(); ... } ... [Test] public void Test() { var controller = new HomeController(this._context); var result = controller.Index(); ... } }
์์ ํ ์คํธ ํด๋ผ์ค๋ฅผ ๋ณด๋ฉด HttpContextBase๋ฅผ mocking ํ์ฌ ์ฝํธ๋กค๋ฌ์ Dependency Injection์ ์ํค๋ ๊ฒ์ ๋ณผ ์ ์๋ค. ๋ง์ฝ Unity๋ผ๋ ๊ฐ Autofac ๊ฐ์ IoC ์ฝํ ์ด๋๋ฅผ ์ฌ์ฉํ๊ฒ ๋๋ค๋ฉด HttpContextBase์ญ์๋ ์ง์ ์ฌ์ฉํ๋ ๊ฒ๋ณด๋ค๋ IHttpContextBaseWrapper ๊ฐ์ ํํ๋ก ํ ๋ฒ ๋ ๊ฐ์ธ์ ์ฌ์ฉํ๋ฉด ๋๋ค.
์ฐธ๊ณ : HttpContext vs HttpContextBase vs HttpContextWrapper









