[英]JUnit testing Try/Catch exception
I can't seem to be able to access the Exception in the method for a JUnit test. 我似乎无法访问JUnit测试方法中的Exception。 Here is the method:
方法如下:
public void doUpdateStocks() {
for (Entry<Integer, IFolioRestricted> e : folioList.entrySet()) {
IFolioRestricted folio = e.getValue();
for(Entry<Integer, IStockRestricted> s : folio.getStockList().entrySet()){
try {
((IStock) (s.getValue())).updatePrice();
} catch (MethodException e1) {
e1.printStackTrace();
}
}
}
And this is how I am testing it: 这就是我测试的方式:
@Test
public void testUpdateStock() {
h.doCreateNewFolio("a");
try {
h.doBuyStock(0, "A", 10);
} catch (IOException | WebsiteDataException | NoSuchTickerException | MethodException e) {
// TODO Auto-generated catch block
}
h.doUpdateStocks();
}
After looking online I have seen (expected = MethodException.class) however it doesn't seem to work. 在网上查看后,我已经看到了(预期= MethodException.class),但是它似乎不起作用。 Anyone any ideas on how to cover the catch (MethodException e1) { e1.printStackTrace();
任何人都有关于如何覆盖陷阱的任何想法(MethodException e1){e1.printStackTrace(); } in a JUnit?
在JUnit中?
First of all, you will need to throw the exception in order to catch it in your JUnit test: 首先,您将需要引发异常以便在JUnit测试中将其捕获:
public void doUpdateStocks() throws MethodException { // throw the exception
for (Entry<Integer, IFolioRestricted> e : folioList.entrySet()) {
IFolioRestricted folio = e.getValue();
for(Entry<Integer, IStockRestricted> s : folio.getStockList().entrySet()){
((IStock) (s.getValue())).updatePrice();
}
}
You code should than work already, but you will have to fail the test, if no exception is thrown: 您的代码应该已经可以工作,但是如果没有引发异常,则必须使测试失败:
try {
h.doBuyStock(0, "A", 10);
// No exception thrown, thats wrong so fail the test
Assert.fail()
} catch (IOException | WebsiteDataException | NoSuchTickerException | MethodException e) {
// This is where you want to end
}
Besides throw the exception (which you definitely have to do), there is a better approach to handle exceptions on unit tests using https://github.com/Codearte/catch-exception 除了抛出异常(您一定要做)之外,还有一种更好的方法可以使用https://github.com/Codearte/catch-exception处理单元测试中的异常
Look at the samples on github. 查看github上的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.