TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Ask HN: How do I start with test driven development?

136 点作者 pravj大约 10 年前
I&#x27;m a student developer, @pravj on GitHub. I try to follow the best possible development practice when I&#x27;m working like documentation, respecting language&#x27;s style guide etc.<p>But one thing I don&#x27;t like with me is that I never write tests.<p>Why I never followed that aspect is because I always felt that the thing that I&#x27;m writing, sounds totally OK.<p>One another negative point is that I don&#x27;t actually get it that How to do&#x2F;start this and what type of tests I should write for any given project. Maybe this is because I have never done this before.<p>For example recently I wrote a identicons library, Penticons[1]. It generates GitHub contribution flavored identicons. You can read the development story here[2].<p>Now, the thing that stopped me from writing tests was, I thought that ultimately it&#x27;s a image generation library, why this thing needs any tests.<p>I don&#x27;t want to lost my 1 point in the Joel score. Whenever I see a <i>build passing</i> label on a GitHub repository, It makes me crazy.<p>I&#x27;m asking here because I just love HN, I know people will suggest some awesome things here.<p>1. https:&#x2F;&#x2F;github.com&#x2F;penticons&#x2F;penticons.go<p>2. http:&#x2F;&#x2F;pravj.github.io&#x2F;blog&#x2F;penticons-the-hash-game&#x2F;

42 条评论

jrochkind1大约 10 年前
As far as writing tests... I&#x27;m sure you are testing your code manually yourself already, right? When you make a change, you do something(s) to make sure your change had the effect you wanted, and your software still worked. You just do it yourself, manually, and do different things every time of course.<p>Take those things, write automated tests to test them. Run the automated tests instead of testing manually, every time you can. Especially when making changes don&#x27;t run the software yourself to see if your changes did what you wanted, write a test to do it and run that. The first time one of your tests catches a bug that you never would have expected, you&#x27;ll be hooked.<p>&quot;Test-Driven Development&quot; actually refers to (almost) always writing the tests _before_ you write the code they test. Not everyone subscribes to this, at least universally. I wouldn&#x27;t worry about that for now, I think if you just start writing automated tests every time you would have been manually testing, you&#x27;ll be on the path and things will fall into place.
评论 #9087385 未加载
评论 #9087392 未加载
ollysb大约 10 年前
I can&#x27;t recommend the discussion between Kent Beck, David Hansson and Martin Fowler enough. They look at how and where it should be used and in particular discuss their approach to mocking which I feel is an often misunderstood tool.<p>Part 1 - <a href="https://www.youtube.com/watch?v=z9quxZsLcfo" rel="nofollow">https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=z9quxZsLcfo</a><p>Part 2 - <a href="https://www.youtube.com/watch?v=JoTB2mcjU7w" rel="nofollow">https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=JoTB2mcjU7w</a><p>Part 3 - <a href="https://www.youtube.com/watch?v=YNw4baDz6WA" rel="nofollow">https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=YNw4baDz6WA</a><p>Part 4&#x2F;5 - <a href="https://www.youtube.com/watch?v=gWD6REVeKW4" rel="nofollow">https:&#x2F;&#x2F;www.youtube.com&#x2F;watch?v=gWD6REVeKW4</a>
评论 #9086383 未加载
评论 #9085963 未加载
defenestration大约 10 年前
I can give you some pointers. 1) A good discussion about Unit Testing on Hacker News. Is most unit testing a waste or not? <a href="https://news.ycombinator.com/item?id=7353767" rel="nofollow">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;item?id=7353767</a><p>2) A story about unit testing at Airbnb: <a href="http://nerds.airbnb.com/testing-at-airbnb/" rel="nofollow">http:&#x2F;&#x2F;nerds.airbnb.com&#x2F;testing-at-airbnb&#x2F;</a><p>3) Practical tips for test driven development: <a href="http://soundsoftware.ac.uk/unit-testing-why-bother/" rel="nofollow">http:&#x2F;&#x2F;soundsoftware.ac.uk&#x2F;unit-testing-why-bother&#x2F;</a>
评论 #9085888 未加载
mkolodny大约 10 年前
My favorite resource for learning how to test your code is <a href="http://getpython3.com/diveintopython3/unit-testing.html" rel="nofollow">http:&#x2F;&#x2F;getpython3.com&#x2F;diveintopython3&#x2F;unit-testing.html</a><p>Once you start testing your code, it&#x27;s addictive. Testing gives you confidence.<p>- By forcing you to detail your requirements, writing tests helps you make sure that you&#x27;re building the right thing.<p>- Testing lets you refactor your code with confidence -- if your old tests still pass after you refactor, your new version works the same way as your old version.<p>- Testing makes your code much (MUCH!) more maintainable. As long as your old tests still pass, you can be confident that the new code you wrote didn&#x27;t break any of your old code.
评论 #9086074 未加载
评论 #9086714 未加载
swanson大约 10 年前
Start watching James Shore&#x27;s &quot;Let&#x27;s Play: TDD&quot; videos [1]. Yes, it is in Java and about making a basic desktop app for finance tracking - but that doesn&#x27;t matter. I&#x27;m cutting out paradox of choice and just telling you to start here :)<p>This is a great introduction to the basics of TDD, is appropriate for beginners, shows trial and error (not edited&#x2F;rehearsed &#x27;final versions&#x27;). It is very digestible (15 min per episode) and free to watch on YouTube. It will seem tedious at times, but just commit to watching the first couple episodes and stick with it.<p>Destroy All Software, &quot;Is TDD Dead&quot; Hangouts, other more specific books, etc are all <i>amazing</i> resources - but they are not a good place for a beginner to start. Once you have a basic understanding and have personally run into some of the tricky situations (mocks&#x2F;stubs, testing at system boundaries, slow test suites, etc) these are invaluable, but until then just file them away to revisit later.<p>[1]: <a href="http://www.jamesshore.com/Blog/Lets-Play/Lets-Play-Test-Driven-Development.html" rel="nofollow">http:&#x2F;&#x2F;www.jamesshore.com&#x2F;Blog&#x2F;Lets-Play&#x2F;Lets-Play-Test-Driv...</a>
评论 #9087502 未加载
nethopp3r大约 10 年前
I&#x27;ve found the Craftsman series by Uncle Bob[1] to be very helpful in showing how to do not only TDD, but also pair programming. Before that I would complete tutorials and exercises, but was never able to effectively use it in actual projects. The Craftsman series shows the steps of using TDD in both easy and tricky situations, such as socket code, and enabled me to become much more comfortable with the process.<p>[1] <a href="http://www.objectmentor.com/resources/publishedArticles.html" rel="nofollow">http:&#x2F;&#x2F;www.objectmentor.com&#x2F;resources&#x2F;publishedArticles.html</a>
评论 #9090615 未加载
michaelmcmillan大约 10 年前
I got into it by watching DAS (destroyallsoftware.com) by Gary Bernhardt (creator of the WAT presentation), it has truly shaped me into a better developer. Not only will you learn how to practice TDD, but so much more: refactoring, unix tools, OO-principles ... I could go on forever, it&#x27;s really a great series.
IlPeach大约 10 年前
Hi, currently writing a book on the subject and I&#x27;m doing a bit of research myself.<p>There are two aspects of testing that you need to discern: the development and the project management point of view. The first regards what and how to test things. This can be achieved by any developer and is moderately easy with the right help and mentoring. The second instead is the most difficult: trying to force tests in a non-test-focused environment, where the business does not understand the meaning and&#x2F;or the value of testing can be poisonous to us and the business itself. In other words there must be an effort in both directions. I can keep talking about these two points, but I&#x27;ll skip them for now unless you&#x27;re interested.<p>Regardless of the current environment you&#x27;re in, and taking for granted that the second part is - if not fully, at least partially satisfied, let&#x27;s have a look at how to start with TDD: the major problem you&#x27;re facing is that TDD does not define &quot;what to test&quot;. That&#x27;s why BDD was introduced, to fill in the gaps that TDD has.<p>Still BDD is somewhat lacking depth and proactive understanding from the project level on how much should be spent on unit tests, how much on functional and acceptance tests. On this note, Google has defined the ACC, which helps you define the testing plan for your application; I think it&#x27;s totally worth from both a developer and business perspective to dig a bit more into that, especially if you want to get into testing properly.<p>If you still fail to see why tests are important, let&#x27;s put it down this way, using James Whittaker&#x27;s words: &quot;although it is true that quality cannot be tested in, it&#x27;s equally evident that without testing is impossible to develop anything of quality&quot;.<p>my 2 cents
评论 #9090141 未加载
logn大约 10 年前
TDD is a subset of automated testing as a whole. You&#x27;ll find proponents of testing who might not actually like TDD. It&#x27;s more of an opinion about the best approach. Anyhow TDD is essentially writing the APIs, interfaces, and function signatures first, then writing tests, then implementing things under the hood, then getting tests to pass.<p>Automated testing (unit or integration tests) is an extension of taking those little one-off things we do during development to make sure things work, and formalizing them to be a permanent part of the code base. Some people go further then and try to add tests for every feature or (gasp) every single line and sub-line of code.<p>It&#x27;s easy to get carried away with testing. And some people have valid arguments against testing. But it&#x27;s nothing too hard or unapproachable. The point really is that everyone does testing already, but not everyone keeps all their tests and makes them nice.
评论 #9086253 未加载
评论 #9087378 未加载
AndrewDucker大约 10 年前
The reason you _need_ tests is so that (a) when you change some code in the future it doesn&#x27;t break any of your functionality without you knowing about it and (b) if someone else changes you code it doesn&#x27;t break any of your functionality without you knowing about it.<p>If you don&#x27;t believe that you need unit tests, you won&#x27;t write them - so step one is persuading yourself that they&#x27;re useful. So try to remember a time when you broke your code in an unexpected way, and then try to work out what kind of unit test would have helped avoid that.
jezclaremurugan大约 10 年前
Well the question looks more like a why instead of a how.. answering the how is simple, if you are starting on a new project (as you seem to be), start with unit tests for all functions, for anything that talks to DBs&#x2F;external APIs use mocks.<p>Answering the why,<p>scenario 0 - it forces you to have functions that do one thing and one thing well. Unit testing mostly helps people keep functions small and focused.<p>scenario 1 - assume you are working on a fun app without tests. Everything is fine and the app works great. After some time you decide to add a new feature X, and you realize you need to modify an existing function to achieve that.. you modify that, and the new feature X works fine, but two days later you will realize that an old feature Y is broken.<p>scenario 2 - scenario 1 but with collaborators instead of yourself revisiting the app.<p>scenario 3 - people use unit tests to understand code - while reading&#x2F;working on other people&#x27;s code. Unit tests also serve as excellent examples on how to call&#x2F;use something, which params to pass etc.<p>There are a lot more reasons esp for large projects, and you never know when a small one off project grows into something big and critical so its recommended to always start with unit tests as adding them later is usually 10x more work as it would require refactoring etc.
jordanpg大约 10 年前
Testing and certainly TDD usually fall by the wayside because it takes too long. At least that is the perception. I see two keys to keep tests lightweight, fast, and desirable.<p>First, you should choose testing and mocking libraries and learn them completely and totally. They are usually not that complicated. Read all the docs and memorize all the neat things they can do. Most libraries have a best practices guide. Read it and follow it. The point of this is to make sure that you can write tests as quickly as you can write trivial if&#x2F;then statements.<p>Second, keep your tests as simple as possible while still testing behavior. Do not verify that every variable is set or if every method is called, or the right thing is passed everywhere. The tests should read like documentation: it should do x, it should do y. If you find the process of writing tests arduous or difficult to maintain, you&#x27;re overcomplicating your tests (and probably your code, too).<p>In a word: lightweight.
hugs大约 10 年前
In general, don&#x27;t worry (too much) about tests in the beginning of a project until it&#x27;s likely you&#x27;ll have more than one user (aka yourself) and&#x2F;or paying customers. If you have neither users nor customers, don&#x27;t feel too guilty about your lack of tests. In many cases, it&#x27;s more important to make something useful enough that makes an investment in more testing later worthwhile. Later, when you <i>do</i> have users and customers, you will want your tests to discover regressions before your users do.<p>However, the longer you wait, the higher the risk that you&#x27;ll discover your code is not easily testable... which will require lots of refactoring to make testable. And that refactoring is made harder by the lack of tests...<p>In the meantime, if you&#x27;re truly stuck, write down a list of how you&#x27;re currently manually testing your code and write down edge and corner cases you&#x27;re worried about.<p>(disclosure: I make testing tools for a living.)
MattyMc大约 10 年前
In August of this year I walked into a job interview for an entry-level&#x27;ish Rails dev position at a start-up. Already having a great job in education, I made clear that I was weak in testing and needed a plan to patch things up. I&#x27;m now very confident with testing using MiniTest. Here&#x27;re my 2 cents:<p>- Build something super easy (&lt;4 hours), using Test-Driven Development. The example I used was a URL shortener.<p>- Rebuild one of your existing apps using Test-Driven Development. If you&#x27;re wondering where to get started, watch videos titled &quot;creating a simple app using ____ and TDD&quot;, or even consider calling the Rails hotline.<p>- Get someone to look at your test code for you. I learned a ton from this, I can&#x27;t even begin.<p>- Use MiniTest. RSpec is amazing, but I found MiniTest to be more transparent as to what was actually happening.<p>- Check out the codeschool and codeacademy tutorials. Very helpful.<p>Best of luck. It&#x27;s a very difficult topic, one that I really struggled with.
kureimoru大约 10 年前
I would like to point out that TDD isn&#x27;t really about tests, it&#x27;s about design of your program. It forces you from the very beginning to deal with really important questions: how do one use a piece of your program? Is it easy, clear and simple? Can it be tested? What do you expect from the program? Is your program or component overcomplicated?<p>Design your programs from top to bottom fleshing out details as you go. Deal with one abstraction at a time. And when you&#x27;re finished you can throw away non-critical tests so that they don&#x27;t outlive their purpose.<p>Do remember that tests are code too and that they have to be maintained and that they can become a part of technical debt. Do not use TDD for prototypes when you really don&#x27;t know how or why implement your program. Create a prototype, explore possibilities, throw the prototype away and write a production version with TDD.
评论 #9090127 未加载
briantopping大约 10 年前
TDD without refactoring is like sex without orgasm. Okay, maybe it&#x27;s not that bad.. ;)<p>Seriously, the most fun I ever had with TDD was when using a language that my IDE had great refactoring tools for. Just write all your code inside a test to start with, don&#x27;t bother with production anything. The test becomes a little like a command line program, launches immediately from the IDE and you can iterate super quickly. Your output is whether the test (with the test data) passes or fails. I&#x27;d pick the test framework by whatever the IDE liked best. Pursue solutions that viscerally satisfy until you know better.<p>Once you have a test working like that, do &quot;Extract Method&quot; followed immediately by &quot;Move Method&quot;. The destination of the move is the production class. With two menu selections, you have a perfectly testable interface, called perfectly by the test. A good extract refactoring always proposes parameters for the method and lets you order and rename them. It will also recognize extractions that can&#x27;t work, like when two results are generated by the selected code. In that case, extract more than one method and move all the methods to the production code.<p>Want to add more code? Do the same thing again and again and again, each time as a new test.<p>When you are done, you&#x27;ll have production classes that are the composite of the extractions and all the tests that once contained inline code (but now contain method calls to the production code).<p>At some point, you will ask &quot;how can I improve my tests?&quot; The answer is easy: Code coverage tools. You should shoot for &gt; 80% of your production code having test coverage. Some say more, few say less. Make some rules for yourself about things you don&#x27;t bother testing, like getters and setters, use the 20% leeway so you aren&#x27;t flogging yourself. Keep having fun, don&#x27;t make a death march out of testing every last line of code.<p>This habit becomes really fun. You&#x27;ll start telling your friends. Nirvana will ensue.
评论 #9088227 未加载
SEJeff大约 10 年前
So TDD is a difficult thing to get into from the beginning. The more experienced you are as a developer the easier it will be to write tests. The thing that is great about TDD is that it forces you to write discrete and modular code as it tends to be easier to test that way.<p>This week, one of my coworkers described being new to TDD like being new to vim. There is a horribly steep learning curve but once you &quot;get it&quot; it becomes second nature. The real win of TDD, especially for open source, is that when the projects start to get bigger and harder to manually test you can merge PRs with a bit more confidence that you&#x27;re not breaking things. I can speak with a bit of experience here as an OSS co-maintainer of two pretty large (&gt;500 unique contributors) projects, graphite, and salt.
jermo大约 10 年前
TDD takes time and is hard to get right at first. I&#x27;m sure you will find the usual tutorials so I would rather recommend this blog post: <a href="https://www.stevefenton.co.uk/Content/Blog/Date/201305/Blog/My-Unit-Testing-Epiphany/" rel="nofollow">https:&#x2F;&#x2F;www.stevefenton.co.uk&#x2F;Content&#x2F;Blog&#x2F;Date&#x2F;201305&#x2F;Blog&#x2F;...</a><p>and Ian Cooper&#x27;s talk &quot;TDD, where did it all go wrong&quot;: <a href="https://vimeo.com/68375232" rel="nofollow">https:&#x2F;&#x2F;vimeo.com&#x2F;68375232</a><p>In a nutshell: test your high level API and not your implementation, minimize your usage of mocking.
junto大约 10 年前
For .Net developers I can recommend the combination of local dev machine continuous testing using NCrunch, manual runs using the unit test runner in Resharper and then the NUnit test runner in TeamCity.<p>TeamCity is a gatekeeper. Builds that fail unit testing don&#x27;t get automatically deployed. Locally NCrunch keeps you updated on what is broken without you having to think about running your tests, since it runs them in the background for you. Resharper unit test runner helps you run and debug specific tests or groups of tests.<p>I work on a large application with many other developers and this flow works well for us.
m52go大约 10 年前
James Shore&#x27;s TDDJS series is supposed to be excellent: <a href="http://www.letscodejavascript.com/" rel="nofollow">http:&#x2F;&#x2F;www.letscodejavascript.com&#x2F;</a>
vpeters25大约 10 年前
I usually start with an &quot;it works&quot; test that calls each method with expected inputs and asserts an expected result. The expected result most of the time is that it didn&#x27;t throw an exception. I found that such tests usually cover most of each method and are pretty effective at detecting regressions.<p>When I&#x27;m fixing a bug, I first create a test that fails when reproducing the conditions that cause it, then I make necessary changes until that test passes.
grandalf大约 10 年前
Thinking about testing can help with good overall design. Consider:<p>- How can I build a small, testable unit that can be combined with other small, testable units?<p>- How can I design a small, testable unit with a stable interface?<p>- How can I test this small testable unit in isolation and in various production&#x2F;deployment scenarios?<p>Choosing the right building blocks to focus on meshes well with testing thinking b&#x2F;c it lends itself to a bottom-up philosophy.
mrbrandonking大约 10 年前
The best introduction to TDD that I&#x27;ve seen is Jon Reid&#x27;s video tutorial here...<p><a href="http://qualitycoding.org/objective-c-tdd/" rel="nofollow">http:&#x2F;&#x2F;qualitycoding.org&#x2F;objective-c-tdd&#x2F;</a><p>Even though he&#x27;s demonstrating TDD with Objective-C, I&#x27;ve recommended this video to .NET developers and they&#x27;ve still had an &quot;Aha!&quot; moment when Jon explains the &quot;TDD Waltz&quot;.
aaronem大约 10 年前
&gt; ultimately it&#x27;s a image generation library, why this thing needs any tests<p>So you can be confident that it generates correct images, even three years from now when you&#x27;ve mostly forgotten about it but you dip back in just to add a quick feature without thinking about it very much -- or, for that matter, when someone submits a pull request, and you want to make sure it doesn&#x27;t break anything.
rmetzler大约 10 年前
One very easy thing to test for is wether your SVG creating code actually returns valid XML&#x2F;SVG or not.<p>Then you might want to make some of these magic values configurable so users can create different sizes or different color schemes and some of them might be dependent. Unfortunately, I doubt that this refactoring is done without mistakes. Maybe you should write some tests before and then refactor.
mattxxx大约 10 年前
TDD in what language? It&#x27;s all about workflow. So if you&#x27;re using java, you should get familiar with mvn and the junit lib. If you&#x27;re using NodeJS, then you need to do something like mocha and grunt.<p>TDD gives you insane test coverage, but your process becomes: 1) Write a failing test 2) Write some code 3) Run test 4) Repeat 2 &amp; 3 until test works, then go back to 1.
veihan大约 10 年前
Long time ago I also didn&#x27;t write tests. Now this software causes me the most problems. For start you shouldn&#x27;t focus on testing with any methodology like TDD, BDD, etc., just ignore it. Better read about Right-BICEP, this going to help you shift way of thinking. Anyway after some hellish struggling you should be able always to think out tests before code.
crdoconnor大约 10 年前
&gt;Now, the thing that stopped me from writing tests was, I thought that ultimately it&#x27;s a image generation library, why this thing needs any tests.<p>I&#x27;m not sure this one does. It&#x27;s a very simple library and there&#x27;s no bugs in the issue tracker.<p>I would write a test for the first bug you encounter, though.<p>Or, if you start writing a more complex method on a new feature, start TDD&#x27;ing that.
ranko大约 10 年前
There were two things that helped me get started: pairing with a more experienced developer who did TDD, and reading Growing Object-Oriented Software, Guided by Tests by Steve Freeman and Nat Pryce. You might not have the luxury of the first, but the second is pretty accessible, even if you don&#x27;t use the particular tools that the authors demonstrate.
hluska大约 10 年前
I thought TDD seemed like a waste until I wanted to really figure out Rails and went through mhartl&#x27;s Rails tutorial. By the end of the book, I realized that TDD had automated all the silly manual tests I did, and actually saved me time. I was kind of shocked, though thats what I get for thinking I actually knew an answer...:)
raverbashing大约 10 年前
Really, you start by starting.<p>First grab a testing framework for your language, if it&#x27;s not built-in. Something that runs the tests in your project once you run a command.<p>Following that, add a test to a function in your project. You can start with an easy one. Try that and see what works, try covering corner cases, etc<p>Then you can go for actual TDD once you write new code.
seanwilson大约 10 年前
Tests for Penticons sounds straightforward to be honest. After saving some example images generated from a set of inputs, write some code that checks those inputs produce those images. Imagemagick has image comparison commands that can help . I did something similar when optimising a gaussian blur filter and found it useful.
vinceguidry大约 10 年前
I personally got started with Gary Bernhardt&#x27;s excellent Destroy All Software screencasts. I started with the third season for his series on untested code, and got the other four soon after.<p><a href="https://www.destroyallsoftware.com" rel="nofollow">https:&#x2F;&#x2F;www.destroyallsoftware.com</a>
laurencei大约 10 年前
Personally I love Uncle Bob&#x27;s videos. He has some great TDD theory and work throughs - it is how I got started: <a href="https://cleancoders.com/" rel="nofollow">https:&#x2F;&#x2F;cleancoders.com&#x2F;</a><p>Specifically episodes 6 and 7. But if you have time - I recommend most of the videos
pypetey大约 10 年前
Writing tests is like writing articles. You just have to start writing and at some point you will get better.<p>Writing tests will change your coding style and way of thinking which is great. You might read some articles about testing for your language of choice.<p>Just start :)
tejohnso大约 10 年前
When you&#x27;re writing your procedures, you have to think about what you want them to do. What small unit of work each procedure should perform. That&#x27;s the best time to write the tests for the procedure, because it will help you to think of edge cases that you might otherwise miss, and it will confirm that the procedure does what you expect before you move onto the next. It&#x27;s also the easiest time to write the test for the procedure, because you haven&#x27;t yet committed to any particular level of complexity or dependency structure. If you write tests first, your code will always be testable. If you attempt to show up the next day and start writing tests, you may find that the person who wrote the code yesterday wrote some pretty untestable code. Another benefit to having the tests is that they will continue to pay off as you modify the code weeks and months later, always confirming that you haven&#x27;t broken anything.<p>Like most other learning endeavours, I found that the best approach was to start small. Try something simple like a fizz-buzz test. You&#x27;ll probably have more trouble setting up and writing the tests than writing the code under test. That&#x27;s okay. Like any other learning process, it takes time to get used to the new language and behaviour that is required to become fluent in writing testable code. Make sure that every time you save your working code, your tests run and you can see the result so that you get immediate feedback. And make sure to always work in as small a unit of work as seems comfortable.<p>Here are some example test function names for fizzbuzz<p>1. itPrintsFizzForMultiplesOfThree() 2. itPrintsBuzzForMultiplesOfFive()<p>These tests might be too broad in scope. Where is it getting the numbers that it&#x27;s checking for multiples? What does &quot;print&quot; mean? How are the tests going to confirm what was printed?<p>1. itReturnsTrueForMultiplesOfThree() 2. itReturnsTrueForMultiplesOfFive() 3. itReturnsEitherFizzOrBuzzOrTheNumber() 4. itSendsTheResultToOutput()<p>These tests are against simpler methods and are easier to write but the tradeoff is that they make the code under test too fine grained at times. Can you have too many tests? I don&#x27;t think that&#x27;s likely in practice, not if they&#x27;re true unit tests and extremely quick to execute. But some would disagree when they see a five method fizzbuzz class rather than a class with one &quot;doTheWholeThing&quot; method. You have to find what works for you. When you return to your code a day or two later, do the tests immediately make sense? If not, they&#x27;re probably too complicated. Start small, get a feel for the shift in mindset, grow from there.
christiangenco大约 10 年前
Here&#x27;s the thing with TDD: until you work on a project that&#x27;s either<p>a) contributed to by a lot of developers that aren&#x27;t familiar with the source code,<p>b) so large that you&#x27;re scared of making any substantial changes because the last time you did that another piece broke and it took forever to figure out it was actually broken and another forever to figure out how to get both pieces working together and in the process you half-broke this other piece and GAH maybe I should just rewrite the entire thing, or:<p>c) mission-critical, where a piece not doing what it&#x27;s supposed to means lost lives or money,<p>then TDD is a net waste of time. Much like learning git, you&#x27;ll be fighting an uphill battle with your mind at every stumbling block (&quot;ugh this is so complicated - why am I learning this again? Doesn&#x27;t putting my source code in Dropbox solve all of these problems already?&quot;) until you have an actual, real, legitimate use for the solution (&quot;oh right, I&#x27;m learning git because using Dropbox to collaborate means &#x27;conflicted copy&#x27; city&quot;).<p>Tests don&#x27;t have to be complicated. They don&#x27;t have to use the next new shiny framework, they don&#x27;t have to have a smart lookup system that auto-runs files that are checked in and sends you an email if you push bad code; tests are just if statements, and they&#x27;re mostly the if statements that <i>you&#x27;re already running through your mind when you program</i>. Here&#x27;s a hopefully not too contrived example:<p>When you wrote commit 4a069[1], how did you know the code you wrote actually <i>did</i> anything? From my quick understanding of reading this over, it looks like you changed `padding` and `size` from constants (5 and 30 respectively) to variables set somewhere else (in `utils.go`). If you made all these changes at once, then re-ran whatever code you use to make a penticon, the expected behavior is that you&#x27;d see the exact same thing as before (test#1).<p>But wait, were you even editing the same file you ran? Let&#x27;s double `Padding` and `Size` in `utils.go` and make sure it changes the image (test#2). Alright cool, it does. But wait, the padding looks way too big - is it twice what it needs to be? Let&#x27;s try `Padding = 1` and `Padding = 0` and make sure that looks how I expect it to (test#3, test#4). Awesome - that&#x27;s perfect.<p>Does the size work too? I wonder if this would break if the `Size=0` (test#5). Oh shoot, what if <i>both</i> the size and padding were 0 (test#6). OH SHOOT WHAT IF THEY WERE NEGATIVE? (test#7).<p>---<p>All of that to illustrate: the difference between what you&#x27;re (probably) doing right now and TDD is that in TDD you write down each test as you&#x27;re testing it. At the end of adding those two variables you&#x27;d have a second file of 7 if statements that make sure that changing the size and padding works like it&#x27;s supposed to.<p>Unfortunately, `penticons.go` is a horrible project to bring TDD into your workflow because 1) it&#x27;s tiny and can probably fit in your head all at once so you&#x27;ll know immediately anyway if something breaks, and 2) testing images is hard. It looks like a lot of your other public projects are equally as TDD-unnecessary.<p>What you <i>could</i> do is generate a bunch of references images (like a 1x1px empty image for when the padding=1 and Size=0), then write a script that runs the code that should generate the same image and make sure they match bit-for-bit. Again, though: until you&#x27;re feeling the pain that having the piece of mind that no other part of your program was just broken by what you did, you don&#x27;t need to add TDD to your workflow.<p>1. <a href="https://github.com/penticons/penticons.go/commit/4a06961954530ece6a8c451feee7b1027a3f5e30" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;penticons&#x2F;penticons.go&#x2F;commit&#x2F;4a069619545...</a>
评论 #9087790 未加载
评论 #9086188 未加载
评论 #9086661 未加载
rvalue大约 10 年前
isnt TDD dead already ?<p>Just write unit and integration tests
评论 #9090427 未加载
buildops大约 10 年前
Have you tried Typemock? It helps you get started with unit testing and offers a free version
jasenmh大约 10 年前
I&#x27;d recommend learning a new language that has a strong TDD community. I started testing and TDD by adding unit tests to an existing C++ project and didn&#x27;t really get the point. I recently picked up Ruby and the course I took taught RSpec alongside Ruby. It made so much more sense. Plus, learn another language.
ninjakeyboard大约 10 年前
You start with a test (that fails).
bbcbasic大约 10 年前
TDD requires you write the test first, then the code later. At an extreme you would write a test for a minimal piece of functionality, then do the minimal amount of coding to get the test to pass and then repeat. I.e. you would write no production code that is not covered by a test.<p>This takes a lot of discipline and I have never done it a t work but it is fun to try at home to see what the extreme case is like. I don&#x27;t do this at work because I have no control over 99.99% of the production code and how loosely coupled it is for testing. (In C#, but in Ruby you can get away with it due to duck typing).<p>TDD forces you to write code that is testable. So you never should end up thinking &#x27;oh shit I need to expose that private member variable to make this class testable&#x27;.<p>Anyway just try it and then as you get stuck read up on how to do TDD. I am always an advocate of try before you learn (makes the learning easier).