Bạn có thể sử dụng tiêm phụ thuộc hàm tạo. Ví dụ:
public class SingletonDependedClass
{
private string _ProviderName;
public SingletonDependedClass()
: this(ConfigurationManager.ConnectionStrings["main_db"].ProviderName)
{
}
public SingletonDependedClass(string providerName)
{
_ProviderName = providerName;
}
}
Điều đó cho phép bạn chuyển chuỗi kết nối trực tiếp đến đối tượng trong khi thử nghiệm.
Ngoài ra nếu bạn sử dụng khung kiểm thử Visual Studio Team Edition, bạn có thể tạo hàm tạo với tham số riêng và kiểm tra lớp thông qua trình truy cập.
Thực ra tôi giải quyết vấn đề đó với chế nhạo. Ví dụ:
Bạn có một lớp mà phụ thuộc vào singleton:
public class Singleton
{
public virtual string SomeProperty { get; set; }
private static Singleton _Instance;
public static Singleton Insatnce
{
get
{
if (_Instance == null)
{
_Instance = new Singleton();
}
return _Instance;
}
}
protected Singleton()
{
}
}
public class SingletonDependedClass
{
public void SomeMethod()
{
...
string str = Singleton.Insatnce.SomeProperty;
...
}
}
Trước hết SingletonDependedClass
cần phải được refactored để có Singleton
dụ như tham số constructor:
public class SingletonDependedClass
{
private Singleton _SingletonInstance;
public SingletonDependedClass()
: this(Singleton.Insatnce)
{
}
private SingletonDependedClass(Singleton singletonInstance)
{
_SingletonInstance = singletonInstance;
}
public void SomeMethod()
{
string str = _SingletonInstance.SomeProperty;
}
}
Test of SingletonDependedClass
(Moq mocking library được sử dụng):
[TestMethod()]
public void SomeMethodTest()
{
var singletonMock = new Mock<Singleton>();
singletonMock.Setup(s => s.SomeProperty).Returns("some test data");
var target = new SingletonDependedClass_Accessor(singletonMock.Object);
...
}
Thông báo lỗi chính xác là gì? – Kane
Null pointer exception – yeyeyerman