1

我有一个方法如下

private void validate(String schemaName){
    ....
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);**strong text**
    Source schemaFile = new SteamSource(getClass().getClassLoader().getResourceAsStream(schemaName));
    Schema schema = factory.newSchema(schemaFile);
    ....
}

这个方法是从我需要测试的另一个方法中调用的(使用easymock和powermock)。我正在努力模拟以下行

Source schemaFile = new SteamSource(getClass().getClassLoader().getResourceAsStream(schemaName));

有人可以给我一个线索吗?

当前状态

以下是模拟语句

expectNew(StreamSource.class, anyObject(InputStream.class)).andReturn(mockedobject); 

Powermock.replay(mockedobject, StreamSrouce.class); 

这会引发以下异常。

org.powermock.reflect.exceptions.TooManyConstructorsFoundException: Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to. 
Matching constructors in class javax.xml.transform.stream.StreamSource were:
4

2 回答 2

2

我认为您可以通过powermock以下方式进行操作(我只是按照这里的教程进行操作):

假设你的班级看起来像这样:

public class MyClass {
   private void validate(String schemaName) {
   ....
   SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);**strong text**
   Source schemaFile = new SteamSource(getClass().getClassLoader().getResourceAsStream(schemaName));
   Schema schema = factory.newSchema(schemaFile);
....
   }
}

您应该像这样创建一个测试类:

@RunWith(PowerMockRunner.class) 
@PrepareForTest(MyClass.class) 
public class MyClassTest {

   private MyClass testedClass = new MyClass();
   private ClassLoader mockedClassLoader = createMock(ClassLoader.class);
   private InputStream mockedInputStream = createMock(InputStream.class);

   @Before
   public void setUp() {
       PowerMock.createPartialMock(MyClass.class, "getClass");
       expect(testedClass.getClass()).andReturn(mockedClassLoader);
       expected(mockedClassLoader.getResourceAsStream(***You string***)).andReturn(mockedInputStream);
       replayAll(); // Not sure if that's the name of the method - you need to call replay on all mocks
   }


   @Test
   public void testValidate() {
       // Run your test logic here
   }
}

easymock如果我使用的某些方法的名称有所不同,请原谅。但这是基本思想。

于 2013-10-14T09:18:45.750 回答
1

I think you need one or a combination of the following. Use Powermock constructor mocking for the new StreamSource as documented here: Powermock MockConstructor. You will probably also need to use a mock for SchemaFactory which mean you will need to mock the static factory method call via Powermock: MockStatic

于 2013-10-14T11:34:37.557 回答