我正在使用sts,但也在命令行上使用mvn clean install。我创建了这个简单的测试作为一个例子。
import org.junit.Test;
import junit.framework.TestCase;
public class QuickTest extends TestCase {
@Test(expected = Exception.class)
public void test() {
throwsException();
}
private void throwsException() throws Exception {
throw new Exception("Test");
}
}
我的STS(Eclipse)IDE抱怨调用方法testThrowsException();未处理的异常类型Exception。
如果我尝试运行测试,我会得到相同的错误
java.lang.Error: Unresolved compilation problem:
Unhandled exception type Exception
我做错了什么?
答案 0 :(得分:6)
问题是您在注释中按预期声明import UIKit
class SlideTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var dataItems: [String] = ["item1", "item2", "item3", "item4"]
@IBOutlet weak var tabelView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tabelView.delegate = self
tabelView.dataSource = self
}
// MARK: - Table view data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = dataItems[indexPath.row]
return cell
}
}
。这是运行时行为,由JUnit确定。您的代码在编译时仍必须符合所有Java的常规规则。在Java的常规规则下,当方法抛出已检查的异常时,您必须1)将其标记为方法签名中抛出或2)捕获并处理它。你的代码都没有。对于您的测试,您希望执行前者以使JUnit失败:
Exception
或者,您可以在两种情况下将public class QuickTest extends TestCase
{
@Test(expected = Exception.class)
public void test() throws Exception {
throwsException();
}
}
更改为Exception
,以便它是未经检查的例外(即不受相同规则约束)。
答案 1 :(得分:4)
你需要添加throws,因为这是一个经过检查的异常,你希望方法抛出它而不是处理它(用于测试目的)
@Test(expected = Exception.class)
public void test() throws Exception{
throwsException();
}