没有接口的Moq和DbSet。 [英] Moq and DbSet without interfaces.

查看:85
本文介绍了没有接口的Moq和DbSet。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



我在工作中遇到单元测试问题(我是单元测试世界的新手)。我必须测试在ApplicationDbContext和DbSets上运行的Provider,但是没有任何接口,并且它们不是虚拟成员。

我无法创建它们因为应用程序很大而无法进行更改。



所以,我需要上课。现在我有问题。



我需要测试一下这样的想法:

Hello,

I have a problem with unit tests in work(I'm new in unit test world). I have to test Provider who operates on ApplicationDbContext and DbSets but there aren't any interfaces of that and they are not virtual members.
I can't create them becouse application is to big to make changes.

So, I need to work on classes. Now i have problem.

I need to test somethink like that:

public bool AddOrUpdateSomeDbSet(SomeClass doc)
       {
           this.db.SomeDbSet.AddOrUpdate(doc);

           try
           {
               this.db.SaveChanges();
               return true;
           }
           catch (Exception)
           {
               //TODO: logging
               return false;
           }
       }





如此渴望我想测试成功试试。

1.db是ApplicationDbContext。

2.我需要模拟db。

3。 db.SomeDbSet.AddOrUpdate(doc)必须返回一些东西才能不进行崩溃测试。

4. db.SaveChanges()必须返回东西



我在第3点和第4点遇到问题。



关于点数3:

我有一些想法像这样:



So firsty I want to test a success try.
1. "db" is ApplicationDbContext.
2. I need to mock db.
3. db.SomeDbSet.AddOrUpdate(doc) must return some stuff to don't crash test.
4. db.SaveChanges() must return stuff too

And I have problem with point 3 and 4.

About point number 3:
I have somethink like that:

// That doesn't work because there is no .Return after that code. I dont know why.
contextMock.Setup(x => x.SomeDbSet.AddOrUpdate(It.IsAny<SomeClass>())).Returns(SomeStuff)



关于第4点:

在上下文中有两种方法SaveChanges()和SaveChanges(字符串值)


About point number 4:
In context are two methods SaveChanges() and SaveChanges(string value)

contextMock.Setup(x => x.SaveChanges("a")).Returns(1); // WORK
contextMock.Setup(x => x.SaveChanges()).Returns(1); // dont work
// An expression tree may not contain a call or invocation that uses optimal arguments - hmm? 





任何人都可以帮我吗?



Can anyone help me with it?

推荐答案

您正在运行Entity Framework 6.0,这意味着您可以利用本文:

使用模拟框架进行测试(EF6以上) [ ^ ]



使用EF 6,Microsoft更改了T4文件以使用关键字 virtual 。这允许Moq框架覆盖方法和属性的实现。您可以使用EF 5执行此操作,但您需要更改T4文件以允许此操作。



我已使用此实现了数十个单元测试,因此如果您遇到特定问题,请告诉我。
You are running Entity Framework 6.0 which means you can take advantage of the this article:
Testing with a mocking framework (EF6 onwards)[^]

With EF 6, Microsoft changed the T4 file to generate everything using the keyword virtual. This allows the Moq framework to override the implementation of the methods and properties. You could do this with EF 5, but you would need to change the T4 file to allow for this.

I've implemented dozens of unit tests using this, so let me know if you run into a specific issue.


这篇关于没有接口的Moq和DbSet。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆