Sha*_*ean 8 nunit unit-testing moq
如何在mocks上设置我的测试方法接受对象的存储库?
这是我到目前为止:
Service.cs
public int AddCountry(string countryName)
{
Country country = new Country();
country.CountryName = countryName;
return geographicsRepository.SaveCountry(country).CountryId;
}
Run Code Online (Sandbox Code Playgroud)
test.cs中
[Test]
public void Insert_Country()
{
//Setup
var geographicsRepository = new Mock<IGeographicRepository>();
geographicsRepository.Setup(x => x.SaveCountry(It.Is<Country>(c => c.CountryName == "Jamaica"))); //How do I return a 1 here?
GeographicService geoService = new GeographicService(geographicsRepository.Object);
int id = geoService.AddCountry("Jamaica");
Assert.AreEqual(1, id);
}
Run Code Online (Sandbox Code Playgroud)
SaveCountry(Country country); 返回一个int.
我需要做两件事:
我需要创建第二个测试Insert_Duplicate_Country_Throws_Exception().在我的安装程序中,当我这样做时,如何告诉存储库抛出错误:
int id = geoService.AddCountry("Jamaica");
int id = geoService.AddCountry("Jamaica");
Run Code Online (Sandbox Code Playgroud)框架:
你的第一个测试应该是这样的:
[Test]
public void Insert_Country()
{
Mock<IGeographicRepository> geographicsRepository = new Mock<IGeographicRepository>();
GeographicService geoService = new GeographicService(geographicsRepository.Object);
// Setup Mock
geographicsRepository
.Setup(x => x.SaveCountry(It.IsAny<Country>()))
.Returns(1);
var id = geoService.AddCountry("Jamaica");
Assert.IsInstanceOf<Int32>(id);
Assert.AreEqual(1, id);
geographicsRepository.VerifyAll();
}
Run Code Online (Sandbox Code Playgroud)
第二个测试应如下所示:
[Test]
public void Insert_Duplicate_Country_Throws_Exception()
{
Mock<IGeographicRepository> geographicsRepository = new Mock<IGeographicRepository>();
GeographicService geoService = new GeographicService(geographicsRepository.Object);
// Setup Mock
geographicsRepository
.Setup(x => x.SaveCountry(It.IsAny<Country>()))
.Throws(new MyException());
try
{
var id = geoService.AddCountry("Jamaica");
Assert.Fail("Exception not thrown");
}
catch (MyException)
{
geographicsRepository.VerifyAll();
}
}
Run Code Online (Sandbox Code Playgroud)