gpt4 book ai didi

java - JUnit 预期异常未按预期工作

转载 作者:行者123 更新时间:2023-11-29 04:17:28 25 4
gpt4 key购买 nike

我正在尝试测试 ActionListener 中的私有(private)方法。如果传递了无效的 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 异常,消息为 no protocol: 'asdasdsa',但测试失败。有人可以向我解释为什么吗? JUnit 版本为 4。

最佳答案

您必须在调用实际抛出异常的代码之前设置预期的异常。

代替

@Test
public void saveStation() throws ... {
// code here
expectedException.expect(MalformedURLException.class);
}

你应该把测试方法写成

@Test
public void saveStation() throws ... {
expectedException.expect(MalformedURLException.class);
// code here
}

此外,如果您真的想抛出异常,则必须更改方法 saveStation 以不抑制异常。有关详细信息,请参阅@Leviand 的回答。

关于java - JUnit 预期异常未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51436783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com