【发布时间】:2018-07-20 06:58:27
【问题描述】:
我正在尝试测试 ActionListener 中的私有方法。如果传递了无效的 url,该方法应该抛出异常: 这是我的测试代码:
@Rule
public ExpectedException expectedException = ExpectedException.none();
Map<JLabel, JTextField> inputs;
ActionListener listener;
AddStationWindow window;
ArrayList<Station> stationsToDelete;
@Before
public void setUp() throws IllegalAccessException, NoSuchFieldException,
InstantiationException, SQLException, ClassNotFoundException {
inputs = new HashMap<JLabel, JTextField>();
window = new AddStationWindow();
stationsToDelete = new ArrayList<>();
InitializeH2Database.initialiteDatabase();
}
@Test
public void saveStation() throws NoSuchFieldException,
IllegalAccessException, MalformedURLException, NoSuchMethodException,
InvocationTargetException {
Field f = window.getClass().getDeclaredField("inputElements");
f.setAccessible(true);
LinkedHashMap<JLabel, JTextField> inputs = (LinkedHashMap<JLabel,
JTextField>) f.get(window);
Field f2 = window.getClass().getDeclaredField("save");
f2.setAccessible(true);
JButton saveButton = (JButton) f2.get(window);
inputs.get(window.getInputLabels().get(0)).setText("Testsender");
inputs.get((window.getInputLabels().get(1))).setText("asdasdsa");
ActionListener listener = saveButton.getActionListeners()[0];
Method m = listener.getClass().getDeclaredMethod("saveStation");
m.setAccessible(true);
m.invoke(listener);
expectedException.expect(MalformedURLException.class);
}
@After
public void tearDown() {
stationsToDelete.forEach(s ->
H2DatabaseConnector.getInstance().deleteStation(s));
}
这是 ActionListener 内部测试的方法:
private boolean saveStation() {
List<JLabel> keys = new ArrayList<>();
for (Map.Entry<JLabel, JTextField> inputElement : inputElements.entrySet()) {
keys.add(inputElement.getKey());
}
String stationName = inputElements.get(keys.get(0)).getText();
String urlString = inputElements.get(keys.get(1)).getText();
URL stationURL = null;
try {
stationURL = new URL(urlString);
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(window, "Invalid URL!", "URL
not valid", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
return false;
}
Station s = new Station(stationName, stationURL);
if (checkStation(s)) {
return WebradioPlayer.addStation(s);
}
return false;
}
如果我运行测试,我可以看到堆栈 tarce 显示格式错误的 url 异常,消息没有协议:'asdasdsa',但测试失败。 有人可以解释一下为什么吗? JUnit 版本为 4。
【问题讨论】: