How to write a unit test for the methods that change data?
I have the following method:
Void UpdateUser(User user){}
I need to check this method whether will work properly.
I've used a separate db to check this in unit testing. But many experienced people said if I use this method that won't be unit testing; that's integration testing.
But I don't know how to mock for unit testing.
The code written in the UpdateUser
method, will try to update data using Entity framework.
If I mock (Actually I don't how to do this either), how this will work with entity framework?
Mocking means that you develop your software components (classes) in a way that any class with behaviour is used/consumed/called-upon as an interface (or abstract class). You program to an abstraction. Run-time you use something (service locator, DI container, factory, ...) to retrieve/create those instances.
The most common way is to use construction injection. Here is an excellent explanation of why one would use DI, and examples of how to do it.
In your case, your component that uses the Entity Framework (your repository for instance) must implement a repository-interface, and any class that uses your repository should use it as an interface.
This way, you can mock the repository in your unittests. Which means that you create a unit-test-repository class (which has nothing to do with any database or EF), and use that when you create the instance of the class that you want to unit-test.
Hopefully this helps. There are many source to be found. Personally I just read this book and I found it to be very good. This is the authors blog.
You can use transaction and rollback or create a test user try its update. Assert and then in the finally block delete the test user.
You can use mocking framework like moq, rhino etc. moq is quite easy and you can find many example that demonstrate moq with DI like unity framework.
If your class is like this
public class UserRepository()
{
Sqlcontext _context;
void UpdateUser(User user)
{
_context.Users.Add(user);
}
}
then this is not unit testable.
Although this is not a unit test, if you insist on connecting on database and testing it, you could change your function to
User UpdateUser(User user)
{
_context.Users.Add(user);
return user;
}
and test if
user.Id > 0
Here, you are basically just testing entity framework.
链接地址: http://www.djcxy.com/p/82254.html上一篇: 我应该在界面或抽象背后隐藏DTO和View模型吗?
下一篇: 如何为改变数据的方法编写单元测试?