結構..彈簧自動裝配Autowired字段爲null上測試幫助器類
src/test/java
config
TestConfiguration.java
hooks
WebDriverHooks.java
nicebank
RunSteps.java
OtherSteps..
support
ATMUserInterface.java
KnowsTheDomain.java
@Autowired
在nicebank
包放置步驟時被正確地注入KnowsTheDomain
。但我無法@Autowired
KnowsTheDomain
放入Helper類如WebDriverHooks
和ATMUserInterface
自動裝配不同的軟件包時未要求配置註解是什麼時候?我正在運行黃瓜亞軍..
從WebDriverHook.java和ATMUserInterface.java,字段private KnowsTheDomain helper;
返回null而不是單例實例。我需要他們返回當我運行nicebank
包中的步驟時返回的內容。
任何人都知道爲什麼這個helper
字段爲空?
TestConfiguration.java
@Configuration
@ComponentScan(basePackages = { "support"})
public class TestConfiguration {
@Bean
public static KnowsTheDomain knowsTheDomain() {
return new KnowsTheDomain();
}
}
WebDriverHooks.java
@ContextConfiguration(classes = TestConfiguration.class, loader=AnnotationConfigContextLoader.class)
@Configurable(autowire = Autowire.BY_TYPE)
public class WebDriverHooks {
@Autowired
private KnowsTheDomain helper;
@After
public void finish(Scenario scenario) {
try {
byte[] screenshot =
helper.getWebDriver().getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshot, "image/png");
} catch (WebDriverException somePlatformsDontSupportScreenshots) {
System.err.println(somePlatformsDontSupportScreenshots.getMessage());
}
finally {
helper.getWebDriver().close();
}
}
}
RunSteps.java - 這個運行黃瓜亞軍..
@RunWith(Cucumber.class)
@CucumberOptions(
plugin = {"pretty", "html:out"},
snippets = SnippetType.CAMELCASE,
features = "classpath:cucumber",
dryRun = false)
@ContextConfiguration(classes = TestConfiguration.class)
public class RunSteps {
}
KnowsTheDomain.java
@Component
public class KnowsTheDomain {
private Account myAccount;
private CashSlot cashSlot;
private Teller teller;
private EventFiringWebDriver webDriver;
public Account getMyAccount() {
if (myAccount == null) {
myAccount = new Account();
}
return myAccount;
}
public CashSlot getCashSlot() {
if (cashSlot == null) {
cashSlot = new CashSlot();
}
return cashSlot;
}
public Teller getTeller() {
if (teller == null) {
teller = new ATMUserInterface();
}
return teller;
}
public EventFiringWebDriver getWebDriver() {
if (webDriver == null) {
System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver_win32/chromedriver.exe");
webDriver = new EventFiringWebDriver(new ChromeDriver());
}
return webDriver;
}
}
ATMUserInterface.java
@ContextConfiguration(classes = TestConfiguration.class, loader=AnnotationConfigContextLoader.class)
@Configurable(autowire = Autowire.BY_TYPE)
public class ATMUserInterface implements Teller {
@Autowired
private KnowsTheDomain helper;
@Override
public void withdrawFrom(Account account, int dollars) {
try {
helper.getWebDriver().get("http://localhost:" + ServerHooks.PORT);
helper.getWebDriver().findElement(By.id("Amount"))
.sendKeys(String.valueOf(dollars));
helper.getWebDriver().findElement(By.id("Withdraw")).click();
} catch (Exception e) {
System.err.println("err" + e);
}
}
}
'@ Configurable'需要充分AOP是工作,這需要一些設置。最好的選擇幾乎總是切換到構造函數注入。 – chrylis