What's the difference between DOM and SAX? DOM creates tree-like representation of the XML document in memory, SAX is event-based. 
What's the difference between XSD and DTD? XSD is in XML, DTD is not. XSD is much more comprehensive than DTD
You're given an XML file, and you're supposed to retrieve the value of a specific element in the file. How do you do that? Open-ended question. See how the candidate uses various types of parsers (DOM, SAX, etc) and see if he explores the usage of XPath.
You're supposed to unit test Java class that accesses a database,
in a machine that doesn't have database server installed,
and no external connectivity at all. What's your approach?
Open-ended
question. See if the answer tackles the problem effectively.
See if he/she suggests mocking as an option
How do you ensure your unit tests have covered all paths /
possibilities?
Use
code coverage tool like Cobertura, Emma, etc
How do you unit-test a private method? -
Use Reflection, set accessible property of that method to true
- Call an accessible method that calls the private method and observe the
effect caused by calling the private method

XML Message Verification in B-Puma:

1, First get the XML message from cache component, using the ConsumerTemplate.receiverBody(uri, TIMEOUT, Node.class); and cast to Element.

2, Pass the obtained Element to OrderVerifier constructor which builds a XPathVerifyDelegate(Node):

private static XPath xpath = XPathFactory.newInstance().newXPath();

String actual = xpath.evaluate(key, node); //key is like @limitPrice, the path of the data

在这里,Node是从camel consumerTemplate里直接收到的,如果你的XML在一个file里而且你想用XPath读,你需要首先读进一个DOM object里:

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
    builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
    e.printStackTrace(); 
}
try {
    Document document = builder.parse(newFileInputStream("c:\\employees.xml"));
} catch (SAXException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
//read an xml node using xpath
String expression = "/Employees/Employee[@emplid='3333']/email";
Node node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);

About DOM:

The parser traverses the XML file and creates the corresponding DOM objects. These DOM objects are linked together in a tree structure.

The Node object is the primary data type for the entire DOM. Document不只包括树型元素结构,所以Element这种结构只是获取Document里的树型结构Document.getDocumentElement()。Document和Element都是Node interface的sub-interface。

A node can be an element node, an attribute node, a text node, or any other of the node types explained in the "Node types" chapter. Element is the only kind of node that can have child nodes and attributes.

DOM on the other hand is more robust - it reads the entire XML document into a tree, and is very efficient when you want to alter, add, remove data in that XML tree. XPath is useful when you only need a couple of values from the XML document, and you know where to find them (you know the path of the data, /root/item/challange/text).

如果你用DOM来获取元素:

Element rootElement = document.getDocumentElement();
NodeList nodes = element.getChildNodes();

for(int i=0; i<nodes.getLength(); i++){
Node node = nodes.item(i); if(node instanceof Element){
//a child element to process
Element child = (Element) node;
String attribute = child.getAttribute("width");
}
}

A Node is a part of the DOM tree, an Element is a particular type of Node : e.g. <foo> This is Text </foo>

          (I)Node

(I)Document   (I)Element    (I)Attr

You have a foo Element, (which is also a Node, as Element inherits from Node) and a Text Node 'This is Text', that is a child of the foo Element/Node

XPath为XML Path language: XPath包含一个标准函数库

XPath语法:

nodename        选取名为nodename节点的所有子节点

/                     从根节点选取

//                    选取节点,所有,不管位置

@                    选取属性

Predicates:

例如  //tiltle[@lang]   选取所有属性lang的所有title节点

    /bookstore/book[price>35]/title                    child::*    选取当前节点的所有子元素

    //title| //price    选取若干路径"|"                     ancestor::book  选取当前节点的所有book先辈

XML Message Constructing in B-Puma:

<from uri="direct:default-order-record"/>

<transform>
  <constant>&lt;xml/&gt;</constant>
</transform>
<to uri="xquery:com/barcap/eq/baths/core/puma/templates/DefaultOrderRecord.xml"/>

then Node.setAttribute(String name, String value); 

Unit Testing or Component Testing:

1, To write a test with the JUnit 4.x/TestNG-6-3.1 framework you annotate a method with the @org.junit.Test/@org.testng.annotations.Test

annotation.

2, In TestNG, if you want to run multi-tests as a suite: define XML file with <suite> tag.

<suite><test><packages><package>...</>

Then in the test or base test, use annotation @BeforeSuite and @AfterSuite to initiate/close actors.

Other annotations: @BeforeGroups, @BeforeClass, @BeforeTest, @BeforeMethod.

3, Base class in B project:

extends AbstractTestNGSpringContextTests, part of spring-test-3.1.1, which integrates the Spring TestContext framework with testing support in a TestNG enrironment.

For example, at your base class, @ContextConfiguration(locations = {"/pApp-actors.xml"}), @ActiveProfiles({"SIT2"}).

4, Spring configuration files in test project:

====

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<import resource="spring/puma.xml"/>

<bean id="paul" p:pumaGuiUsername="${puma.user.name}" class="com.barcap.eq.baths.puma.framework.interactor.impl.PumaActorCamel"/>

<beans profile="SIT2">
  <bean p:locations="classpath*:env/US-SIT2-*.properties" class="org.apache.camel.spring.spi.BridgePropertyPlaceholderConfigurer"/>
</beans>

====

Either to use <beans profile> in Spring xml and @ActiveProfiles annotation, to switch among profiles,

Or <profile> in Maven xml and mvn -P Profile1.

5, TestNG also include JUnit's Assert class, which lets you perform assertions on complex objects:

import static org.testng.AssertJUnit.*; assertEquals("Beust", m_lastName);

assertTrue(boolean value), assertFalse(boolean value), assertNull(object),  assertNotNull(object), assertEquals(expected, actual).

6, TestNG DataProvider

A Data Provider is a method on your class that returns an array of array of objects.  This method is annotated with @DataProvider:

@DataProvider(name = "test1")

public Object[][] createData() { return new Object[][] {{"Constance", new Integer(12)}, {"Roxy", new Integer(33)}};}

@Test(dataProvider = "test1")

public void verifyData(String name, Integer age) {System.out.println(name + " " + age);}

7, Mockito testing

The concept behind mock objects is that we want to create an object that will take the place of the real object. This mock object will expect a certain method to be called with certain parameters and when that happens, it will return an expected result.

http://www.codeproject.com/Articles/516360/Mockito-a-great-mock-framework-for-Java-developmen

这里,没有PersonDao的具体implementation,只是为了test PersonService class,所以需要@Mock PersonDao personDao; 然后stub method calls, verify interations.

public class PersonServiceTest
{
@Mock
private PersonDao personDAO;
private PersonService personService;
@Before
public void setUp()
throws Exception
{
MockitoAnnotations.initMocks( this );
personService = new PersonService( personDAO );
}
@Test
public void shouldUpdatePersonName()
{
Person person = new Person( 1, "Phillip" );
when( personDAO.fetchPerson( 1 ) ).thenReturn( person ); //Stub method calls
boolean updated = personService.update( 1, "David" );
assertTrue( updated );
verify( personDAO ).fetchPerson( 1 ); //verify interation
ArgumentCaptor<Person> personCaptor = ArgumentCaptor.forClass( Person.class );
verify( personDAO ).update( personCaptor.capture() );
Person updatedPerson = personCaptor.getValue();
assertEquals( "David", updatedPerson.getPersonName() );
// asserts that during the test, there are no other calls to the mock object.
verifyNoMoreInteractions( personDAO );
}
@Test
public void shouldNotUpdateIfPersonNotFound()
{
when( personDAO.fetchPerson( 1 ) ).thenReturn( null );
boolean updated = personService.update( 1, "David" );
assertFalse( updated );
verify( personDAO ).fetchPerson( 1 );
verifyZeroInteractions( personDAO );
verifyNoMoreInteractions( personDAO );
}
}

8, @Listeners annotation in TestNG

提供了一种改变TestNG behavior的方法,你create的listener class要implement ITestNGListener,比如在你的listener class里:

@Override
public void onConfigurationFailure(final ITestResult testResult) {
  reporter.onConfigurationFailure(testResult);
}

9,JUnit 4里有expected = IllegalArgumentException.class,在testng里是expectedExceptions = {}。

												

[Java Basics3] XML, Unit testing的更多相关文章

  1. Java Unit Testing - JUnit & TestNG

    转自https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaUnitTesting.html yet another insignifican ...

  2. 10 Unit Testing and Automation Tools and Libraries Java Programmers Should Learn

    转自:https://javarevisited.blogspot.com/2018/01/10-unit-testing-and-integration-tools-for-java-program ...

  3. Unit Testing of Classes in Java

    Every class can have a main method. That is a handy trick for unit testing of classes. For example, ...

  4. C/C++ unit testing tools (39 found)---reference

    http://www.opensourcetesting.org/unit_c.php API Sanity AutoTest Description: An automatic generator ...

  5. Unit Testing of Spring MVC Controllers: “Normal” Controllers

    Original link: http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-m ...

  6. Unit Testing of Spring MVC Controllers: Configuration

    Original Link: http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-m ...

  7. Javascript单元测试Unit Testing之QUnit

    body{ font: 16px/1.5em 微软雅黑,arial,verdana,helvetica,sans-serif; }           QUnit是一个基于JQuery的单元测试Uni ...

  8. Unit Testing a zend-mvc application

    Unit Testing a zend-mvc application A solid unit test suite is essential for ongoing development in ...

  9. java对xml节点属性的增删改查

    学习本文之前请先看我的另一篇文章JAVA对XML节点的操作可以对XML操作有更好的了解. package vastsum; import java.io.File; import java.io.Fi ...

随机推荐

  1. 解决 笔记本键盘打字母却跳出数字来,每次都要按一遍Fn+Num LK 的问题

    方法一. 开始-运行,输入“Regedit"命令进入注册表 HKEY_USERS\.DEFAULT\Control Panel\Keyboard 将 InitialKeyboardIndic ...

  2. NXOPEN环境配置

    1.找到NX中的vc文件夹 D:\study software\NX\NX9.0\UGOPEN\vs_files

  3. ORACLE 自定义聚合函数

    用户可以自定义聚合函数  ODCIAggregate,定义了四个聚集函数:初始化.迭代.合并和终止. Initialization is accomplished by the ODCIAggrega ...

  4. gdb注意事项

    假设我当前有文件test.cpp,要gdb调试,先shell上执行:g++ test.cpp -o test -g 1. gdb调试针对的文件是debug模式的可执行文件. 上面-g参数即加上debu ...

  5. java 通过反射获取调用类方法及属性

    首先说下反射是什么?反射是Sun公司推出的一组API,此组API位于Java.lang.reflect中 反射的作用是编写工具(例如eclipse),编写框架,当然对于一般的程序,我们不可能用反射来做 ...

  6. php发送邮件

    <?php header("content-Type: text/html; charset=utf-8"); require("class.phpmailer.p ...

  7. 查询Sqlserver数据库死锁的一个存储过程

    From:http://www.cnblogs.com/mzhanker/archive/2011/06/04/2072739.html 使用sqlserver作为数据库的应用系统,都避免不了有时候会 ...

  8. 遍历所有表,取每个表的MAXID更新到ID控制表

    ) Declare @TID int DECLARE Temp_Cursor1 Cursor--定义游标 FOR SELECT Name FROM Sys_Entity OPEN Temp_Curso ...

  9. Ubuntu Install Java

    http://linuxpilot.com/ubuntu-java class HelloWorld{public static void main(String[]arg){System.out.p ...

  10. 开启GZIP(转)

    因为在做一个项目,项目里面服务器主要提供数据,但是数据多了文件就大了,比较浪费流量和时间,我们便用Gzip来处理.我在本机上是apache,服务器上是IIS6.0,用的是php,那么我就在这里分享一下 ...