简体   繁体   English

犀牛模拟仿制药问题

[英]Rhino mocks generics issue

I have an interface that I need to mock - 我有一个需要模拟的界面-

 public interface IRepositoryCachable  
 {
     IEnumerable<T> All<T>() where T : ICacheEntity;
     void Delete<T>(T item) where T : ICacheEntity;
     void Add<T>(T item) where T : ICacheEntity;
     void Update();
     T SingleOrDefault<T>(Func<T, bool> predicate) where T : ICacheEntity;
     IEnumerable<T> Find<T>(Func<T, bool> predicate) where T : ICacheEntity;
 }

Here is my test - 这是我的测试-

var repo = MockRepository.GenerateMock<IRepositoryCachable>();
repo.Expect(x => x.Add(Arg<ICacheEntity>.Is.Anything));

testClass = new testclass(repo);

testClass.Add;

repo.VerifyAllExpectations();

testClass.Add calls repo.Add . testClass.Add调用repo.Add But in VerifyAllExpectation(); 但是在VerifyAllExpectation(); it barfs stating that Add was not called. 它表示没有调用Add。

Code for test class - pseudo - 测试类代码-伪-

public class TestClass
{
    public void Add()
    {
         _repo.Add( new CacheEntity());
    }
}

What Am I doing wrong? 我究竟做错了什么?

为什么要测试实现详细信息(称为什么?)而不是行为(将其添加到数据库中,或者返回缓存的实体,等等)?

This line seems suspect: 这行似乎是可疑的:

testClass.Add; 

Should a parameter be passed to this method? 是否应该将参数传递给此方法? I don't even see how this can compile to be honest. 老实说,我什至不知道该如何编译。

Use GenerateStub instead of GenerateMock . 使用GenerateStub而不是GenerateMock Stubs are usually used for interfaces. 存根通常用于接口。 I usually only use mocks when I'm mocking out actual class members. 我通常只在模拟实际的类成员时才使用模拟。

What is happening here I think is that you are setting up an expectation for the method Add to be called but this method is distinct from Add which is the method you are really calling. 我认为这里正在发生的事情是您对要调用的方法Add设置了期望,但是该方法与Add(您真正要调用的方法)不同。

In short either change you expectation to: 简而言之,将您期望的任何一项更改为:

repo.Expect(x => x.Add(Arg<CacheEntity>.Is.Anything));

Or change your non-test code to: _repo.Add<ICacheEntity>(new CacheEntity()); 或将您的非测试代码更改为: _repo.Add<ICacheEntity>(new CacheEntity());

I am assuming you will not want to do the second since you put a generic parameter on that method and the only reason to do that is because you need to have the parameter be typed to the concrete type. 我假设您不想执行第二个操作,因为在该方法上放置了通用参数,而这样做的唯一原因是因为您需要将参数键入为具体类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM