Nếu bạn không muốn kiểm tra thực tế là các sợi thực sự ngủ, một cách tiếp cận đơn giản hơn (và một trong đó là có thể) là có một ISleepService. Sau đó bạn có thể giả lập điều này, và sau đó không ngủ trong các thử nghiệm của bạn, nhưng có một thực hiện mà gây ra một Thread.Sleep trong mã sản xuất của bạn.
ISleepService sleepService = Container.Resolve<ISleepService>();
..
while (running)
{
...
// Work
...
sleepService.Sleep(Interval);
}
Ví dụ sử dụng Moq:
public interface ISleepService
{
void Sleep(int interval);
}
[Test]
public void Test()
{
const int Interval = 1000;
Mock<ISleepService> sleepService = new Mock<ISleepService>();
sleepService.Setup(s => s.Sleep(It.IsAny<int>()));
_container.RegisterInstance(sleepService.Object);
SomeClass someClass = _container.Resolve<SomeClass>();
someClass.DoSomething(interval: Interval);
//Do some asserting.
//Optionally assert that sleep service was called
sleepService.Verify(s => s.Sleep(Interval));
}
private class SomeClass
{
private readonly ISleepService _sleepService;
public SomeClass(IUnityContainer container)
{
_sleepService = container.Resolve<ISleepService>();
}
public void DoSomething(int interval)
{
while (true)
{
_sleepService.Sleep(interval);
break;
}
}
}
Cập nhật
Trên một thiết kế \ bảo trì lưu ý, nếu nó là đau đớn để thay đổi các nhà xây dựng của "SomeClass", hoặc để thêm Dependency Injection trỏ đến người dùng của lớp, sau đó mẫu kiểu trình định vị dịch vụ có thể trợ giúp tại đây, ví dụ:
private class SomeClass
{
private readonly ISleepService _sleepService;
public SomeClass()
{
_sleepService = ServiceLocator.Container.Resolve<ISleepService>();
}
public void DoSomething(int interval)
{
while (true)
{
_sleepService.Sleep(interval);
break;
}
}
}
Nguồn
2010-08-03 15:57:31
Thực sự thay đổi giá trị của đồng hồ (mà tôi chắc chắn bạn không muốn làm), bạn sẽ không có thể nhận được kết quả bạn đang tìm kiếm. –
Giải pháp ưu tiên là cách ly chức năng định thời với một dịch vụ để bạn có thể thử dịch vụ cho các bài kiểm tra của mình. Nếu bạn không thể làm điều này (thường vì nó là một codebase hiện có), thì một cách khác là sử dụng một khung như Moles để hủy bỏ các cuộc gọi tĩnh: http://research.microsoft.com/en-us/projects/moles/ –