当我尝试对 JDialog 对象中的某些方法进行单元测试时,出现 NullPointerException。我必须初始化对话框父级的模拟版本以及将使用的另一个类(除了调用静态方法。代码如下:
@RunWith( PowerMockRunner.class )
@PrepareForTest( ControlFileUtilities.class )
public class StructCompDlgTest
{
@Before
public void setUp() throws Exception
{
controlFrame = org.mockito.Mockito.mock( ControlFrame.class );
structCmpDlg = new StructureCompareDialog( controlFrame );
serverPipeline = org.mockito.Mockito.mock( ServerPipeline.class );
}
...
}
用于构建对话框的代码如下:
StructureCompareDialog( IControlFrame controlFrame )
{
super( (Frame) controlFrame, "title", true );
...
}
当调用 super 构造函数时,我最终会在 java.awt.Window.addOwnerWindow(Window.java:2525) 处得到 NullPointerError"
void addOwnedWindow(WeakReference weakWindow) {
if (weakWindow != null) {
synchronized(ownedWindowList) { ***<<------ offending line***
// this if statement should really be an assert, but we don't
// have asserts...
if (!ownedWindowList.contains(weakWindow)) {
ownedWindowList.addElement(weakWindow);
}
}
}
}
我知道我在一个有毒的漩涡中混合了静力学和摆动 gui,但我别无选择。我被指示将一些单元测试与现有代码放在一起。我不知道出了什么问题。
谢谢
最佳答案
看起来很棘手!本质上,您将必须找到在 controlFrame
上调用的所有方法。作为构造函数的一部分,然后撒一些调用
when(controlFrame.methodCalled()).thenReturn(somethingSensible);
如果这看起来像一件困难的苦差事,那么尝试创建
IControlFrame
的默认实现如何?作为测试 setUp() 的一部分创建并使用模拟的实例。不久前我遇到了类似的问题,我试图对 Spring JMS 监听器进行单元测试。不管是对还是错,我通过创建自己的默认实现
DefaultMessageListenerContainer
得到了一个可行的解决方案。这给了我与您所描述的类似的问题。我的解决方案涉及使用我自己的测试特定版本扩展实际实现,如下所示/**
* Empty mocked class to allow unit testing with spring references to a
* DefaultMessageListenerContainer. The functionality on this class should never be
* called so just override and do nothing.
*/
public class MockDefaultMessageListenerContainer extends DefaultMessageListenerContainer {
public MockDefaultMessageListenerContainer() {
}
public void afterPropertiesSet() {
}
@Override
protected Connection createConnection() throws JMSException {
return null;
}
}
在我的示例中,我能够通过回传一个
null
来运行我的测试。有问题的 createConnection() 方法的值。也许同样的方法可以帮助你。
关于swing - 调用 super() JDialog 时的 Powermock,Mockito nullpointerexception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11233428/