I migrated my Spring tests to JUnit 5, and they work fine. However, I don't know how to migrate #Rule public JUnitRestDocumentation restDocumentation = ....
Any hint is appreciated.
Spring RestDocs 2 introduces a new class : RestDocumentationExtension for JUnit 5. You can use it instead of Rule
#ExtendWith(RestDocumentationExtension.class)
public class JUnit5ExampleTests {
A complete example is available on https://github.com/spring-projects/spring-restdocs/blob/v2.0.0.RELEASE/samples/junit5/src/test/java/com/example/junit5/SampleJUnit5ApplicationTests.java
The extension is documented on https://github.com/spring-projects/spring-restdocs/blob/master/docs/src/docs/asciidoc/getting-started.adoc#setting-up-your-junit-5-tests
Spring RestDocs 2 requires Spring 5 and JDK 8
Until the issue is officially resolved, I was able to get it working with a JUnit 5 extension (below).
Using that extension, I modified my test class thusly:
#ExtendWith(RestDocsExtension.class)
and
#BeforeEach
void setUp(WebApplicationContext wac, ManualRestDocumentation restDocumentation) throws Exception {
Here is the Extension.
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ContainerExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.TestExtensionContext;
import org.springframework.restdocs.ManualRestDocumentation;
import java.lang.reflect.Method;
import java.util.Optional;
public class RestDocsExtension implements BeforeAllCallback, BeforeEachCallback, AfterEachCallback, ParameterResolver {
private static final String REST_DOC_STORE_KEY = "restDocumentation";
private ManualRestDocumentation restDocumentation;
#Override
public void beforeAll(ContainerExtensionContext context) throws Exception {
if (restDocumentation == null) {
restDocumentation = new ManualRestDocumentation("target/generated-snippets");
getStore(context).put(REST_DOC_STORE_KEY, restDocumentation);
}
}
#Override
public void beforeEach(TestExtensionContext context) throws Exception {
Optional<Class<?>> testClass = context.getTestClass();
Optional<Method> methodNameOpt = context.getTestMethod();
if (testClass.isPresent() && methodNameOpt.isPresent()) {
getDoc(context).beforeTest(testClass.get().getClass(), methodNameOpt.get().getName());
} else {
throw new Exception("TestExtensionContext with no class or method. wat");
}
}
#Override
public void afterEach(TestExtensionContext context) throws Exception {
getDoc(context).afterTest();
}
#Override
public boolean supports(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return parameterContext.getParameter().getType() == ManualRestDocumentation.class;
}
#Override
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return getDoc(extensionContext);
}
private ManualRestDocumentation getDoc(ExtensionContext context) {
return (ManualRestDocumentation) getStore(context).get(REST_DOC_STORE_KEY);
}
private ExtensionContext.Store getStore(ExtensionContext context) {
return context.getStore(ExtensionContext.Namespace.DEFAULT);
}
}
Related
I am trying to create mock instance of the class which is autowired inside Verticle but I am getting it as a null. For synchronous code the way which works is looking not useful for Vert.x.
Verticle is:
#Component
public class MyVerticle extends AbstractVerticle{
#Autowired
private ServiceExecutor serviceExecutor;
#Override
public void start() throws Exception {
super.start();
vertx.eventBus().<String>consumer("address.xyz").handler(handleRequest());
}
private Handler<Message<String>> handleRequest() {
return msg -> {
getSomeData(msg.body().toString())
.setHandler(ar -> {
if(ar.succeeded()){
msg.reply(ar.result());
}else{
msg.reply(ar.cause().getMessage());
}
});
};
}
private Future<String> getSomeData(String inputJson) {
Promise<String> promise = Promise.promise();
String data = serviceExecutor.executeSomeService(inputJson); // Getting NPE here. serviceExecutor is coming as null when trying to create mock of it using Mockito.when.
promise.complete(data);
return promise.future();
}
}
Dependent component is:
#Component
public class ServiceExecutor {
public String executeSomeService(String input){
return "Returning Data";
}
}
Test case is:
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
#RunWith(VertxUnitRunner.class)
public class MyVerticleTest {
#Mock
private ServiceExecutor serviceExecutor;
private Vertx vertx;
#Before
public void setup(TestContext ctx){
MockitoAnnotations.initMocks(this);
Async async = ctx.async();
this.vertx = Vertx.vertx();
vertx.deployVerticle(MyVerticle.class.getName(), h -> {
if(h.succeeded()){
async.complete();
}else{
ctx.fail();
}
});
}
#Test
public void test_consumption(TestContext ctx) {
Async async = ctx.async();
when(serviceExecutor.executeSomeService(Mockito.anyString())).thenReturn("Returning Data");
vertx.eventBus().request("address.xyz","message", h ->{
if(h.succeeded()){
ctx.assertEquals("Returning Data",h.result().body().toString());
async.complete();
}else{
ctx.fail(h.cause());
}
});
}
}
Above Test Case works well if I don't use autowired instance to call a method to get the date. But if used it (which I must do to get the data), it is giving NPE at MyVerticle->getSomeData() method when trying to use serviceExecutor object as a mock. This approach works very well for Synchronous code flow but for Vert.x looks like it won't help. So need help here to mock the autowired instance serviceExecutor inside Verticle.
Add a constructor in your MyVerticle
public MyVerticle(ApplicationContext context) {
context.getAutowireCapableBeanFactory().autowireBean(this);
}
and deploy your verticle something like vertx.deployVerticle(new MyVerticle(context),...
I have application context while deploying the verticle and thats what I am passing in the constructor. Check if this works for you.
I am writing unit test cases for following class which extends WCMUsePOJO. Now, this class is using a getSlingScriptHelper method shown below.
public class ConstantsServiceProvider extends WCMUsePojo {
private static final Logger logger = LoggerFactory.getLogger(ConstantsServiceProvider.class);
private String var1;
#Override
public void activate() throws Exception {
ConstantsService constantsService = getSlingScriptHelper().getService(ConstantsService.class);
if(constantsService != null) {
var1 = constantsService.getVar1();
}
}
public string getVar1() { return var1; }
}
The question is how do I mock getSlingScriptHelper method? Following is my unit test code.
public class ConstantsServiceProviderTest {
#Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_MOCK);
#Mock
public SlingScriptHelper scriptHelper;
public ConstantsServiceProviderTest() throws Exception {
}
#Before
public void setUp() throws Exception {
ConstantsService service = new ConstantsService();
scriptHelper = context.slingScriptHelper();
provider = new ConstantsServiceProvider();
provider.activate();
}
#Test
public void testGetvar1() throws Exception {
String testvar1 = "";
String var1 = provider.getVar1();
assertEquals(testvar1, var1);
}
}
The only thing that you should "have to"* mock is the SlingScriptHelper instance itself, so that it will mimic the dependency injection of the declared service.
Everything else (e.g. the Bindings instance) can be a concrete implementation, for example:
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.junit.Test;
import javax.script.Bindings;
import javax.script.SimpleBindings;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ConstantsServiceProviderTest {
private SlingScriptHelper mockSling = mock(SlingScriptHelper.class);
private ConstantsServiceProvider constantsServiceProvider = new ConstantsServiceProvider();
private Bindings bindings = new SimpleBindings();
#Test
public void testFoo() throws Exception {
//Arrange
final String expected = "Hello world";
final ConstantsService testConstantsService = new TestConstantsService(expected);
when(mockSling.getService(ConstantsService.class)).thenReturn(testConstantsService);
bindings.put(SlingBindings.SLING, mockSling);
//Act
constantsServiceProvider.init(bindings);
//Assert
final String actual = constantsServiceProvider.getVar1();
assertThat(actual, is(equalTo(expected)));
}
class TestConstantsService extends ConstantsService {
String var1 = "";
TestConstantsService(String var1) {
this.var1 = var1;
}
#Override
String getVar1() {
return var1;
}
}
}
The entry point here, as you said above, is via the init() method of the WCMUsePojo superclass (as this method is an implementation of the Use.class interface, this test structure also works for testing that via that interface, even if you don't use WCMUsePojo directly.)
*this could be any type of test-double, not necessarily a mock.
You shouldn't create a mock for ConstantsServiceProvider.class if you want to unit-test it. Instead, you should create mocks of its internal objects. So:
Create real instance of ConstantsServiceProvider with new
Mock objects that are returned by getSlingScriptHelper().getService(.) methods. Usually, dependencies are provided (injected) to classes by some container like Spring or simply provided by other classes of your app using setters. In both cases mocks creation is easy.
If your current implementation doesn't allow this - consider refactoring.
You are testing void activate() method which doesn't return anything. So, you should verify calling constantsService.getVar1() method.
I strongly advice you to study Vogella unit-testing tutorial
Here one of possible solution.
The main idea is to have a real object of your class but with overridden getSlingScriptHelper() to return mocked scriptHelper.
I mocked the ConstantsService as well but may be not needed, I don't know your code.
public class ConstantsServiceProviderTest {
#Mock
public SlingScriptHelper scriptHelper;
#Test
public void getVar1ReturnsActivatedValue() throws Exception {
// setup
final String expectedResult = "some value";
// Have a mocked ConstantsService, but if possible have a real instance.
final ConstantsService mockedConstantsService =
Mockito.mock(ConstantsService.class);
Mockito.when(
mockedConstantsService.getVar1())
.thenReturn(expectedResult);
Mockito.when(
scriptHelper.getService(ConstantsService.class))
.thenReturn(mockedConstantsService);
// Have a real instance of your class under testing but with overridden getSlingScriptHelper()
final ConstantsServiceProvider providerWithMockedHelper =
new ConstantsServiceProvider() {
#Override
SlingScriptHelper getSlingScriptHelper() {
return scriptHelper;
}
};
// when
String actualResult = providerWithMockedHelper.getVar1();
// then
assertEquals(expectedResult, actualResult);
}
}
package com.dh.inheritance;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class Client6{
public static void main(String[] args){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enableDefaultTyping();
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT);
objectMapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
objectMapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);
objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true);
objectMapper.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, true);
objectMapper.registerModule(new MyModule());
try {
String test = null;
test.length();
} catch (Exception e) {
try {
String jsonString = objectMapper.writeValueAsString(e);
System.out.println(jsonString);
**objectMapper.readValue(jsonString, e.getClass());**
} catch (JsonProcessingException e1) {
e1.printStackTrace();
}
}
}
}
package com.dh.inheritance;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
public abstract class MixIn {
#JsonIdentityInfo(generator=ObjectIdGenerators.StringIdGenerator.class, property="$id")
private Throwable cause;
}
package com.dh.inheritance;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class MyModule extends SimpleModule{
public MyModule() {
super("test", new Version(2, 7, 2, null));
}
#Override
public void setupModule(SetupContext context) {
context.setMixInAnnotations(Throwable.class, MixIn.class);
}
}
{"java.lang.NullPointerException":{"detailMessage":null,"cause":{"java.lang.NullPointerException":{"$id":"912da540-bf85-4e5d-869c-acfaebe85bdf","detailMessage":null,"cause":"912da540-bf85-4e5d-869c-acfaebe85bdf","stackTrace":null}},"stackTrace":null}}
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
Unrecognized field "$id" (class java.lang.NullPointerException), not
marked as ignorable (3 known properties: "cause", "stackTrace",
"detailMessage"]) at [Source:
{"java.lang.NullPointerException":{"detailMessage":null,"cause":{"java.lang.NullPointerException":{"$id":"912da540-bf85-4e5d-869c-acfaebe85bdf","detailMessage":null,"cause":"912da540-bf85-4e5d-869c-acfaebe85bdf","stackTrace":null}},"stackTrace":null}}; line: 1, column: 107] (through reference chain:
java.lang.NullPointerException["$id"]) at
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:62)
at
com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:855)
at
com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1083)
at
com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1389)
at
com.fasterxml.jackson.databind.deser.std.ThrowableDeserializer.deserializeFromObject(ThrowableDeserializer.java:135)
at
com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:133)
at
com.fasterxml.jackson.databind.jsontype.impl.AsWrapperTypeDeserializer._deserialize(AsWrapperTypeDeserializer.java:115)
at
com.fasterxml.jackson.databind.jsontype.impl.AsWrapperTypeDeserializer.deserializeTypedFromObject(AsWrapperTypeDeserializer.java:49)
at
com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeWithType(BeanDeserializerBase.java:1017)
at
com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:488)
at
com.fasterxml.jackson.databind.deser.std.ThrowableDeserializer.deserializeFromObject(ThrowableDeserializer.java:104)
at
com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:133)
at
com.fasterxml.jackson.databind.jsontype.impl.AsWrapperTypeDeserializer._deserialize(AsWrapperTypeDeserializer.java:115)
at
com.fasterxml.jackson.databind.jsontype.impl.AsWrapperTypeDeserializer.deserializeTypedFromObject(AsWrapperTypeDeserializer.java:49)
at
com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeWithType(BeanDeserializerBase.java:1017)
at
com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize(TypeWrappedDeserializer.java:42)
at
com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3789)
at
com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2779)
at com.dh.inheritance.Client6.main(Client6.java:38)
Above exception thrown, when converting json to Object.
I'm writing some integration tests towards my jax-rs service where I have a set of exception mappers. So, when performing a given request I expect a certain response code based on the exception mapper. The problem is that I cannot get the exception mappers to be invoked when running in this environment.
My service which should throw a logicalexception in my test:
#Stateless
#Path("/baseCustomer")
public class BaseCustomerService {
#EJB //this one gets mocked in the unittest
private BaseCustomerManagerBean customerManager;
#POST
#Path("crud")
#Consumes({MediaType.APPLICATION_XML})
#Produces({MediaType.APPLICATION_XML, MediaType.TEXT_XML})
public Hkunde createCustomer(Hkunde newCustomer) throws LogicalException {
//throws exception according to mocking
return customerManager.createCustomer(newCustomer);
}
And the exception mapper:
#Provider
public class LogicalExceptionMapper implements ExceptionMapper<LogicalException> {
#Override
public Response toResponse(LogicalException exception) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
I set up my tests like this:
#Mock
private BaseCustomerManagerBean baseCustomerManager;
private HttpClient httpClient;
private BaseCustomerServiceClient client;
#Configuration
public Properties config() throws Exception {
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.RemoteInitialContextFactory");
properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, Boolean.TRUE.toString());
properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, LogicalExceptionMapper.class.getName());
properties.setProperty("openejb.jaxrs.providers.auto", "true");
properties.setProperty("openejb.servicemanager.enabled", "true");
return properties;
}
#MockInjector
public Class<?> mockitoInjector() {
return MockitoInjector.class;
}
#Module
public EjbModule createModule() throws Exception {
final StatelessBean bean = (StatelessBean) new StatelessBean(BaseCustomerService.class).localBean();
bean.setRestService(true);
final EjbJar ejbJar = new EjbJar();
ejbJar.addEnterpriseBean(bean);
final OpenejbJar openejbJar = new OpenejbJar();
openejbJar.addEjbDeployment(new EjbDeployment(ejbJar.getEnterpriseBeans()[0]));
EjbModule module = new EjbModule(ejbJar);
module.setOpenejbJar(openejbJar);
return module;
}
#Module
public Class[] exceptionMappers() {
return new Class[]{LogicalExceptionMapper.class};
}
#Before
public void setup() {
ServiceHost serviceHost = new ServiceHost("http://localhost:4204/BaseCustomerServiceTest");
httpClient = new HttpClient(serviceHost);
client = new BaseCustomerServiceClient(httpClient);
}
#Test
public void createCustomer_givenLogicalException_expectsLogicalException() throws LogicalException {
Hkunde expected = new Hkunde(true);
when(baseCustomerManager.createCustomer(expected)).thenThrow(new LogicalException("mock"));
try {
client.createCustomer(expected);
fail("Expected LogicalException");
} catch (LogicalException ex) {
}
verify(baseCustomerManager).createCustomer(expected);
}
So when I execute the test, my client will read the response code from the response and throw an exception based on this code.
The problem is that the exception mapper is never invoked, and I always receive a 500 internal server error, instead of the "forbidden" response. I'm guessing I need to add some more info when setting up the ejbjar or something like that.
Thanks!
This example http://svn.apache.org/repos/asf/openejb/trunk/openejb/examples/rest-applicationcomposer/src/test/java/org/superbiz/composed/rest/GreetingServiceTest.java (via http://rmannibucau.wordpress.com/2012/09/13/use-mockito-with-openejb/ ;-)) shows exactly what you want.
Add the following after openejbJar.addEjbDeployment(... and it should work.
final Properties properties = openejbJar.getEjbDeployment().iterator().next().getProperties();
properties.setProperty("cxf.jaxrs.providers", LogicalExceptionMapper.class.getName());
Here is a minimal working example (using openejb-cxf-rs 4.5.0 and openejb-core 4.5.0):
import java.util.Properties;
import javax.ejb.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.openejb.OpenEjbContainer;
import org.apache.openejb.config.EjbModule;
import org.apache.openejb.jee.EjbJar;
import org.apache.openejb.jee.StatelessBean;
import org.apache.openejb.jee.oejb3.EjbDeployment;
import org.apache.openejb.jee.oejb3.OpenejbJar;
import org.apache.openejb.junit.ApplicationComposer;
import org.apache.openejb.junit.Configuration;
import org.apache.openejb.junit.Module;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
#RunWith(ApplicationComposer.class)
public class RestWithExceptionMapper {
#Configuration
public Properties configuration() {
return new Properties() {
{
setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, Boolean.TRUE.toString());
}
};
}
#Module
public EjbModule app() {
final StatelessBean bean = (StatelessBean) new StatelessBean(MyResource.class).localBean();
bean.setRestService(true);
final EjbJar ejbJar = new EjbJar();
ejbJar.addEnterpriseBean(bean);
final OpenejbJar openejbJar = new OpenejbJar();
openejbJar.addEjbDeployment(new EjbDeployment(ejbJar.getEnterpriseBeans()[0]));
final Properties properties = openejbJar.getEjbDeployment().iterator().next().getProperties();
properties.setProperty("cxf.jaxrs.providers", MyExceptionMapper.class.getName());
final EjbModule module = new EjbModule(ejbJar);
module.setOpenejbJar(openejbJar);
return module;
}
public static class FooException extends RuntimeException {
}
public static class MyExceptionMapper implements ExceptionMapper<FooException> {
#Override
public Response toResponse(final FooException t) {
return Response.ok("Objection!").build();
}
}
#Path(value = "/test")
public static class MyResource {
#GET
#Path(value = "/throw")
public String throwException() {
throw new FooException();
}
}
#Test
public void checkServiceWasDeployed() {
assertEquals("Objection!", WebClient.create("http://localhost:4204/RestWithExceptionMapper").path("/test/throw").get(String.class));
}
}
I want to capture a screenshot only upon unexpected exception.
Note.- This answer could be outdated. The answer is based on Selenium 2.15
Using TestWatcher does the trick (the unit test must extend following BaseTest):
public abstract class BaseTest {
// ...
protected WebDriver driver;
#Rule
public TestRule testWatcher = new TestWatcher() {
#Override
public void starting(Description desc) {
LOG.info("Launching browser...");
driver = Utils.getFirefoxDriver();
}
#Override
public void finished(Description desc) {
LOG.info("Quitting driver...");
driver.quit();
}
#Override
public void failed(Throwable e, Description d) {
LOG.debug("Creating screenshot...");
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(
OutputType.FILE);
String scrFilename = "Screenshot.png";
File outputFile = new File(SCREEN_SHOTS_RESULTS_PATH, scrFilename);
LOG.info(scrFilename + " screenshot created.");
try {
org.apache.commons.io.FileUtils.copyFile(scrFile, outputFile);
} catch (IOException ioe) {
LOG.error("Error copying screenshot after exception.", ioe);
}
}
};
}
Note
Utils.getFirefoxDriver() returns a customized WebDriver. Something like:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
public class Utils {
// ...
public static WebDriver getFirefoxDriver() {
FirefoxProfile firefoxProfile = new FirefoxProfile();
// Profile customization. For example:
// firefoxProfile.addExtension("firebug-1.8.4-fx.xpi");
// firefoxProfile.setPreference("extensions.firebug.currentVersion","1.8.4");
FirefoxBinary firefox = new FirefoxBinary();
// Firefox customization. For example:
// firefox.setEnvironmentProperty("DISPLAY", display);
WebDriver driver = new FirefoxDriver(firefox, firefoxProfile);
// WebDriver customizations. For example:
// driver.manage().timeouts().implicitlyWait(SHORT_TIMEOUT_S, TimeUnit.SECONDS);
return driver;
}
}