How to use Interface IObjectFactory2 class of org.testng package

Best Testng code snippet using org.testng.Interface IObjectFactory2

Run Testng automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package info.stasha.testosterone.jersey.testng;
2
3import info.stasha.testosterone.SuperTestosterone;
4import info.stasha.testosterone.TestInstrumentation;
5import info.stasha.testosterone.Utils;
6import info.stasha.testosterone.testng.AfterClassAnnotation;
7import info.stasha.testosterone.testng.BeforeClassAnnotation;
8import java.util.logging.Level;
9import java.util.logging.Logger;
10import org.testng.IObjectFactory2;
11import org.testng.ITestObjectFactory;
12import org.testng.annotations.ObjectFactory;
13
14/**
15 * TestNG Testosterone
16 *
17 * @author stasha
18 */
19public interface Testosterone extends info.stasha.testosterone.jersey.junit4.Testosterone {
20
21    @ObjectFactory
22    default ITestObjectFactory getFactory() {
23        return new TestObjectFactory();
24    }
25
26    /**
27     * Factory for creating new test class instances.
28     *
29     * @return
30     */
31    public static class TestObjectFactory implements IObjectFactory2 {
32
33        @Override
34        public Object newInstance(Class<?> cls) {
35            try {
36                if (!Utils.isTestosterone(cls)) {
37                    return cls.newInstance();
38                }
39                
40                return TestInstrumentation.testClass((Class<? extends SuperTestosterone>) cls,
41                        new BeforeClassAnnotation(), new AfterClassAnnotation()).newInstance();
42            } catch (Throwable ex) {
43                Logger.getLogger(TestObjectFactory.class.getName()).log(Level.SEVERE, null, ex);
44                throw new RuntimeException(ex);
45            }
46        }
47
48    }
49
50}
51
Full Screen
copy
1/*
2 * The MIT License (MIT)
3 *
4 * Copyright (c) 2016 NovaTec Consulting GmbH
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25package info.novatec.smoketest.core.service.testing;
26
27import com.beust.jcommander.internal.Lists;
28import com.google.common.base.Strings;
29import com.google.inject.Injector;
30import info.novatec.smoketest.core.SmokeTestConfiguration;
31import info.novatec.smoketest.core.application.Environment;
32import org.testng.IObjectFactory2;
33import org.testng.IReporter;
34import org.testng.TestNG;
35
36import javax.inject.Inject;
37import java.util.Arrays;
38import java.util.List;
39
40/**
41 * TestNG implementation of {@link ITestExecutionService}.
42 *
43 * @author Claudio Waldvogel (claudio.waldvogel@novatec-gmbh.de)
44 */
45public class TestExecutionService implements ITestExecutionService {
46
47    /**
48     * The very last fallback output directory name.
49     */
50    private static final String DEFAULT_OUTPUT_DIRECTORY = "test-results";
51
52    /**
53     * The Gucie Injector which is used to enable dependency injection to test classes.
54     */
55    private Injector injector;
56
57    /**
58     * The running {@link Environment}.
59     */
60    private Environment<?> environment;
61
62    /**
63     * The effective {@link SmokeTestConfiguration}.
64     */
65    private SmokeTestConfiguration configuration;
66
67    /**
68     * The {@link TestNG} instance.
69     */
70    private TestNG testNG;
71
72    /**
73     * The list of all applied {@link IReporter}s.
74     */
75    private List<IReporter> reporters;
76
77    /**
78     * The output directory name.
79     */
80    private String outputDirectory = DEFAULT_OUTPUT_DIRECTORY;
81
82
83    /**
84     * Creates a new  TestExecutionService.
85     *
86     * @param injector
87     *         The Gucie {@link Injector}
88     * @param environment
89     *         The {@link Environment}
90     * @param configuration
91     *         The {@link SmokeTestConfiguration}
92     */
93    @Inject
94    public TestExecutionService(final Injector injector,
95                                final Environment environment,
96                                final SmokeTestConfiguration configuration) {
97        this.injector = injector;
98        this.environment = environment;
99        this.configuration = configuration;
100        this.reporters = Lists.newArrayList();
101    }
102
103    //-------------------------------------------------------------
104    // Interface Implementation: ITestExecutionService
105    //-------------------------------------------------------------
106
107    @Override
108    public void execute() {
109        execute(environment.getTests());
110    }
111
112    @Override
113    public void execute(Class<?>... tests) {
114        execute(Arrays.asList(tests));
115    }
116
117    @Override
118    public void execute(List<Class<?>> tests) {
119        initializeOutputDirectory();
120        initializeTestNG();
121        testNG.setTestClasses(tests.toArray(new Class[tests.size()]));
122        testNG.run();
123    }
124
125    @Override
126    public void addReporter(Class<? extends IReporter> clazz) {
127        addReporter(environment.getInjector().getInstance(clazz), false);
128    }
129
130    @Override
131    public void addReporter(IReporter reporter) {
132        addReporter(reporter, true);
133    }
134
135    @Override
136    public void setReportDirectory(String outputDirectory) {
137        this.outputDirectory = outputDirectory;
138    }
139
140    //-------------------------------------------------------------
141    // Methods: Internals
142    //-------------------------------------------------------------
143
144    /**
145     * Actually adds the reporter. If the the reporter was not instantiated with the Injector, the dependency injection
146     * are injected
147     *
148     * @param reporter
149     *         The reporter to be added
150     * @param performInjection
151     *         Flag to indicate if dependencies should be injected
152     */
153    private void addReporter(final IReporter reporter,
154                             boolean performInjection) {
155        if (performInjection) {
156            this.environment.getInjector().injectMembers(reporter);
157        }
158        this.reporters.add(reporter);
159    }
160
161    /**
162     * Set the output directory.
163     */
164    private void initializeOutputDirectory() {
165        if (Strings.isNullOrEmpty(outputDirectory)) {
166            if (!Strings.isNullOrEmpty(configuration.getReportDirectory())) {
167                outputDirectory = configuration.getReportDirectory();
168            } else {
169                outputDirectory = DEFAULT_OUTPUT_DIRECTORY;
170            }
171        }
172    }
173
174    /**
175     * Initializes the TestNG test suite.
176     */
177    private void initializeTestNG() {
178        if (testNG == null) {
179            testNG = new TestNG(false);
180            testNG.setDefaultSuiteName(environment.getName());
181            testNG.setDefaultTestName("Unnamed (@Test missing)");
182            testNG.setOutputDirectory(outputDirectory);
183            //Add all reports as listener to the testNG engine
184            reporters.forEach(reporter -> testNG.addListener(reporter));
185            //We enable dependency injection to test classes by defining an IObjectFactory2
186            //which instantiates all test classes by using the Gucie Injector
187            testNG.setObjectFactory((IObjectFactory2) clazz -> this.injector.getInstance(clazz));
188        }
189    }
190
191}
192
Full Screen
copy
1package org.testng;
2
3
4/**
5 * Factory used to create all test instances. This object factory only receives the class
6 * in parameter.
7 *
8 * @see org.testng.IObjectFactory
9 *
10 * @author Cedric Beust <cedric@beust.com>
11 *
12 * @since 5.14.6
13 */
14public interface IObjectFactory2 extends ITestObjectFactory {
15  Object newInstance(Class<?> cls);
16}
17
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

...Most popular Stackoverflow questions on Interface-IObjectFactory2

    No relevant questions found for this class 😞

Most used methods in Interface-IObjectFactory2

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)