View Javadoc
1   /*
2    * Copyright 2009 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.openehealth.ipf.commons.xml;
17  
18  import org.junit.Assert;
19  import org.junit.Before;
20  import org.junit.Test;
21  import org.openehealth.ipf.commons.core.modules.api.ValidationException;
22  
23  import javax.xml.transform.Source;
24  import javax.xml.transform.stream.StreamSource;
25  import java.lang.reflect.Field;
26  import java.util.Map;
27  
28  public class XsdValidatorTest {
29  
30  	private XsdValidator validator;
31  	private Map<String, ?> cache;
32  	private static final String SCHEMA_RESOURCE = "/xsd/test.xsd";
33  
34  	@Before
35  	public void setUp() throws Exception {
36  		validator = new XsdValidator();
37  
38  		Field field = XsdValidator.class.getDeclaredField("XSD_CACHE");
39  		field.setAccessible(true);
40  		cache = (Map<String, ?>) field.get(null);
41  	}
42  
43  	@Test
44  	public void testValidate() throws Exception {
45  		cache.clear();
46  		Source testXml = new StreamSource(getClass().getResourceAsStream("/xsd/test.xml"));
47  		validator.validate(testXml, SCHEMA_RESOURCE);
48  		Assert.assertTrue(cache.containsKey(SCHEMA_RESOURCE));
49  	}
50  
51  	@Test(expected = ValidationException.class)
52  	public void testValidateFails() throws Exception {
53  		boolean schemaExisted = cache.containsKey(SCHEMA_RESOURCE);
54  		int cacheSize = cache.size();
55  		Source testXml = new StreamSource(getClass().getResourceAsStream(
56  				"/xsd/invalidtest.xml"));
57  		validator.validate(testXml, SCHEMA_RESOURCE);
58  		if (schemaExisted) {
59  			Assert.assertEquals(cacheSize, cache.size());
60  		} else {
61  			Assert.assertEquals(cacheSize + 1, cache.size());
62  		}
63  	}
64  
65  }