我有一个测试类,它有以下代码:
public void getDetails (String message){
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
StringReader strReader = new StringReader(message);
InputSource inputSrc = new InputSource(strReader);
Document doc = docBuilder.parse(inputSrc);
...
}
我想使用Mockito为这段代码编写一个JUnit。 我尝试了各种各样的事情:
DocumentBuilderFactory docBuilderFactoryMock = Mockito.mock(DocumentBuilderFactory.class);
Mockito.when(DocumentBuilderFactory.newInstance()).thenReturn(docBuilderFactoryMock);
但我得到了例外:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
DocumentBuilderFactory$$EnhancerByMockitoWithCGLIB$$23223735 cannot be returned by toString()
toString() should return String
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
如果我执行以下操作:
DocumentBuilderFactory docBuilderFactoryMock = Mockito.spy(DocumentBuilderFactory.newInstance());
DocumentBuilder documentBuilderMock = Mockito.mock(DocumentBuilder.class);
Mockito.when(docBuilderFactory.newDocumentBuilder()).thenReturn(documentBuilderMock);
docBuilderdocBuilderMockito.when(docBuilderFactoryMock.newDocumentBuilder()).thenReturn(docBuilderFactoryMock);
并调试我的代码然后我看到测试中的类不会在任何地方使用我的Mock对象但是会创建自己的对象并在
处抛出SAXParseException Document doc = docBuilder.parse(inputSrc);
答案 0 :(得分:0)
单元测试旨在测试组件/类,而不是使用的库组件/类。 您的类将String解析为xml内容并对其进行测试,您会发现提供一组具有已知输出的xml字符串是测试的最佳方法。 只需将已知的xml String传递给您正在测试的类,并断言所解析的结果模型包含您对该xml内容所期望的数据。 我认为你不需要任何嘲弄。