如何使用PowerMockito模拟以下语句?

huangapple go评论117阅读模式
英文:

How can I mock the following statement by using PowerMockito?

问题

我有一个类,写成这样:

  1. public class AccountInformationManager {
  2. private ControlSubAccountInfoDAO contSubAcctDao = (ControlSubAccountInfoDAO) (AppContext.getSpringContext().getBean("controlSubAcctDAO"));
  3. ......
  4. }

AppContext.getSprintContext() 返回一个类型为 ApplicationContext 的对象。

我迄今为止尝试过的方法:

  1. @RunWith(PowerMockRunner.class)
  2. public class AccountInformationManagerTest {
  3. @Mock
  4. ControlSubAccountInfoDAO controlSubAccountInfoDAO;
  5. @Before
  6. public void setup() throws Exception {
  7. PowerMockito.when(AppContext.getSpringContext().getBean(anyString())).thenReturn(controlSubAccountInfoDAO);
  8. accountInformationManager = new AccountInformationManager();
  9. }
  10. }

但是我在这一行收到了一个空指针异常:

  1. PowerMockito.when(AppContext.getSpringContext().getBean(anyString())).thenReturn(controlSubAccountInfoDAO);
英文:

I have a class written like so:

  1. public class AccountInformationManager {
  2. private ControlSubAccountInfoDAO contSubAcctDao = (ControlSubAccountInfoDAO) (AppContext.getSpringContext().getBean("controlSubAcctDAO"));
  3. .....
  4. }

AppContext.getSprintContext() returns an object of type ApplicationContext

What I've tried so far:

  1. @RunWith(PowerMockRunner.class)
  2. public class AccountInformationManagerTest {
  3. @Mock
  4. ControlSubAccountInfoDAO controlSubAccountInfoDAO;
  5. @Before
  6. public void setup() throws Exception {
  7. PowerMockito.when(AppContext.getSpringContext().getBean(anyString())).thenReturn(controlSubAccountInfoDAO);
  8. accountInformationManager = new AccountInformationManager();
  9. }
  10. }

But I am gettinga null pointer exception in the line:

  1. PowerMockito.when(AppContext.getSpringContext().getBean(anyString())).thenReturn(controlSubAccountInfoDAO);

答案1

得分: 1

我认为你可以写成类似这样的方式:

  1. PowerMockito.when(AppContext.getSpringContext()).thenReturn(aContext/* 一个实现了SpringContext接口的对象,该接口的getBean()方法返回模拟的controlSubAccountInfoDAO */);
英文:

I think you may write something like:

  1. PowerMockito.when(AppContext.getSpringContext()).thenReturn(aContext/* an object implementing SpringContext interface, which method getBean() returns mocked controlSubAccountInfoDAO */);

huangapple
  • 本文由 发表于 2020年7月30日 05:49:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63162956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定