简体   繁体   English

Mocking class 中的一个动态方法

[英]Mocking a method in a class dynamically

I am pretty new to Mockito and Spring. I am trying to mock many methods of many classes.我是 Mockito 和 Spring 的新手。我正在尝试模拟许多类的许多方法。 I want to create a functionality where bean name and method name can given as input as string, and it will throw same exception.我想创建一个功能,其中 bean 名称和方法名称可以作为字符串输入,并且它会抛出相同的异常。

Example I have a class A and Class B例子我有一个 class A 和 Class B

@Named
public Class A {
   public void methodInA() {
   System.out.println("In A"); 
  }
}

@Named
public Class B {
   public void methodInB() {
   System.out.println("In B"); 
  }
}


Below is what I am trying to do in test.以下是我在测试中尝试做的事情。

TestConfig:测试配置:

@SpyBean
A a;

Test::测试::

String className = "A";
String methodName = "methodInA";


Object bean = applicationContext.getBean("a");
Class clazzToSpy = bean.getClass();

Class[] paramTypes = clazzToSpy.getMethod(methodName);

Answer answer = new Answer() {
@Override
public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
   if(invocationOnMock.getMethod().getName().equals(methodName)) {
       throw new UnknownError("Manual Exception Created");
   }
   return invocationOnMock.callRealMethod();

  }
};

//Here I want to use the answer on the mock Something like below.

Method mockedMethod = clazzToSpy.getMethod(methodName, paramTypes);

Mockito.doAnswer(answer).when(mockedMethod)


I understand there is a gap in my understanding.我知道我的理解存在差距。 How do I achieve something like above?我如何实现上述目标?

Has someone tried doing similar thing?有人试过做类似的事情吗?

Related threads which I have tried:我试过的相关主题:

  1. Mocking Reflection based calls Mocking 基于反射的调用

  2. Mocking getClass method with PowerMockito Mocking 使用 PowerMockito 的 getClass 方法

  3. mockito: mock method call with parameters by reflection mockito:通过反射模拟带参数的方法调用

  4. Mockito: is it possible to combine mock with a method name to create a methodCall inside a when() call? Mockito:是否可以将 mock 与方法名称结合起来在 when() 调用中创建 methodCall?

  5. Using Mockito to mock methods by reflection 使用 Mockito 通过反射模拟方法

This seems not going to work since when you:这似乎行不通,因为当你:

@Spy
Method methodSpy;

Mockito throws: Mockito 抛出:

 org.mockito.exceptions.base.MockitoException: Unable to initialize @Spy annotated field 'methodSpy'. Please ensure that the type 'Method' has a no-arg constructor.

and if you:如果你:

@Mock
Method methodMock;

it throws:它抛出:

 org.mockito.exceptions.base.MockitoException: Cannot mock/spy class java.lang.reflect.Method Mockito cannot mock/spy because: - final class

at:在:

MockitoAnnotations.initMocks( this );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM