我避免耦合和促進再使用性的方法是:
1)組我的步驟由實體,像AccountRepositorySteps(對於AccountRepository)或AccountControllerSteps(爲的AccountController)。 2.)使步驟依賴於抽象,而不是混凝土(就像我們的生產代碼一樣)。
3.)依靠當前的ScenarioContext在步驟和步驟文件之間傳遞值。
這裏有一個簡單的例子:
Given a guy with the name Darren exists
And a guy with the name John exists
When I hit the guy page
Then I should see two guys
RepositorySteps.cs
private List<string> guys;
[BeforeScenario]
public void Setup(){
guys = new List<string>();
var fake = new Mock<IRepository>();
fake.Setup(x=>x.GetGuys()).Returns(guys);
ScenarioContext.Current.Set(fake) // Mock<IRepository>
ScenarioContext.Current.Set(fake.Object); // IRepository
}
[Given("a guy with the name '(.*)' exists"]
public void a(string guy){
guys.Add(guy);
// and if I need to pull out the mock, I can do it like so
var fake = ScenarioContext.Current.Get<Mock<IRepository>>();
}
GuyController.cs
When["I hit the guy page"]
public void x(){
var repository = ScenarioContext.Current.Get<IRepository>();
var controller = new GuyController(repository);
var result = controller.Index();
ScenarioContext.Current.Set(result);
}
看,這裏的GuyController步驟獲取模仿對象,但他不知道這是一個模擬。對他來說這只是一個IRepository。如果出於某種原因,您需要加載IRepository的REAL存儲庫並想運行您的規格,那麼您只需將ScenarioContext加載到真正的IRepository中即可。
按照這種模式,我的步驟是非常脫鉤,並保護我免受其他人的變化。它比我在使用SpecFlow時所做的技巧要好得多,我會在同一個步驟文件中使用靜態方法或組無關的步驟。
哎呀!舊帖子。 – 2012-09-27 11:17:48