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

时间:2020-07-29 21:49:38

标签: java junit 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);

1 个答案:

答案 0 :(得分:1)

我认为您可能会写以下内容:

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