I am developing unit tests that can benefit from a lot from reusability when it comes to creation of test dat开发者_运维技巧a. However, there are different things (API calls) I need to do with the same test data (API args).
I am wondering if the following idiom is possible in Java.
Class RunTestScenarios {
void runScenarioOne (A a, B b, C c) {
........
}
void runScenarioTwo (A a, B b, C c) {
........
}
void runScenario (/* The scenario */ scenarioXXX) {
A a = createTestDataA();
B b = createTestDataB();
C c = createTestDataC();
scenarioXXX(a, b, c);
}
public static void main (String[] args) {
runScenario(runScenarioOne);
runScenario(runScenarioTwo);
}
}
Essentially, I dont want to have something like the following repeated everywhere:
A a = createTestDataA();
B b = createTestDataB();
C c = createTestDataC();
To my knowledge such aliasing (scenarioXXX) is not possible but I will be happy to be corrected or if anyone can suggest possible design alternatives to accomplish this effect.
Btw, I am aware of Command Pattern to get this done. But not what I am looking for.
Thanks, US
- Use jUnit.
- Convert a,b & c to fields.
- Use jUnit's
setUp
andtearDown
methods to initialise fresh objects for each test.
No, you cannot do that in Java. Not without lambda support (don't hold your breath...). You can do that in Scala, for example using ScalaTest. And probably in some other JVM languages.
In Java, the idiom is to wrap these functions with anonymous classes, perhaps implementing an interface defining the method to run.
One way you can achieve this is by using intefaces:-
- Modify the
runScenario()
method to accept that interface as an argument. - Implement the inteface for each scenario types and pass the one that you need for the scenario testing.
Generally unit testing in java is done by using jUnit if you already did not know about it. There are many tutorials available and one such can be found here.
I'm not sure to quite get what you need, but it seems to me that you can use DataProvider
that TestNG provides.
Is something like this:
...
@Test(dataProvider="someMethodWithDataProviderAnnotation")
void runScenarioOne (A a, B b, C c) {
...
}
@Test(dataProvider="someMethodWithDataProviderAnnotation")
void runScenarioTwo (A a, B b, C c) {
...
}
And then you craete your data provider:
@DataProvider(name="someMethodWithDataProviderAnnotation")
private Object [][] getTestData() {
return new Object[]][] {{
createTestDataA(),
createTestDataB(),
createTestDataC()
}};
}
And that's it, when you run your test they will be invoked with the right parameters which will be creates only once. Although this is more useful when you have to load a lot of resources, for instance, all the files in a directory or something like that.
You just run all the methods in the class.
Read more here:
http://testng.org/doc/documentation-main.html#parameters-dataproviders
BTW: TestNG is included as plugin in Intellj IDEA
精彩评论