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

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

How can I mock the following statement by using PowerMockito?

问题

我有一个类,写成这样:

public class AccountInformationManager {
    private ControlSubAccountInfoDAO contSubAcctDao = (ControlSubAccountInfoDAO) (AppContext.getSpringContext().getBean("controlSubAcctDAO"));

    ......

}

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

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

@RunWith(PowerMockRunner.class)
public class AccountInformationManagerTest {

    @Mock
    ControlSubAccountInfoDAO controlSubAccountInfoDAO;

    @Before
    public void setup() throws Exception {
        PowerMockito.when(AppContext.getSpringContext().getBean(anyString())).thenReturn(controlSubAccountInfoDAO);
        accountInformationManager = new AccountInformationManager();
    }
}

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

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

I have a class written like so:

public class AccountInformationManager {
   	private ControlSubAccountInfoDAO contSubAcctDao = (ControlSubAccountInfoDAO) (AppContext.getSpringContext().getBean("controlSubAcctDAO"));

     .....

}

AppContext.getSprintContext() returns an object of type ApplicationContext

What I've tried so far:

    @RunWith(PowerMockRunner.class)
    public class AccountInformationManagerTest {

      @Mock
      ControlSubAccountInfoDAO controlSubAccountInfoDAO;
    
      @Before
        public void setup() throws Exception {
            PowerMockito.when(AppContext.getSpringContext().getBean(anyString())).thenReturn(controlSubAccountInfoDAO);
            accountInformationManager = new AccountInformationManager();
        }
    
    
    }

But I am gettinga null pointer exception in the line:

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

答案1

得分: 1

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

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

I think you may write something like:

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:

确定