Hi, I'm trying to unit test a common interface used in a generic Repository, something like T GetWhere(Func<T, Boolean> where)...
When I set this expectation in a test
JustMock throws this exception: "Telerik.JustMock.MockAssertionException: Setup contains calls that are marked as "MustBeCalled" but actually never called"
It seems the GetWhere() method was never call, to return the expected object.
Below is a simple example that illustrate the case.
How should I rewrite the second test below so that I can mock and test these type of interfaces?
Thanks in advance.
using
System;
using
Microsoft.VisualStudio.TestTools.UnitTesting;
using
Telerik.JustMock;
//Free version 2011.1.331.1
using
Model.Infrastructure;
using
Model;
namespace
Model.Infrastructure
{
public
interface
IRepository<T> where T :
class
{
T GetById(
int
Id);
T GetWhere(Func<T, Boolean> where);
}
}
namespace
Model
{
public
class
Book
{
public
int
Id {
get
;
set
; }
public
string
BookTitle {
get
;
set
; }
public
string
OnLoanTo {
get
;
set
; }
public
Book(){}
}
public
class
BookService
{
private
IRepository<Book> _bookRepository;
public
BookService(IRepository<Book> bookRepository)
{
this
._bookRepository = bookRepository;
}
public
Book GetSingleBook1(
int
bookId)
{
return
_bookRepository.GetById(bookId);;
}
public
Book GetSingleBook2(
int
bookId)
{
Book b = _bookRepository.GetWhere(x => x.Id == bookId);
return
b;
}
}
}
namespace
Model.Tests
{
[TestClass]
public
class
AssortedTests
{
private
Book expectedBook;
private
IRepository<Book> bookRepo;
private
BookService bookService;
[TestInitialize]
public
void
Setup()
{
expectedBook =
new
Book()
{ Id = 1,
BookTitle =
"Adventures"
,
OnLoanTo =
"John Smith"
};
bookRepo = Mock.Create<IRepository<Book>>();
bookService =
new
BookService(bookRepo);
}
[TestMethod]
public
void
Book_CanRetrieveBookFromRepository()
{
Mock.Arrange(() => bookRepo.GetById(1))
.Returns(expectedBook)
.MustBeCalled();
//Act
Book actualBook = bookService.GetSingleBook1(1);
Mock.Assert(bookRepo); //Pass...
Assert.IsTrue(actualBook.BookTitle ==
"Adventures"
);
}
[TestMethod]
public
void
Book_CanRetrieverFromRepositoryUsingLambdaExpressions()
{
Mock.Arrange(() => bookRepo.GetWhere(book => book.Id == 1))
.Returns(expectedBook)
.MustBeCalled();
//Act
Book actualBook = bookService.GetSingleBook2(1);
Mock.Assert(bookRepo);
//Throws the error...
Assert.IsTrue(actualBook.BookTitle ==
"Adventures"
);
}
}
}