JUnit 대 TestNG
현재 우리는 여전히 JUnit 3을 사용하여 테스트를 실행하고 있습니다. 우리는 새로운 테스트 작성 을 위해 JUnit 4로 전환하는 것을 고려 하고 있지만 지금은 잠시 동안 TestNG를 주시하고 있습니다. JUnit 4 또는 TestNG에 대해 어떤 경험이 있으며, 많은 테스트에서 더 잘 작동하는 것 같습니까? 기능 테스트는 광범위한 측면을 다루고 결과를 얻기 위해 다양한 방법으로 작성되어야하므로 테스트 작성시 유연성을 갖는 것도 중요합니다.
이전 테스트는 제대로 작동하기 때문에 다시 작성되지 않습니다. 새 테스트에서보고 싶은 것은 테스트 작성 방법, 유연성있는 어설 션, 그룹화 및 쉽게 배포되는 테스트 실행의 유연성입니다.
두 가지를 모두 사용했지만 기존 테스트를 새로운 형식으로 다시 작성하는 것을 고려해서는 안된다는 저스틴 표준에 동의해야합니다. 결정에 관계없이 두 가지를 모두 실행하는 것은 쉽지 않습니다. TestNG는 JUnit보다 훨씬 더 구성 가능하도록 노력하고 있지만 결국 모두 똑같이 잘 작동합니다.
TestNG에는 테스트를 특정 그룹으로 표시 한 다음 특정 그룹의 모든 테스트를 쉽게 실행하거나 특정 그룹의 테스트를 제외 할 수있는 깔끔한 기능이 있습니다. 따라서 "느린"그룹 에서처럼 느리게 실행되는 테스트를 표시 한 다음 빠른 결과를 원할 때 무시할 수 있습니다. 문서에서 제안한 내용은 새로운 파일을 체크인 할 때마다 실행해야하는 "체크인"테스트로 일부 하위 세트를 표시하는 것입니다. JUnit에서 이러한 기능을 본 적이 없지만 다시는 그렇지 않은 경우 정말 그리워.
높은 구성에 대한 모든 주장에 대해 몇 주 전에 내가하고 싶은 일을 할 수 없었던 코너 케이스를 만났습니다 ... 나는 그것이 무엇인지 기억할 수 있기를 바랍니다. 완벽하지 않다는 것을 알고 있습니다.
TestNG의 가장 큰 장점은 어쨌든 JUnit이 버전 4에 추가 한 주석입니다.
먼저, 최신 유행에 맞게 모든 테스트를 다시 작성하지 마십시오. Junit3은 완벽하게 작동하며 4에 주석을 도입한다고해서 (내 의견으로는) 많이 구입하지는 않습니다. 여러분이 테스트를 작성 하는 것이 훨씬 더 중요합니다 .
가장 자연스럽게 보이는 것을 사용하고 작업을 완료하는 데 도움이됩니다.
사용하지 않은 TestNG b / c에 대해서는 언급 할 수 없습니다. 그러나 어떤 경로를 사용하든 관계없이 JUnit / TestNG / DBUnit / EasyMock을위한 훌륭한 래퍼 인 unitils를 추천 합니다. (위에 언급 된 모든 맛을 지원합니다)
약 1 년 전에도 같은 문제가있었습니다. 어느 쪽이 더 나은지 고려하면서 언젠가 보냈고 결국 TestNG에는 '킬러 기능'이 없다는 것을 깨달았습니다. 훌륭하고 JUnit 4에는없는 기능이 있지만 필요하지는 않습니다.
우리는 사람들이 많은 테스트를 계속 작성하기를 원했기 때문에 TestNG를 알면서 불편한 쓰기 테스트를 느끼기를 원하지 않았습니다.
또한 JUnit은 Java 세계에서 사실상의 표준입니다. 상자에서 지원하지 않는 훌륭한 도구는 없으며 웹에서 많은 도움을 얻을 수 있으며 작년에 많은 새로운 기능을 추가하여 살아 있음을 보여줍니다.
우리는 JUnit을 고수하기로 결정했으며 결코 뒤돌아 보지 않았습니다.
나를 위해 TestNG의 가장 큰 카드는 지원 테스트 그룹과 더 중요한-테스트 그룹 종속성을 포함합니다 (그룹에 의존하는 것으로 테스트를 표시하면 종속 그룹이 실패하면 테스트가 실행을 건너 뜁니다).
TestNG의 다른 대형 카드에는 테스트 매개 변수, 데이터 공급자, 주석 변환기 및 생동감 있고 반응이 빠른 사용자 커뮤니티가 포함됩니다.
표면적으로는 위의 모든 TestNG 기능이 필요하지 않다고 생각할 수도 있지만 테스트에 대한 유연성을 이해하기 시작하면 JUnit에 어떻게 대처했는지 궁금 할 것입니다.
(면책 조항-JUnit 4.x를 전혀 사용하지 않았으므로 고급 기능이나 새로운 기능에 대해서는 실제로 언급 할 수 없습니다).
위의 모든 것을 건배합니다. 내가 개인적으로 TestNG에서 더 좋아하는 것을 발견 한 다른 것들은 다음과 같습니다.
@BeforeClass
당신 만이 당신의 클래스의 정적 메서드를 호출 할 수있는 제약되지 않도록 TestNG를위한, 클래스 생성 한 후 발생합니다.병렬 및 매개 변수화 된 테스트, 아마도 인생이 충분하지 않을 수도 있지만 ... 드라이버 이름을 매개 변수로 사용하여 셀레늄 테스트 한 세트를 작성하는 킥을 얻습니다. 그런 다음 3 개의 병렬 테스트 그룹 (IE, FF 및 Chrome 드라이버마다 하나씩)을 정의하고 경쟁을 지켜보십시오! 나는 원래 4를했지만, 내가 일한 너무 많은 페이지가
HtmlUnit
어떤 이유로 드라이버를 중단합니다 .
그래, 아마 그 삶을 찾아야 할 것입니다 ;)
I wanted to share the one I encountered today. I found built-in Parameterized runner is quite crude in Junit4 as compare to TestNG (I know each framework has its strengths but still). The Junit4 annotation @parameters is restricted to one set of parameters. I encountered this problem while testing the valid and invalid behavior for functionality in same test class. So the first public, static annotated method that it finds will be used, but it may find them in any order. This causes us to write different classes unnecessarily. However TestNG provides clean way to provide different kind of data providers for each and every method. So we can test the same unit of code with valid and invalid way in same test class putting the valid/invalid data separately. I will go with TestNG.
Also one more advantage of TestNG is supporting of parallel testing. In our era of multicores it's important, i think.
I also used both frameworks. But i using hamcrest for assertations. Hamcrest allows you easily write your own assert method. So instead of
assertEquals(operation.getStatus(), Operation.Status.Active);
You can write
assertThat(operation, isActive());
That gives you opportunity to use higher level of abstraction in your tests. And this makes your tests more robust.
JUnit 4 Vs TestNG – Comparison by mkyong.com ( updated on 2013).
Conclusion: I suggest to use TestNG as core unit test framework for Java project, because TestNG is more advance in parameterize testing, dependency testing and suite testing (Grouping concept).
TestNG is meant for functional, high-level testing and complex integration test. Its flexibility is especially useful with large test suites.
In addition, TestNG also cover the entire core JUnit4 functionality. It’s just no reason for me to use JUnit anymore.
In simple terms, TestNG = JUnit + lot more. So, Why debate ? go and grab TestNG :-)
You can find more detailed comparison here.
A couple of additions to Mike Stone's reply:
1) The most frequent thing I use TestNG's groups for is when I want to run a single test method in a test suite. I simply add this test to the group "phil" and then run this group. When I was using JUnit 3, I would comment out the entries for all methods but the one I wanted to run in the "suite" method, but then would commonly forget to uncomment them before checkin. With the groups, I no longer have this problem.
2) Depending on the complexity of the tests, migrating tests from JUnit3 to TestNG can be done somewhat automatically with sed and creating a base class to replace TestCase that static imports all of the TestNG assert methods.
I have info on my migration from JUnit to TestNG here and here.
Why we use TestNG instead of JUnit?
The declaration of
@BeforeClass
and@AfterClass
method has to be static in JUnit whereas, there is more flexibility in TestNG in the method declaration, it does not have these constraints.In TestNG, we can parametrize tests using 2 ways. @Parameter or @DataProvider annotation.
i) @Parameter for simple cases, where key value mapping is required.(data is provided through xml file)
ii) @DataProvider for complex cases. Using 2 dimensional array, It can provide data.
In TestNG, since @DataProvider method need not be static, we can use multiple data provider methods in the same test class.
Dependency Testing: In TestNG, if the initial test fails, then all subsequent dependent tests will be skipped, not marked as failed. But JUnit marked it failed.
Grouping: Single tests can belong to multiple groups and then run in different contexts (like slow or fast tests). A similar feature exists in JUnit Categories but lacks the @BeforeGroups / @AfterGroups TestNG annotations that allow initializing the test / tearing it down.
Parallelism: If you’d like to run the same test in parallel on multiple threads, TestNG has you covered with a simple to use annotation while JUnit doesn’t offer a simple way to do so out of the box.
TestNG @DataProvider can also support XML for feeding in data, CSVs, or even plain text files.
TestNG allows you to declare dependencies between tests, and skip them if the dependency test didn’t pass.
@Test(dependsOnMethods = { "dependOnSomething" })
This functionality doesn’t exist in JUnit
- Reporting:
TestNG reports are generated by default to a test-output folder that includes HTML reports with all of the test data, passed/failed/skipped, how long did they run, which input was used and the complete test logs. In addition, it also exports everything to an XML file which can be used to construct your own report template.
On the JUnit front, all of this data is also available via XML, but there’s no out of the box report and you need to rely on plugins.
Resource Link:
A good difference is given in this tutorial side by side: TestNG Vs JUnit: What's the Difference?
I like the neat and easy integration of TestNG with Guice.
Your question seems two folded to me. On one had you would like to compare two test frameworks, on the other hand you would like to implement tests easily, have natural assertions, etc...
Ok, firstly JUnit has been playing catchup with TestNG in terms of functionality, they have bridged the gap some what with v4, but not well enough in my opinion. Things like annotations and dataproviders are still much better in TestNG. Also they are more flexible in terms of test execution, since TestNG has test dependency, grouping and ordering.
JUnit still requires certain before/after methods to be static, which limits what you can do prior to the running of tests, TestNG never has this issue.
TBH, mostly the differences between the two frameworks don't mean much, unless your focusing on integration/automation testing. JUnit from my experience is built from the ground up for unit testing and is now being pushed towards higher levels of testing, which IMO makes it the wrong tool for the job. TestNG does well at unit testing and due to its robust dataproviding and great test execution abilities, works even better at integration/automation test level.
Now for what I believe is a separate issue, how to write well structured, readable and maintainable tests. Most of this I am sure you know, but things like Factory Pattern, Command Pattern and PageObjects (if your testing websites) are vital, it is very important to have a layer of abstraction between what your testing (SUT) and what the actual test is (assertions of business logic). In order to have much nicer assertions, you can use Hamcrest. Make use of javas inheritance/interfaces to reduce repetition and enforce commonality.
Almost forgot, also use the Test Data Builder Pattern, this coupled with TestNG's dataprovider annotation is very useful.
My opinion about what makes TestNG truly far more powerful:
1. JUnit still requires the before/after class methods to be static, which limits
what you can do prior to the running of tests, TestNG never has this issue.
2. TestNG @Configuration methods can all take an optional argument to their
annotated methods in the form of a ITestResult, XmlTest, Method, or
ITestContext. This allows you to pass things around that JUnit wouldn't
provide you. JUnit only does this in listeners and it is limited in use.
3. TestNG comes with some pre-made report generation classes that you can copy
and edit and make into your own beautiful test output with very little
effort. Just copy the report class into your project and add a listener
to run it. Also, ReportNG is available.
4. TestNG has a handful of nice listeners that you can hook onto so you can do
additional AOP style magic at certain phases during testing.
both are almost same. TestNG has some extra featurs like testsuits and dependecy. please find the attached screeshot to get the full comparison. full Juni5 vs TestNG Comparison
참고URL : https://stackoverflow.com/questions/6658/junit-vs-testng
'programing tip' 카테고리의 다른 글
Java 용 BDD 프레임 워크의 차이점은 무엇입니까? (0) | 2020.07.14 |
---|---|
Express에서 HTML을 뷰 엔진으로 사용하려면 어떻게합니까? (0) | 2020.07.14 |
Mockito와 JMockit의 비교-Mockito가 JMockit보다 더 나은 투표를하는 이유는 무엇입니까? (0) | 2020.07.14 |
유성 테스트 주도 개발 (0) | 2020.07.14 |
복합 인덱스는 언제 사용해야합니까? (0) | 2020.07.14 |