ASP.NET MVCを使い始めたばかりで、単体テストも初めてです:)これまでのところ、とても良いです。
ビューモデルを使用してインデックスビューを設定するコントローラーアクションがあります。コントローラーのコンストラクターで偽のサービスクラスを渡すことができるため、コントローラーアクションのテストは簡単ですが、ビューモデルは非常に複雑で、インスタンス化時に独自のサービスクラスをフェッチします。
コードはこれをより明確にする必要があります...
コントローラのアクション:
Function Index(ByVal id As Integer?) As ActionResult
Dim totalCount As Integer = 0
Dim selectedClient As Integer
If id Is Nothing Then
selectedClient = _portalClientService.GetFirstClient().ID
Else
selectedClient = id
End If
Dim users As MembershipUserCollection = _membershipService.GetUsersByClientId(selectedClient, 0, 1000, totalCount)
Return View(New UserListViewModel(users, selectedClient))
End Function
Viewmodelクラス:
Public Class UserListViewModel
Private _clientService As IPortalClientService
Public Sub New(ByVal users As MembershipUserCollection, ByVal selectedClient As Integer)
Me.New(users, selectedClient, Nothing)
End Sub
Public Sub New(ByVal users As MembershipUserCollection, ByVal selectedClient As Integer, ByVal clientService As IPortalClientService)
_users = users
_clientService = If(clientService, New PortalClientService)
_clients = New SelectList(_clientService.GetClients.OrderBy(Function(c) c.ClientName), "ID", "ClientName", selectedClient)
End Sub
Private _users As MembershipUserCollection
Public Property Users() As MembershipUserCollection
Get
Return _users
End Get
Set(ByVal value As MembershipUserCollection)
_users = value
End Set
End Property
Private _clients As SelectList
Public Property Clients() As SelectList
Get
Return _clients
End Get
Set(ByVal value As SelectList)
_clients = value
End Set
End Property
End Class
編集:
コントローラのアクションをテストするときに、ビューモデルに偽のサービスクラスを使用させるにはどうすればよいですか?
最初のコンストラクターを捨てて、常にコントローラーからサービスを渡す必要がありますか、それとも別の方法がありますか?
乾杯、
ニック