我避免耦合和促进再使用性的方法是:
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