1.
使用PrivateObject
using (CountyRepository repository = new CountyRepository())
{
PrivateObject accessor = new PrivateObject(repository);
expected = 1;
var returnVal = accessor.Invoke("initialRequestMsg"); // initialRequestMsg 是我們要測試的method name
actual = (returnVal as MsgRequestCounty).Data.Count;
Assert.AreEqual(expected, actual);
}
=> 注意Invoke的時候可以帶入該method需要的參數。
using (CountyRepository repository = new CountyRepository())
{
PrivateObject accessor = new PrivateObject(repository);
expected = 1;
var returnVal = accessor.Invoke("initialRequestMsg"); // initialRequestMsg 是我們要測試的method name
actual = (returnVal as MsgRequestCounty).Data.Count;
Assert.AreEqual(expected, actual);
}
=> 注意Invoke的時候可以帶入該method需要的參數。
2.
將private method改為internal method 並使用[InternalsVisibleTo]屬性
A.
internal method
internal int MyPrivateMethod()
{ return 1; }
internal int MyPrivateMethod()
{ return 1; }
B.
加入[InternalsVisibleTo] 屬性到該Method的namespace
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Icash.StoreManage.Service.Client.Test")]
namespace Icash.StoreManage.Service.Client
=> InternalsVisibleTo必須帶入UnitTest project的namespace
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Icash.StoreManage.Service.Client.Test")]
namespace Icash.StoreManage.Service.Client
=> InternalsVisibleTo必須帶入UnitTest project的namespace
3.
Reference
How to create private accessors in VS 2012
How to create private accessors in VS 2012