因此,我一直在对android应用程序进行单元测试,尽管在某些情况下我会测试失败的情况,但我并没有按照此答案所建议的方式对其进行测试(尝试在JUnit测试中捕获).
So I've been unit testing an android application, and while there are cases that I test with fail scenarios, I don't test them quite the way this answer is suggesting (Try catch in a JUnit test).
我以下面的代码显示的方式对其进行了测试.答案是建议您在测试方法签名上具有引发异常",因为如果它实际上引发了您不希望的异常,它将使测试失败.但是,我尝试使用和不使用这段代码,它都以相同的方式失败. 上面提供的答案也使用规则"来进行这种测试,因为我需要的所有东西都将它们放在try catch块中,并且实例化是在@Before方法中完成的,因此我没有使用过.
I test it the way it shows on the code below. The answer is suggesting that you should have on test method signature the "throws Exception", since if it actually throws an exception you don't expect, it will fail the test. However i tried it with and without that piece of code, and it fails the same way. The answer provided above, also approaches this kind of test with the use of "rule", which i haven't used, since everything i need i have them inside my try catch block, and the instantiations are done inside a @Before method.
@Test public void testMethod() { try{ //code that will throw exception fail("Exception was not thrown"); } catch (/* types of exceptions */) { //my asserts } }我追求的是哪种方法被认为是最佳实践"及其背后的原因.
What I'm after is which approach is considered "best practice" and the reason behind it.
推荐答案@Test批注的expected属性用于定义测试用例,以检查是否引发了特定的异常.另外,还有@Rules注释,用于更具体的控制和不建议使用的"try-catch"习惯用法.有关示例,请参见此和 junit Wiki .
There's the expected attribute of the @Test annotation to define test cases that check if specific exceptions get raised. Alternatively there's the @Rules annotation for more specific control and a somewhat deprecated "try-catch" idiom. For samples see this and the junit wiki.
@Test(expected = IllegalArgumentException.class)更多推荐
测试异常时的单元测试最佳实践
发布评论