วิธีการขยายการทดสอบหน่วย UrlHelper

ฉันกำลังพยายามสร้างการทดสอบหน่วยเพื่อให้แน่ใจว่าวิธีการขยาย UrlHelper ของฉันใช้งานได้ ไม่มีใครรู้วิธีการทำเช่นนี้? ฉันใช้ MVC 1.0 และ MvcContrib ฉันสามารถทดสอบเส้นทางได้ แต่ไม่สามารถทดสอบโค้ดเช่นนี้ได้:

    public static string MoreFloorplans(this UrlHelper urlHelper, long productID, int pageIndex)
    {
     return urlHelper.Action<CatalogController>(x => x.GetRelatedProducts(productID, pageIndex));

    }

person fregas    schedule 19.04.2010    source แหล่งที่มา


คำตอบ (2)


ฉันทำตามคำแนะนำจาก Aaronaught และ Scott H แต่มันก็เกิดข้อผิดพลาดไปบ้าง ฉันลงเอยด้วยสิ่งนี้

public UrlHelper GetUrlHelper(
        string fileName = "/",
        string url="http://localhost", 
        string queryString="")
{
    // Use routes from actual app
    var routeCollection = new RouteCollection();
    MvcApplication.RegisterRoutes(routeCollection);

    //Make a request context
    var request = new HttpRequest(fileName, url, queryString);
    var response = new HttpResponse(new StringWriter());
    var httpContext = new HttpContext(request, response);
    var httpContextBase = new HttpContextWrapper(httpContext);
    var requestContext = new RequestContext(httpContextBase, new RouteData());

    // Make the UrlHelper with empty route data
    return new UrlHelper(requestContext, routeCollection);
}

public void MoreFloorplans_ReturnsExpectedUrl()
{
    var urlHelper = GetUrlHelper();
    var actualResult = urlHelper.MoreFloorPlans(1,2);
    Assert.AreEqual("/MoreFloorPlans/1/2", actualResult);
}

โปรดทราบว่าคุณควรทดสอบวิธีการขยายของคุณ ไม่ใช่ UrlHelper ดังนั้นการตั้งค่า RouteData ใน RequestContext อาจไม่อยู่ในขอบเขต

person Craig Celeste    schedule 23.07.2010

ในการสร้าง UrlHelper คุณต้องมี RequestContext ในการสร้าง RequestContext ที่ใช้งานได้ คุณต้องมี HttpContextBase และ RouteData ส่วนที่สอง RouteData ควรสร้างตรงไปตรงมา HttpContextBase คุณต้องเยาะเย้ย

เพื่อดำเนินการดังกล่าว ฉันขอแนะนำให้คุณดู MvcMockHelpers ของ Scott H บางส่วนอาจเก่าไปสักหน่อย แต่ฉันคิดว่ามันดีพอสำหรับการทดสอบนี้ สิ่งที่คุณต้องการจริงๆ คือเมธอด FakeHttpContext และการขึ้นต่อกันของเมธอด หากคุณไปรับไลบรารีนั้น โค้ดของคุณจะมีลักษณะดังนี้:

[TestMethod]
public void Can_write_more_floorplans()
{
    const long productID = 12345;
    const int pageIndex = 10;

    var httpContext = FakeHttpContext();  // From the MvcMockHelpers
    var routeData = new RouteData();
    var requestContext = new RequestContext(httpContext, routeData);
    var urlHelper = new UrlHelper(requestContext);
    string floorplans = MoreFloorplans(urlHelper, productID, pageIndex);
    Assert.AreEqual(some_string, floorplans);
}

ฉันรู้ว่าคุณพูดว่าคุณกำลังพยายามใช้โปรเจ็กต์ MvcContrib TestHelper แต่เท่าที่ฉันรู้ ไลบรารีนั้นเกี่ยวกับการทดสอบคอนโทรลเลอร์ ฉันไม่แน่ใจว่ามันละเอียดพอที่จะทดสอบส่วนประกอบระดับล่างหรือไม่ คุณไม่จำเป็นต้องมีทุกสิ่งในนั้นจริงๆ สิ่งที่คุณต้องมีคือ RequestContext

person Aaronaught    schedule 19.04.2010