development

TDD 대 유닛 테스트

big-blog 2020. 7. 19. 00:07
반응형

TDD 대 유닛 테스트


우리 회사는 코드를 단위 테스트하는 데 익숙하지 않습니다. 나는 한동안 TDD 및 단위 테스트에 대해 읽었으며 그 가치를 확신합니다. TDD가 우리의 프로그래밍 방식에 대한 사고 방식을 배우고 변화시키는 노력을 기울일 가치가 있음을 우리 팀에 확신 시키려고 노력했지만 그것은 어려움입니다. 내 질문에 나옵니다.

TDD 커뮤니티에는 테스트 작성과 코드 작성에 대해 매우 종교적인 사람들이 많이 있지만 TDD로 어려움을 겪고있는 팀에게는 타협이 여전히 추가 혜택을 가져다 줍니까?

코드가 작성되면 (아마도 코드 체크인 요구 사항으로) 팀이 단위 테스트를 작성하도록하는 데 성공할 수 있으며, 단위 테스트를 작성하는 데 여전히 가치가 있다고 가정합니다.

고군분투 팀을 TDD에 참여시키는 가장 좋은 방법은 무엇입니까? 코드를 작성한 후에도 단위 테스트를 작성하는 것이 여전히 가치가 있습니까?

편집하다

내가 여기서 빼낸 것은 코딩 과정 어딘가에서 단위 테스트를 시작하는 것이 중요하다는 것입니다. 개념을 익힌 팀의 사람들은 먼저 TDD 및 테스트를 향해 더 많은 것을 시작하십시오. 모두의 의견을 보내 주셔서 감사합니다.

팔로우

우리는 최근에 새로운 소규모 프로젝트를 시작했으며 팀의 일부는 TDD를 사용했으며 나머지는 코드 후에 단위 테스트를 작성했습니다. 프로젝트의 코딩 부분을 마무리 한 후 코드 작성 후의 테스트 단위 작성은 TDD 코더가 이미 수행되었고 더 견고한 코드를 사용하는 것을보고 놀랐습니다. 회의론자들을이기는 좋은 방법이었습니다. 우리는 여전히 많은 고통을 겪고 있지만 의지의 싸움은 끝났다. 조언을 해주신 모든 분들께 감사드립니다!


팀이 TDD를 구현하는 데 어려움을 겪고 있지만 이전에 단위 테스트를 작성하지 않은 경우 ... 코드 작성 후 단위 테스트를 작성하여 시작하십시오. 코드 후에 작성된 단위 테스트조차 단위 테스트가 전혀없는 것보다 낫습니다!

그들이 단위 테스트 (및 그것과 함께 제공되는 모든 것)에 능숙하면 테스트를 먼저 만들고 코드를 두 번째로 만들 수 있습니다.


코드를 작성한 후에도 단위 테스트를 작성하는 것은 여전히 ​​가치가 있습니다. 코드가 테스트 가능하도록 설계되지 않았기 때문에 때로는 더 어려워지는 경우가 많으며 코드가 너무 복잡 할 수 있습니다.

팀을 TDD에 도입하는 좋은 실용적인 방법은 과도기 또는 장기적으로 "개발 중 테스트 중"의 대체 방법을 제공하는 것입니다. 그들은 자연스럽게 보이는 코드 섹션을 TDD하도록 권장해야합니다. 그러나 테스트 우선 순위에 접근하기 어려운 코드 섹션 또는 민첩하지 않은 A & D 프로세스에 의해 미리 결정된 객체를 사용하는 경우 개발자는 코드의 작은 섹션을 작성한 다음 해당 코드를 다루기 위해 테스트를 작성할 수 있습니다. 코드를 작성하고이 프로세스를 반복합니다. 해당 코드를 작성한 직후 일부 코드에 대한 단위 테스트를 작성하는 것은 단위 테스트를 전혀 작성하지 않는 것보다 낫습니다.


100 % 테스트 범위와 TDD를 사용한 50 % 완료된 라이브러리보다 "코드 우선, 테스트 후"및 100 % 완료된 라이브러리를 사용하여 50 % 테스트 범위를 갖는 것이 더 나쁘지 않다고 생각합니다. 잠시 후, 동료 개발자들은 public그들이 작성 하는 모든 코드에 대한 테스트를 작성하는 것이 즐겁고 교육적인 것을 알게 될 것이므로 TDD는 개발 루틴에 몰두할 것입니다.


나는 이것을 달력에서 읽었습니다. "모든 규칙이 최대한 실행되면 말도 안되거나 위험 해집니다." 그러므로 제 제안은 종교적이지 않아야합니다. 팀의 모든 구성원은 테스트와 관련하여 "정확한"느낌 사이의 균형을 찾아야합니다. 이런 식으로 팀의 모든 구성원이 가장 생산적 일 것입니다 ( "왜이 테스트를 작성해야합니까?"라고 말하는 대신).

따라서 일부 테스트는 없음보다 낫습니다. 코드 후 테스트는 몇 번의 테스트보다 낫습니다. 그러나 각 단계마다 고유 한 장점이 있으므로 작은 단계조차 밟아서는 안됩니다.


TDD는 디자인에 관한 것입니다! 따라서이 코드를 사용하면 테스트 가능한 코드 디자인으로 테스트를보다 쉽게 ​​작성할 수 있습니다. 코드를 작성한 후에 테스트를 작성하면 여전히 가치가 있지만 IMHO는 테스트 가능한 디자인이 없기 때문에 시간을 낭비하게됩니다.

팀이 TDD를 채택하도록 설득하기 위해 제안 할 수있는 한 가지 제안은 Fearless Change : 새로운 아이디어를 도입하기위한 패턴, Mary Lynn Manns 및 Linda Rising에 설명 된 기술 중 일부를 사용하는 것입니다 .


그들이 IMO보다 테스트에 익숙하지 않다면 이미 작성된 테스트 코드를 시작하고 천천히 테스트 작성을 시작하십시오. TDD를 배우고 단위 테스트를 처음 접하는 사람으로서 완전한 180을하고 코드 전에 테스트를 작성하도록 사고 방식을 변경하는 것이 어렵다는 것을 알았습니다. 따라서 내가 취하는 접근법은 일종의 50-50 혼합입니다. ; 코드의 모양을 정확히 알면 코드를 작성한 다음 테스트를 작성하여 코드를 확인합니다. 확실하지 않은 상황에서는 테스트부터 시작하여 거꾸로 진행하겠습니다.

또한 테스트를 만족시키기 위해 코드를 작성하는 대신 코드를 검증하기 위해 테스트를 작성하는 데 아무런 문제가 없음을 기억하십시오. 팀이 TDD 경로를 가고 싶지 않다면 TDD 경로를 강요하지 마십시오.


코드가 작성되면 (아마도 코드 체크인 요구 사항으로) 팀이 단위 테스트를 작성하도록하는 데 성공할 수 있으며, 단위 테스트를 작성하는 데 여전히 가치가 있다고 가정합니다.

단위 테스트 코드에 값이 있다는 사실에 대해서는 의심의 여지가 없으며 (테스트 작성 시점에 상관없이) "정의 정의"에 "코드 단위 테스트"를 포함시킵니다. 사람들은 테스트하는 한 TDD를 사용하거나 사용하지 않을 수 있습니다.

버전 관리 와 관련하여 단위 테스트 정책 과 함께 " 개발 분기 " 를 사용하고 싶습니다 (즉, 코드가 컴파일 및 빌드되면 모든 단위 테스트가 통과 됨). 기능이 완료되면 개발 지점에서 트렁크로 게시됩니다. 다시 말해, 트렁크 분기는 " 완료 분기 "(트렁크에 정크 없음!)이며 배송 정책 (언제든지 릴리스 할 수 있음)이 있으며, 이는 더 엄격하고 "테스트 된 단위"보다 더 많은 것을 포함합니다.


이것은 팀이 그것을 믿기 시작하기 전에 자신의 성공을 거두어야 할 것입니다.

약 5 년 전에 저는 프로젝트를 진행할 때 nUnit을 발견했습니다. 우리는 V1.0을 거의 완성했으며이 새로운 도구를 시험하기 위해 몇 가지 테스트를 만들었습니다. 우리는 새로운 팀, 촉박 한 마감일, 높은 기대치 (친숙한 소리 등)이기 때문에 많은 버그를 가지고있었습니다. 어쨌든 우리는 1.0을 받고 1.1에서 시작했습니다. 우리는 팀을 약간 재구성했고 2 명의 개발자가 나에게 할당되었습니다. 나는 그들을 위해 1 시간의 시연을했고 우리가 쓴 모든 것이 그것과 함께 테스트 케이스를 가져야한다고 말했다. 우리는 더 많은 코드, 단위 테스트를 작성했기 때문에 1.1 개발주기 동안 팀의 나머지 부분을 지속적으로 "뒤에서"실행했습니다. 우리는 더 많은 노력을 기울 였지만 결과는 다음과 같습니다. 마침내 테스트를 시작했을 때 코드에 정확히 0 개의 버그가있었습니다. 우리는 다른 사람들이 버그를 디버깅하고 복구하도록 도와주었습니다. 사후에 버그 카운트가 나타 났을 때

I'm not dumb enough to think you can test your way to success but I am a true believer when it comes to unit tests. The project adopted nUnit and it soon spread to the company for all .Net projects as a result of 1 success. Total time period for our V1.1 release was 9 dev weeks so it was definitely NOT an overnight success. But long term, it proved successful for our project and the company we built solutions for.


There is no doubt that testing (First, While or even After) will save your bacon, and improve your productivity and confidence. I recommend adopting it!

I was in a similar situation, because I was a "noob" developer, I was often frustrated when working on team project by the fact that a contribution had broken the build. I did not know if I was to blame or even in some cases, who to blame. But I was more concerned that I was doing to same thing to my fellow developers. This realisation then motivated to adopt some TDD strategies. Our team started have silly games, and rules, like you cannot go home till all your tests pass, or if you submit something without a test, then you have to buy everyone "beer/lunch/etc" and it made TDD more fun.


One of the most useful aspect of unit testing is ensuring the continuing correctness of already working code. When you can refactor at will, let an IDE remind you of compile time errors, and then click a button to let your tests spot any potential runtime errors--sometimes arriving in previously trivial blocks of code, then I think you will find your team starting to appreciate TDD. So starting with testing existing code is definitely useful.

Also, to be blunt, I have learned more about how to write testable code by trying to test written code than from starting with TDD. It can be too abstract at first if you are trying to think of contracts that will both accomplish the end goal and allow testing. But when you look at code and can say "This singleton here completely spoils dependency injection and makes testing this impossible," you start to develop an appreciation for what patterns make your testing life easier.


Well, if you do not write tests firsts it's not "Test Driven", it's just testing. It has benefits in itself and if you allready have a code base adding tests for it is certainly usefull even if it's not TDD but merely testing.

Writing tests first is about focusing on what the code should do before writing it. Yes you also get a test doing that and it's good, but some may argue it's not even the most important point.

What I would do is train the team on toy projects like these (see Coding Dojo, Katas) using TDD (if you can get experienced TDD programmers to participate in such workshop it would be even better). When they'll see the benefits they will use TDD for the real project. But meanwhile do not force them, it they do not see the benefit they won't do it right.


If you have design sessions before writing code or have to produce a design doc, then you could add Unit Tests as the tangible outcome of a session.

This could then serve as a specification as to how your code should work. Encourage pairing on the design session, to get people talking about how something should work and what it should do in given scenarios. What are the edge cases, with explicit test cases for them so everyone knows what it's going to do if given a null argument for example.

An aside but BDD also may be of interest


You may find some traction by showing an example or two where TDD results in less code being written - because you only write code required to make the test pass, the temptation to gold-plate or engage in YAGNI is easier to resist. Code you don't write doesn't need to be maintained, refactored, etc, so it's a "real savings" that can help sell the concept of TDD.

If you can clearly demonstrate the value in terms of time, cost, code and bugs saved, you may find it's an easier sell.


Starting to build JUnit test classes is the way to start, for existing code it's the only way to start. In my experience it is very usefull to create test classes for existing code. If management thinks this will invest too much time, you can propose to only write test classes when the corresponding class is found to contain a bug, or is in need of cleanup.

For the maintenance process the approach to get the team over the line would be to write JUnit tests to reproduce bugs before you fix them, i.e.

  • bug is reported
  • create JUnit test class if needed
  • add a test that reproduces the bug
  • fix your code
  • run the test to show the current code does not reproduce the bug

You can explain that by "documenting" bugs in this way will prevent those bugs from creeping back in later. That is a benefit the team can experience immediately.


I have done this in many organizations and I have found the single best way to get TDD started and followed is to set up pair programming. If you have someone else you can count on that knows TDD then the two of you can split up and pair with other developers to actually do some paired programming using TDD. If not I would train someone who will help you to do this before presenting it to the rest of the team.

One of the major hurdles with unit testing and especially TDD is that developers don't know how to do it, so they can not see how it can be worth their time. Also when you first start out, it is much slower and doesn't seem to provide benefits. It is only really providing you benefits when you are good at it. By setting up paired programming sessions you can quickly get developers to be able to learn it quickly and get good at it quicker. Additionally they will be able to see immediate benefits from it as you work though it together.

This approach has worked many times for me in the past.


One powerful way to discover the benefits of TDD is to do a significant rewrite of some existing functionality, perhaps for performance reasons. By creating a suite of tests that do a good job covering all the functionality of the existing code, this then gives you the confidence to refactor to your heart's content with full confidence that your changes are safe.

Note that in this case I'm talking about testing the design or contract - unit tests that test implementation details will not be suitable here. But then again, TDD can't test implementation by definition, as they are supposed to be written before the implementation.


TDD is a tool that developers can use to produce better code. I happen to feel that the exercise of writing testable code is as least as valuable as the tests themselves. Isolating the IUT (Implementation Under Test) for testing purposes has the side affect of decoupling your code.

TDD isn't for everyone, and there's no magic that will get a team to choose to do it. The risk is that unit test writers that don't know what's worth testing will write a lot of low value tests, which will be cannon fodder for the TDD skeptics in your organization.

I usually make automated Acceptance Tests non-negotiable, but allow developers to adopt TDD as it suits them. I have my experienced TDDers train/mentor the rest and "prove" the usefulness by example over a period of many months.

This is as much a social/cultural change as it is a technical one.

참고URL : https://stackoverflow.com/questions/1742323/tdd-vs-unit-testing

반응형