2012-07-15 36 views
13

Bir birim testinde, bir denetleyici eyleminin gerçekten belirli bir sayfaya yönlendirdiğini doğrulamanın kolay bir yolu var mı?asp.net mv'de birim testi ile yönlendirmeyi doğrulayın

Kontrolör kodu:

public ActionResult Create(ProductModel newProduct) 
{ 
    this.repository.CreateProduct(newProduct); 
    return RedirectToAction("Index"); 
} 

Yani benim testte, ben kontrolör aslında yönlendirme olduğunu doğrulamak gerekir.

ProductController controller = new ProductController(repository); 

RedirectToRouteResult result = (RedirectToRouteResult)controller.Create(newProduct); 

bool redirected = checkGoesHere; 
Assert.True(redirected, "Should have redirected to 'Index'"); 

Doğrulama işlemini nasıl yapacağınızdan emin değilim. Herhangi bir fikir?

cevap

25

Emin:

Assert.AreEqual("Index", result.RouteValues["action"]); 
Assert.IsNull(result.RouteValues["controller"]); // means we redirected to the same controller 

ve çok daha zarif bir şekilde bu birim testi (hatta bir RedirectToRouteResult yayın yapmak için gerekmez) yazabilirsiniz MvcContrib.TestHelper kullanarak:

// arrange 
var sut = new ProductController(repository); 

// act 
var result = sut.Create(newProduct); 

// assert 
result 
    .AssertActionRedirect() 
    .ToAction("Index"); 
+0

Teşekkür Darin ...

var result = sut.Create(newProduct) as RedirectToRouteResult; Assert.Equal(result.RouteValues["action"], "Index"); Assert.Equal(result.RouteValues["Parameter Name"], "Parameter Value"); 

Umut böyle bir şey yapabilirsiniz. TestHelper –

+0

+1 Bu MvcContrib kütüphanesi harika! –

+0

Link için – will

11

deneyin Bu ...

var result = sut.Create(newProduct) as RedirectToRouteResult; 
Assert.Equal(result.RouteValues["action"], "Index"); 

Ve yönlendirme için bir parametre iletiyorsanız yo Ben böyle basit bir şey olacağını biliyordu - u bu yardımcı olur :)