gpt4 book ai didi

c# - 如何使用 Moq 模拟和测试 IService

转载 作者:太空宇宙 更新时间:2023-11-03 18:45:57 25 4
gpt4 key购买 nike

我有一个服务设置如下:

public interface IMyService
{
void AddCountry(string countryName);
}

public class MyService : IMyService
{
public void AddCountry(string countryName)
{
/* Code here that access repository and checks if country exists or not.
If exist, throw error or just execute. */
}
}

测试.cs

[TestFixture]
public class MyServiceTest
{
[Test]
public void Country_Can_Be_Added()
{ }

[Test]
public void Duplicate_Country_Can_Not_Be_Added()
{ }

}

如何测试 AddCountry 和最小起订量存储库或服务。我真的不确定在这里做什么或 mock 什么。有人可以帮帮我吗?

我正在使用的框架:

  1. N单位
  2. 起订量
  3. ASP.NET MVC

最佳答案

为什么需要使用最小起订量?您不需要模拟 IService。在您的情况下,您可以像这样编写测试:

[Test]
public void Country_Can_Be_Added()
{
new MyService().AddCountry("xy");
}

[Test]
public void Duplicate_Country_Can_Not_Be_Added()
{
Assert.Throws<ArgumentException>(() => new MyService().AddCountry("yx"));
}

如果您有这样的场景,您将需要模拟 IRepository:

interface IRepository { bool CanAdd(string country); }
class MyService : IService
{
private IRepository _service; private List<string> _countries;
public IEnumerable<string> Countries { get { return _countries; } }
public X(IRepository service) { _service = service; _countries = new List<string>(); }
void AddCountry(string x)
{
if(_service.CanAdd(x)) {
_conntires.Add(x);
}
}
}

像这样的测试:

[Test]
public void Expect_AddCountryCall()
{
var canTadd = "USA";
var canAdd = "Canadd-a";

// mock setup
var mock = new Mock<IRepository>();
mock.Setup(x => x.CanAdd(canTadd)).Returns(false);
mock.Setup(x => x.CanAdd(canAdd)).Returns(true);

var x = new X(mock.Object);

// check state of x
x.AddCountry(canTadd);
Assert.AreEqual(0, x.Countires.Count);

x.AddCountry(canAdd);
Assert.AreEqual(0, x.Countires.Count);
Assert.AreEqual(0, x.Countires.Count);
Assert.AreEqual(canAdd, x.Countires.First());

// check if the repository methods were called
mock.Verify(x => x.CanAdd(canTadd));
mock.Verify(x => x.CanAdd(canAdd));
}

关于c# - 如何使用 Moq 模拟和测试 IService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4473354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com