단위 테스트 Url.IsLocalUrl(returnurl 로.ToString()),어떻게 얻을 수 있습니다면 false 를 반환에서 유닛 테스트?

StackOverflow https://stackoverflow.com/questions/9463201

문제

표준에서 로그온에서 메서드 계정에서 컨트롤러 MVC3 응용 프로그램,방법을 테스트 할 수 있습니다

Url.IsLocalUrl(returnUrl.ToString()) 

라인의 코드에 url 을하지 않은 로컬?다시 말해서,어떤 url 을 내가 먹이로이 라인의 코드를 단위 테스트,그것을 얻는 false 를 반환?

내가 사용되는 다음의 생각이 반환되 거짓으로(비 로컬):

Uri uri = new Uri(@"http://www.google.com/blahblah.html");

하지만 그것은 던지 null 예외에서 유닛 테스트

편집:추가해야하는 로그인 방법으로 지금은 다음과 같습니다:

public ActionResult LogOn(LogOnModel model, System.Uri returnUrl)

if (ModelState.IsValid) {

            bool loggedOn = LogOn(model);

            if (loggedOn) {
                if (Url.IsLocalUrl(returnUrl.ToString())) {
                    return Redirect(returnUrl.ToString());
                }
                else {
                    return RedirectToAction("Index", "Home");
                }
            }
            else {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }

        // If we got this far, something failed, redisplay form
        return View(viewModel);
    }

어떤 스타일에 경찰이/코드 분석 오류를 강제로 변화된 문자열에서 매개 변수를 시스템입니다.uri 매개 변수이지만 그것과 매우 유사하는 표준 원래 있습니다.

을 명확히 하기 위해,단위 테스트-고 싶은 테스트를 주장하는 결과를 타격의 Else 라인을 리디렉션 Home/Index, 다,그래서 나는 뭔가를 전달해야를로 (System.Uri)returnUrl 는 false 를 반환에 Url.IsLocalUrl 고 예외가 발생하지 않습

더 편집:

내가 사용하 MvcContrib testhelper,이는 매우 좋은 조롱의 많은 httpcontext 및 웹 물건:

Builder = new TestControllerBuilder();
UserController = new UserController();
    Builder.InitializeController(UserController);
도움이 되었습니까?

해결책

필요한 모형 HttpContext 뿐만 아니라 UrlHelper 인스턴스 컨트롤러에서는 단위 테스트입니다.여기에는 방법의 예는 단위 테스트처럼 보일 수 있을 사용하는 경우 Moq:

[TestMethod]
public void LogOn_Should_Redirect_To_Home_If_Authentication_Succeeds_But_Not_Local_ReturnUrl_Is_Provided()
{
    // arrange
    var sut = new AccountController();
    var model = new LogOnModel();
    var returnUrl = new Uri("http://www.google.com");
    var httpContext = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    httpContext.Setup(x => x.Request).Returns(request.Object);
    request.Setup(x => x.Url).Returns(new Uri("http://localhost:123"));
    var requestContext = new RequestContext(httpContext.Object, new RouteData());
    sut.Url = new UrlHelper(requestContext);

    // act
    var actual = sut.LogOn(model, returnUrl);

    // assert
    Assert.IsInstanceOfType(actual, typeof(RedirectToRouteResult));
    var result = (RedirectToRouteResult)actual;
    Assert.AreEqual("Home", result.RouteValues["controller"]);
    Assert.AreEqual("Index", result.RouteValues["action"]);
}

말:했기 때문에 실제로 표시 LogOn 구현하는 당신을 호출하는지 확인하는 자격 증명이 필요할 수 있는 적응하기 위해 단위를 테스트하는지 확인 이 방법 true 를 반환합니다 첫 번째 장소에서 주어진 모델에 입력 if (loggedOn) 절입니다.


업데이트:

그것은 당신을 사용하는 MvcContrib.TestHelper 는 모든 HttpContext 조롱이 있습니다.그래서 모든 것을 당신이해야 할 모의 관련 부품에 대한 단위 테스트:

[TestMethod]
public void LogOn_Should_Redirect_To_Home_If_Authentication_Succeeds_But_Not_Local_ReturnUrl_Is_Provided()
{
    // arrange
    var sut = new AccountController();
    new TestControllerBuilder().InitializeController(sut);
    var model = new LogOnModel();
    var returnUrl = new Uri("http://www.google.com");
    sut.HttpContext.Request.Expect(x => x.Url).Return(new Uri("http://localhost:123"));

    // act
    var actual = sut.LogOn(model, returnUrl);

    // assert
    actual
        .AssertActionRedirect()
        .ToController("Home")
        .ToAction("Index");
}

일반적으로 2 라인 단위의 시험으로 이동할 수 있 글로벌 [SetUp] 메소드가 반복되지 않도록 그들 각각에 대한 단위 테스트 이 컨트롤러므로 이제 테스트가 된 사이트:

[TestMethod]
public void LogOn_Should_Redirect_To_Home_If_Authentication_Succeeds_But_Not_Local_ReturnUrl_Is_Provided()
{
    // arrange
    var model = new LogOnModel();
    var returnUrl = new Uri("http://www.google.com");
    _sut.HttpContext.Request.Expect(x => x.Url).Return(new Uri("http://localhost:123"));

    // act
    var actual = _sut.LogOn(model, returnUrl);

    // assert
    actual
        .AssertActionRedirect()
        .ToController("Home")
        .ToAction("Index");
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top