I am relatively new to Moq and have this difficult case to taunt and get stuck. I was hoping an experienced Moq user could advise me the following:
Inside my ViewModel model, ctor calls this loading method:
public void LoadCategories()
{
Categories = null;
BookDataService.GetCategories(GetCategoriesCallback);
}
I would like to mock the Service. But since the service method is invalid and the return always comes through a callback, it becomes too complicated for me.
private void GetCategoriesCallback(ObservableCollection<Category> categories)
{
if (categories != null)
{
this.Categories = categories;
if (Categories.Count > 0)
{
SelectedCategory = Categories[0];
}
LoadBooksByCategory();
}
}
Since it wasnโt as bad as you can see, there is another LoadMethod called LoadBooksByCategory ()
public void LoadBooksByCategory()
{
Books = null;
if (SelectedCategory != null)
BookDataService.GetBooksByCategory(GetBooksCallback, SelectedCategory.CategoryID, _pageSize);
}
private void GetBooksCallback(ObservableCollection<Book> books)
{
if (books != null)
{
if (Books == null)
{
Books = books;
}
else
{
foreach (var book in books)
{
Books.Add(book);
}
}
if (Books.Count > 0)
{
SelectedBook = Books[0];
}
}
}
So now my setup is Mock:
bool submitted = false;
Category selectedCategory = new Category{CategoryID = 1};
ObservableCollection<Book> books;
var mockDomainClient = new Mock<TestDomainClient>();
var context = new BookClubContext(mockDomainClient.Object);
var book = new Book
{
...
};
var entityChangeSet = context.EntityContainer.GetChanges();
var mockService = new Mock<BookDataService>(context);
mockService.Setup(s => s.GetCategories(It.IsAny<Action<ObservableCollection<Category>>>()))
.Callback<Action<ObservableCollection<Category>>>(action => action(new ObservableCollection<Category>{new Category{CategoryID = 1}}));
mockService.Setup(s => s.GetBooksByCategory(It.IsAny<Action<ObservableCollection<Book>>>(), selectedCategory.CategoryID, 10))
.Callback<Action<ObservableCollection<Book>>>(x => x(new ObservableCollection<Book>()));
var vm = new BookViewModel(mockService.Object);
vm.AddNewBook(book);
vm.OnSaveBooks();
EnqueueConditional(() => vm.Books.Count > 0);
EnqueueCallback(() => Assert.IsTrue(submitted));
As you can see, I created two settings for each Service call, however, due to their callback and sequential dependency, it is very confusing.
, GetBooksByCategory() , Selectedcategory viewmodel null. , , , viewmodel. , , viewmodel ?:) ?
, , ObservableCollection Books , , ( , , , , , )
. , , Moq.:)