简体   繁体   English

如何在私有 Java 类的静态方法中模拟局部变量?

[英]How to mock local variable in a static method of a private java class?

I am writing unit test for a static method 'updateStatusOfModel' in class 'Util' whose constructor is private.我正在为类“Util”中的静态方法“updateStatusOfModel”编写单元测试,其构造函数是私有的。

This static method instantiates a local variable dbManager as follows:这个静态方法实例化一个局部变量 dbManager 如下:

ActivationDBManager dbManager = new ActivationDBManager(); ActivationDBManager dbManager = new ActivationDBManager();

This dbManager is used to call its method which I have to mock.这个 dbManager 用于调用我必须模拟的方法。

I have mocked this as follows but somehow, it is not working.我对此进行了如下嘲笑,但不知何故,它不起作用。 Unit test is not picking the mock object for ActivationDBManager.单元测试没有为 ActivationDBManager 选择模拟对象。

Any help is appreciated.任何帮助表示赞赏。

@Test 
@PrepareForTest(Util.class) 
void updateStatusModel() throws Exception {     
ActivationDBManager mockdbManager = Mockito.mock(ActivationDBManager.class); 
   PowerMockito.whenNew(ActivationDBManager.class).withNoArguments().thenReturn(mockdbManager);    

PowerMockito.doNothing().when(mockdbManager).updateDBStatus(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());  

Util.updateStatus("", "", "", "");
}

Util.updateStatus is a static method. Util.updateStatus 是一个静态方法。

您应该将ActivationDBManager添加到@PrepareForTest ,因为您正在操纵其字节码(使用whenNew )。

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

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