如何设置我的Moq以返回一些值,并让测试的服务选择正确的值?
IRepository:
public interface IGeographicRepository
{
IQueryable<Country> GetCountries();
}服务:
public Country GetCountry(int countryId)
{
return geographicsRepository.GetCountries()
.Where(c => c.CountryId == countryId).SingleOrDefault();
}测试:
[Test]
public void Can_Get_Correct_Country()
{
//Setup
geographicsRepository.Setup(x => x.GetCountries()).Returns()
//No idea what to do here.
//Call
var country = geoService.GetCountry(1);
//Should return object Country with property CountryName="Jamaica"
//Assert
Assert.IsInstanceOf<Country>(country);
Assert.AreEqual("Jamaica", country.CountryName);
Assert.AreEqual(1, country.CountryId);
geographicsRepository.VerifyAll();
}我基本上被困在设置中了。
发布于 2010-12-19 11:40:04
你不能使用AsQueryable()吗?
List<Country> countries = new List<Country>();
// Add Countries...
IQueryable<Country> queryableCountries = countries.AsQueryable();
geographicsRepository.Setup(x => x.GetCountries()).Returns(queryableCountries);发布于 2010-12-19 11:40:37
您可以做的是编写一个私有助手方法,该方法将生成一个Country对象的IQueryable,并让您的模拟返回该you。
[Test]
public void Can_Get_Correct_Country()
{
// some private method
IQueryable<Country> countries = GetCountries();
//Setup
geographicsRepository.Setup(x => x.GetCountries()).Returns(countries);
//Should return object Country with property CountryName="Jamaica"
//Call
var country = geoService.GetCountry(1);
//Assert
Assert.IsInstanceOf<Country>(country);
Assert.AreEqual("Jamaica", country.CountryName);
Assert.AreEqual(1, country.CountryId);
geographicsRepository.VerifyAll();
}发布于 2013-01-06 02:28:39
我建议不要使用AsQueryable()。在遇到ORM查询语言中的一些特定方法(Fetch、FetchMany、ThenFetchMany、Include、ToFuture等)之前,它只适用于一些简单的场景。
最好在内存数据库中使用。下面的链接描述了NHibernate单元测试。
我们可以使用标准的关系型数据库管理系统,也可以使用内存中的数据库,例如SQLite,以获得非常快的测试速度。
http://ayende.com/blog/3983/nhibernate-unit-testing
https://stackoverflow.com/questions/4481465
复制相似问题