Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

java - How to inject parameter into constructor of TestNG class?

I have implemented a programm with the strategy pattern. So I have an interface which is used at some places and the concrete implementation may be replaced.

Now I want to test this programm. I would like to do it in a similar way. Write a test once, which tests against the interface. The concrete interface implementation should be injected at the beginning of the test, so that I may replace it easily.

My testclass looks similar to this one:

public class MyTestClass {

    private StrategeyInterface strategy;

    public MyTestClass(StrategeyInterface strategy) {
        this.strategy = strategy;
    }
    ....test methods using the strategy.
}

The parameterized contructor must used to be inject the concrete strategy implementation at thr beginning og the tests.

Now I did not get TestNG to run it and inject the concrete implementation instance. I tried several ways with inheritance, @DataProvider, @Factory and the corresponding methods, but without luck.

Here is what the testNG report says:

Can't invoke public void MyClass.myTestMethod(): either make it static or add a no-args constructor to your class

I use the maven surefire plugin to run the tests. Here is the relevant part of the pom.xml:

    <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <suiteXmlFiles>
                    <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
                </suiteXmlFiles>
            </configuration>
        </plugin>
    </plugins>
</build>

How do I write and run the tests, with injecting a concrete implementation into the test class?

Thanks in advance.

P.S. I could deliver more code I tried. I did not post it here, yet, because I tried so many variants so that I am kind of confused now and all of them fail.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have several options. If you are using Guice, here is a very straightforward way to inject your implementation.

If not, you can use a mix of factories and data provider:

@Factory(dataProvider = "dp")
public FactoryDataProviderSampleTest(StrategyInterface si) {
}

@DataProvider
static public Object[][] dp() {
  return new Object[][] {
    new Object[] { new Strategy1Impl() },
    new Object[] { new Strategy2Impl() },
  };
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...