- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个服务设置如下:
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 什么。有人可以帮帮我吗?
我正在使用的框架:
最佳答案
为什么需要使用最小起订量?您不需要模拟 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/
考虑示例 C# 控制台应用程序中服务和组件的以下场景 public interface IService { } public class FooService: IService { } publi
我只是想掌握如何使用 WCF,如果有人能告诉我我是否对端点有正确的想法,我就在徘徊。 我一直在浏览 msdn 上的视频,现在我正在徘徊配置 WCF 服务的方法。这种情况是如果我有多个 IService
可以说我的 IService 拥有 IRepository 拥有的一切,而且还有一些特定的操作吗? 代码如下: public interface IRepository { T Add(T E
我有一个服务设置如下: public interface IMyService { void AddCountry(string countryName); } public class
我正在使用来自 Silverlight 应用程序 (MVVM) 和 Windows Phone 的 WCF 服务。我有一个服务类(自动生成)和一个 IServiceRepository 如下所示 pu
在 AppHost 上调用 Init() 时出现上述错误。 这是在一个干净的 asp.net v 4.5 空 web 应用程序上,根据入门教程使用简单的 HelloWorld 服务。 我专门使用安装了
我有一个托管在 IIS 中的 WCF 服务。我也有一个 WCF 客户端(一个控制台应用程序)。我用过 svcutil构建代理类和配置文件,然后将它们添加到我的客户端项目中。它正确构建。但是当我尝试运行
我使用 unitofwork 和 Repository 实现了一个可以正常工作的架构。我有一个名为 Product 的实体,我在 Controller 中使用 ProductService 进行 CR
我是一名优秀的程序员,十分优秀!