简体   繁体   English

使用Entity Framework对void方法进行单元测试

[英]Unit Testing of void methods using Entity Framework

I'm trying to familiarize myself with unit testing. 我正在努力熟悉单元测试。 I've written a small application that parses data from the Internet and stores it into a db. 我编写了一个小应用程序,它解析来自Internet的数据并将其存储到数据库中。 For this I'm using Entity Framework. 为此,我正在使用实体框架。

Since many of the methods are void methods such as 由于许多方法都是无效的方法,如

public void UpdateSiteValue(Site site, ObjectContext context)

This method could be used for updating some value in the db. 此方法可用于更新db中的某些值。 So I'm basically wondering how to approach this from a unit testing perspective. 所以我基本上想知道如何从单元测试的角度来处理这个问题。 Maybe I could mock the object context? 也许我可以模拟对象上下文?

Would appreciate any input. 将不胜感激任何意见。

It depends on what you're testing for. 这取决于你正在测试什么。

Since you're returning void, you can't test the return of the function - so are you wanting to test that your method will actually make the changes in the database? 由于您返回void,您无法测试函数的返回 - 所以您是否要测试您的方法是否会实际在数据库中进行更改? If so, then mocking your context isn't the best solution, because you aren't testing the actual code. 如果是这样,那么模拟您的上下文不是最佳解决方案,因为您没有测试实际代码。 Ladislav Mrnka made a great post about that. Ladislav Mrnka发表了一篇很好的文章 Could you wrap your test in a transaction scope and then do a rollback afterwards? 您可以将测试包装在事务范围内,然后再进行回滚吗? The Id's would get incremented, but at least you'd be testing everything. Id会增加,但至少你会测试一切。

Alternatively, if you're wanting to test that your method is doing everything right - up until you get to the database layer there's a few ways to go about that. 或者,如果您想测试您的方法正在做的一切 - 直到您到达数据库层,有几种方法可以解决这个问题。 Something that is suggested alot is to use the repository pattern, so that you don't have a dependancy on EF in your test. 建议的很多东西是使用存储库模式,因此您在测试中没有依赖EF。 Truewill made a good post about this also. Truewill也就此发表了一篇好文章 He also links to an MSDN article about this, using an in memory ObjectContext that you may find relevant. 他还使用您可能认为相关的内存ObjectContext链接到有关此内容的MSDN文章

Here is some more general reading about unit vs function vs integration testing that can help. 这里有一些关于单元与功能与集成测试的更一般的阅读 ,可以提供帮助。

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

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