一:Mock
对现有的代码补UT,因为存在大量的引用,reference这些引用,并Fakes它的DLL。
- 如果引用是接口采用MockRepository.GenerateStub<T>实例化
- 如果引用是类实例,可以实例化"ShimXXXX"
构造的时候如果有真正类的实例更好,非常实用!。例如对class A生成对应的Shim类:
new ShimA(new A())
另外一些方法:
调用构造函数创建一个类:
var ctor = typeof(ClassName).GetConstructors();
return (ClassName)ctor.Invoke(new object[0]);
对被调用的函数进行Mock,使其调用自己的函数,函数里只有类似与isCalled = true这样的语句即可。
事件也可以Mock
ConnectedController.Test.cs有上面说的一些例子。
===============================
这里需要注意两个函数:GenerateStub<T> & GenerateMock<T>
更正:自己试了下,这两个函数都可以用。建议使用GenerateStub,可以为属性赋值。
如果只是做简单实例化一个接口,不需要对该接口函数的输出有任何的要求,那就用GenerateStub。
如果UT的结果需要依据这个接口函数的输出,就要使用GenerateMock。(随后调用Stub)
所以UT代码中,GenerateStub一般调用一次就够了。 GenerateMock可能就需要调用多次。
you should use a mock when you are going to verify that something happened on the object, like a method was called. You should use a stub when you just want the object to be involved in the test to return a value but it is not the thing you are testing. A stub which does not have a expectation fulfilled can never fail a test.
I think the general rule should be that you should only ever have a single mock object in a test, but may have several stubs which provide information to the mock object. I believe that more than 1 mock in a test is a code smell.
二,Live Unit Testing
Vs2017中的Live Unit Testing功能非常牛,让你一边写UT,一边就看到UT的执行结果,和被测试类的覆盖率。
具体介绍:http://www.dotnetcurry.com/visualstudio/1363/live-unit-testing-visual-studio-2017
另外面向接口编程,做UT的时候,应该都会用到Mock。项目中使用的Rhino.Mocks。
具体介绍:https://spin.atomicobject.com/2017/08/07/intro-mocking-moq/
三,How to: Deploy Files for Tests