【发布时间】:2016-09-04 21:08:07
【问题描述】:
再生产的步骤,
- 使用受保护的方法创建一个类并在子类中覆盖该方法。
- 为子类创建一个测试并尝试抑制方法调用
throws TooManyMethodsFoundException。
TestInterface.java
package com.test.powermock;
/**
* Created by dineshkumar on 06/05/16.
*/
public interface TestInterface {
public int testMethod() throws Exception;
}
AbstractTest.java
package com.test.powermock;
/**
* Created by dineshkumar on 06/05/16.
*/
public abstract class AbstractTest implements TestInterface {
public int testMethod() throws Exception {
return 0;
}
protected void voidMethodWithParams(String a) throws Exception{
}
}
ImplClassTest.java
package com.test.powermock;
/**
* Created by dineshkumar on 06/05/16.
*/
public class ImplClassTest extends AbstractTest {
@Override
public int testMethod() throws Exception {
voidMethodWithParams("a");
return 2;
}
@Override
protected void voidMethodWithParams(String a) throws Exception{
System.out.println("dd");
}
}
ImplClassTestTest.java
package com.test.powermock;
import org.powermock.api.mockito.PowerMockito;
import static org.powermock.api.support.membermodification.MemberMatcher.method;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;
import static org.testng.Assert.*;
/**
* Created by dineshkumar on 06/05/16.
*/
public class ImplClassTestTest {
@org.testng.annotations.Test
public void testTestMethod() throws Exception {
ImplClassTest implClassTestSpy = PowerMockito.spy(new ImplClassTest());
suppress(method(ImplClassTest.class, "voidMethodWithParams", String.class));
int res = implClassTestSpy.testMethod();
assertEquals(res, 2);
}
}
在谷歌之后,https://groups.google.com/forum/#!topic/powermock/h1U5YyEXqfY
也试过下面的代码,
package com.test.powermock;
import org.powermock.api.mockito.PowerMockito;
import static org.powermock.api.support.membermodification.MemberMatcher.method;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;
import static org.testng.Assert.*;
/**
* Created by dineshkumar on 06/05/16.
*/
public class ImplClassTestTest {
@org.testng.annotations.Test
public void testTestMethod() throws Exception {
ImplClassTest implClassTestSpy = PowerMockito.spy(new ImplClassTest());
suppress(method(AbstractTest.class, "voidMethodWithParams", String.class));
suppress(method(ImplClassTest.class, "voidMethodWithParams", String.class));
int res = implClassTestSpy.testMethod();
assertEquals(res, 2);
}
}
有什么办法可以抑制这些方法吗?
【问题讨论】:
-
implClassTestSpy是一个间谍实例,你不能只做一个doNothing().when(implClassTestSpy, "voidMethodWithParams", anyString())或类似的东西吗?见stackoverflow.com/questions/25020277/… -
是的,我能做到。有什么区别?
标签: java unit-testing mockito powermock powermockito