使用动态参数模拟方法调用

时间:2013-10-14 08:18:11

标签: junit junit4 easymock powermock

我有一个方法如下

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:

2 个答案:

答案 0 :(得分:2)

我认为您可以通过以下方式使用powermock来完成此操作(我只是遵循教程here):

让我们说你上课看起来像这样:

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方法的命名略有不同,请原谅。但这是基本的想法。

答案 1 :(得分:1)

我认为你需要一个或以下的组合。对Powermock new StreamSource使用SchemaFactory构造函数模拟文档here: Powermock MockConstructor。您可能还需要使用模拟{{1}},这意味着您需要通过Powermock: MockStatic模拟静态工厂方法调用