Make xml resource customizable, and do tests in java?

I need to test more than 100 different situations, and for each of them I need an external xml that needs to be read and analyzed. I use:

String xml = IOUtils.toString(
                this.getClass().getResourceAsStream(path),encoding);

For example, my xml test:

<container xmlns:dmc="http://example.com/common">
    <object id="1369" checkedParamter="in" class="Class1">
...

</object>
</container>

But I need to check ivalid id with missing id, with existing id. Then I need checkedParamter to have 3-4 values ​​and combine all the combinations with the id attribute. For each test, I now create a new xml , and the only difference is that these are two id and checkedParamter attributes . I wonder if there is an easy way to read xml and use the same structure, but pass these values ​​from my test.

 <container xmlns:dmc=" http://example.com/common">
        <object id= ${valueId} checkedParamter=${valueChechedParamter} class="Class1">
    ...

    </object>
    </container>

xml . ?

+4
2

- ${valueId}, .

JUnit :

  • - .

resources :

<container xmlns:dmc=" http://example.com/common">
    <object id= ${valueId} checkedParamter=${valueChechedParamter} class="Class1">
        ...
    </object>
</container>

:

@RunWith(Parameterized.class)
public class XmlInputTest {

@Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
                 { 1369, "in" }, 
                 { 1369, "out" }, 
                 { 753, "in" }, 
                 // etc.... 
           });
    }



@Parameter(value = 0)
public int id;

@Parameter(value = 1)
public String checkedParamter;

@Test
public void mainTest() {
    String xml = IOUtils.toString(
         this.getClass().getResourceAsStream("template.xml"),encoding);
    xml = xml.replace("${valueId}",String.valueOf(id)).replace("${valueChechedParamter}",checkedParamter);

    // remaing test....
}
}

, .

+2

- .

Map<String,String> properties = new HashMap<String, String>();
properties.put("valueId", "1");
properties.put("valueChechedParamter", "0");

String propertyRegex = "\\$\\{([^}]*)\\}";
Pattern pattern = Pattern.compile(propertyRegex);

int i = 0;
Matcher matcher = pattern.matcher(xml);
StringBuilder result = new StringBuilder(xml.length());
while(matcher.find()) {
    result.append(expression.substring(i, matcher.start()));
    String property = matcher.group();
    property = property.substring(2, property.length() - 1);
    if(properties.containsKey(property)) {
        property = properties.get(property);
    } else {
        property = matcher.group();
    }
    result.append(property);
    i = matcher.end();
}

result.append(expression.substring(i));
String resultXml = result.toString();
+1

Source: https://habr.com/ru/post/1626837/


All Articles