sld*_*lin 10 junit swing nullpointerexception mockito powermock
当我尝试对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 );
}
...
}
Run Code Online (Sandbox Code Playgroud)
调用构造对话框的代码如下:
StructureCompareDialog( IControlFrame controlFrame )
{
super( (Frame) controlFrame, "title", true );
...
}
Run Code Online (Sandbox Code Playgroud)
当调用超级构造函数时,我最终会在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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我正在混合静力学和挥动gui的有毒漩涡,但我别无选择.我得到了将现有代码与单元测试结合在一起的指令.我不知道出了什么问题.
谢谢
看起来很棘手!基本上你将不得不找到controlFrame作为构造函数的一部分被调用的所有方法,然后将一些调用
when(controlFrame.methodCalled()).thenReturn(somethingSensible);
Run Code Online (Sandbox Code Playgroud)
如果这看起来像是一件困难的事,那么如何尝试创建一个默认实现IControlFrame,你可以创建它作为测试setUp()的一部分并使用模拟的instea.
前一段时间我有一个类似的问题,我试图对弹簧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;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的示例中,我能够通过传递问题null的createConnection()方法的值来运行我的测试.也许同样的方法可以帮助你.
| 归档时间: |
|
| 查看次数: |
1566 次 |
| 最近记录: |