2012-01-16 4 views
2

私は最近の代わりになど、RedirectToActionを使用してのurlヘルパー拡張機能を使用するために私のコントローラのほとんどを変更:ユニットテストコントローラは

public ActionResult Create(CreateModel model) 
{ 
    // ... 
    return Redirect(Url.Home()); 
} 

これは、現在、私のユニットテストは、NullReferenceの例外を除いて壊れてきました。 UrlHelperをモック/スタブするための適切な方法は何ですか?ユニットテストを再度実行するには?

編集:

マイURL拡張子は次のようになります。

public static class UrlHelperExtensions 
{ 
    public static string Home(this UrlHelper helper) 
    { 
     return helper.RouteUrl("Default"); 
    } 
} 

私のユニットテストは、ちょうど彼らが正しいページにリダイレクトされていることを確認するためにテストされています

// Arrange 
var controller = new HomeController(); 

// Act 
var result = controller.Create(...); 

// Assert 
// recalling the exact details of this from memory, but this is what i'm trying to do: 
Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult)); 
Assert.AreEqual(((RedirectToRouteResult)result).Controller, "Home"); 
Assert.AreEqual(((RedirectToRouteResult)result).Action, "Index"); 

何私はUrl.Home()を呼び出すときですが、私はnull参照エラーを取得します。私は新しいUrlHelperでUrlプロパティを設定しようとしましたが、まだnull参照例外を取得します。

+0

http://stackoverflow.com/questions/674458/asp-net-mvc-unit-testing-controllers-that-use-urlhelper – lukiffer

+2

ユニットテストとUrl.Home() UrlHelperクラスには存在しないことは明らかです。あなたは答えを期待していますか? –

+0

質問を詳細に更新しました。 – Dismissile

答えて

1

私はあなたのほうたとえば、あなたの拡張機能を抽象化すると思う:次に

public interface IUrls 
{ 
    string Home(); 
} 

public class Urls : IUrls 
{ 
    public string Home() 
    { 
     //impl 
    } 
} 

コンストラクタは、あなたのテストのために、そしてあなたができる簡単にスタブ「IUrlsは」どこに必要なことを注入します。

関連する問題