¿ªÔÆÌåÓý

ctrl + shift + ? for shortcuts
© 2025 Groups.io
Date   
[TDD] Testing a class which utilizes randomness
Hi Nikola, One could: Have a method boolean containsString(aString) and test that. Have a method putIfAbsent(aString) and test that (by putting the same string twice and observing that I still only have one string. Or something approximately like that. I generally try to avoid something like boolean putString(aString) that returns whether it accepted the string or not, because I try to avoid methods that return a value and do something. I might put up with it but probably not. There are more ways ... Ron Jeffries www.XProgramming.com I have two cats, and a big house full of cat stuff. The cats fight and divide up the house, messing up their own lives. Nice work cats. Meow.
Started by Ron Jeffries @
[TDD] Testing a class which utilizes randomness
Nikola, In this case, you have two things happening: random strings, and unique strings. Let¡¯s suppose your unique random string generator is called UniqueStringGenerator. You need to inject the random generator ¨C don¡¯t embed it in the class itself ¨C in this way you can control what is generated when needed (in your test). For example your constructor might say: public UniqueStringGenerator ( IRandomGenerator randomGenerator). Then you need to create the interface IRandomGenerator. There will be a method something like getRandom() or something similar. In your duplicate name test, create a DuplicateTestRandomGenerator object which implements IRandomGenerator. In DuplicateRandomTestGenerator just return the same random string from getRandom(). Inject it into the UniqueStringGenerator. Run your test. Of course, when you want to really use UniqueStringGenerator, you instantiate it with an object which implements IRandomGenerator ¨C but which really generates random strings. The real RandomGenerator gets tested in other tests. So, two principals: - Inject things which you need to control them for testing (random number generators or clocks for example) - Separate responsibilities: the UniqueStringGenerator is only responsible for handing out a unique string (it will check against previously generated strings). The RandomGenerator is only responsible for generating a random string. Hmm! More writing than I expected. I hope it¡¯s clear. John D.
Started by Donaldson, John @
[TDD] Testing a class which utilizes randomness 2
Trying abstracting away the notion of the random string generator, into an interface/parent class just called "string generator". Then make 2 subclasses of that: your existing random string generator, and a "test string generator" that can return a predictable, deterministic sequence of values. For your unit tests, you would pass in an instance of the test string generator, while in the production code you would use the random string generator. Your code would work the same no matter which string generator it gets passed. But by using the test string generator in your unit tests you could control exactly the values being generated, and in that way make sure your program is handling all the edge cases correctly. HTH, DR
Started by David Rosenstrauch @ · Most recent @
Testing a class which utilizes randomness
Hello! I'm new to TDD and this group. For practice, I started a simple project and now I want to create a list of random strings, but such that no two strings are ever the same. In a very unlikely, yet possible case, when two randomly generated strings are the same, the method that does this should discard the duplicate and generate a new string before it returns. What I want to test is exactly this behavior - the code which discards the duplicate and forces the string to be regenerated. To test that, I need to force the random string generator to return a duplicate at least once (but finite number of times). To create the test which would generate strings until there's at least one duplicate is unrealistic, because such a test could take a very long time to complete. How would I write such a test? Kind regards, Nikola
Started by Nikola Novak @
How do I unit test a Dispose method ? 5
The question is a bit .Net specific. Assuming the simple case, where I have a type which wraps a internal IDisposable member. class Connection { private SecureString password; } SecureString is Disposable. That mandates that Connection should have a Dispose method, which should dispose its members. Options: * To know whether the internal member has been disposed, I'd have to expose it (so that the unit test can see it). Doesn't feel right to me. * The other hack would be to promote it from private to internal + use the InternalVisibleTo path to access it. Does anyone have something better ? Gishu
Started by Gishu @ · Most recent @
[TDD] RE: How do I unit test a Dispose method ?
Yes, +1 to that. I¡¯ve been wondering what the business or functional need was that was driving that particular implementation and whether it might have been done differently. And for sure it would work out differently if you used a language that didn¡¯t ¡°dispose¡±. John D.
Started by Donaldson, John @
[TDD] How do I unit test a Dispose method ? 22
A method on Connection: hasPassword? R Ron Jeffrieswww.XProgramming.com You never know what is enough unless you know what is more than enough. -- William Blake
Started by Ron Jeffries @ · Most recent @
Single assert / Single mock rule in practice
Some more links concerning the Command Query separation issue: Sandy Metz had a nice explanation ans slides: http://www.youtube.com/watch?v=qPfQM4w4I04&t=12m54s Similar post by Mark Seemann: http://blog.ploeh.dk/2013/10/23/mocks-for-commands-stubs-for-queries/
Started by robi.yagel @
[TDD] How do I unit test a Dispose method ?
Gishu, Could you inject a mocked SecureString? Then you can check if the SecureString.Dispose is called. Seems like a good place to use a mock as it¡¯s a ¡°tell¡± pattern. John D.
Started by Donaldson, John @
[TDD] How do I unit test a Dispose method ?
How does a connection get its SecureString? Can you inject one for test purposes, saving a reference to it? Charlie
Started by Charlie Poole @
[TDD] Re: Single assert / Single mock rule in practice 13
"I could have replaced self.assertTrue(item_exists) with foo.xdep.get_item.assert_called_once_with(1)" These two things are not equivalent tests. your first assert, is correct and is testing the interface. You expect the item to exist if get_item returns the value of 1. Your second assertion is testing the implementation. What if you later change the get_item function to return an object instead of the item id? Do you really want to re-write this test? brought to you by the letters A, V, and I and the number 47
Started by Avi Kessner @ · Most recent @
[TDD] Single assert / Single mock rule in practice 5
Are you familiar with Command Query Separation (CQS)? I've always found that the most coherent and useful way to explain why you would choose a mock or a stub. The most interesting thing about a method is either what it returns or, in the case where you don't care what it returns, whether it was called with the correct semantics, not both. So, if the SUT cares about the value that a method returns then you stub that method, only. If the SUT doesn't care about the value a method returns then you use a mock and verify the call has the expected semantics, only. Does that help?
Started by Adam Sroka @ · Most recent @
Single assert / Single mock rule in practice
I'm re-reading my own post and realising, aren't 2) and 3) breaking the guideline [1] about writing tests to the interface, not the implementation? I think the original version of test_exists_ExistingItemId_ReturnTrue I've got is written to the interface and mocks only bare minimum of required dependencies. Anyone could help me out to get in order with terminology vs practice vs best practices here? How much unit tests should know about implementation of what is being tested? [1] "Stop Mocking, Start Testing" Augie Fackler and Nathaniel Manista at Google http://youtu.be/Xu5EhKVZdV8?t=18m9s Best regards, -- Mateusz ?oskot, http://mateusz.loskot.net
Started by Mateusz ?oskot @
Single assert / Single mock rule in practice
Hi, I'd like to ask for ideas of best practices in case of developing and testing a wrapper for a Python legacy module. Especially, about applying the single assert / single mock rule which I have been learning about from numerous books/videos/blogs. I have Python xdep module which exposes API in form of bunch of free functions. I'm creating new Python module foo which uses xdep (the idea is to provide simplified, Pythonic interface, but that is not directly relevant to my question here). I'm trying to keep the code as simple & generic as possible, so my question is not about Python but unit testing and mocking. # xdep.py def open(): ... def get_item(item_id): ... def close(): ... # foo.py import xdep def exists(item_id): xdep.open() item = xdep.get_item(item_id) xdep.close() if item: return item.id == item_id else: return false Here is my module to unit test behaviuour of the foo: - I create and plug a stub for the legacy module xdep - I mock functions of xdep # test_foo.py import unittest import unittest.mock as mock class ItemTest(unittest.TestCase): def setUp(self): # create stub for external dependency of foo self.xdep_stub = mock.Mock() patcher = mock.patch.dict('sys.modules', {'xdep': self.xdep_stub}) self.addCleanup(patcher.stop) patcher.start() # import foo does import xdep, as patched above import foo self.foo = foo def test_exists_ExistingItemId_ReturnTrue(self): foo = self.foo # Arrange ### Data item_id = 1 ### Mock foo.xdep.get_item.return_value = 1 # Act item_exists = foo.item.exists(item_id) # Assert self.assertTrue(item_exists) I have a single assertion and I use single mock which mocks xdep.get_item function, so it seems a valid yet clear unit test. Now, having the single assert/single mock rule in mind, I have some questions, about the test_exists_ExistingItemId_ReturnTrue in particular: 1) How asserting on foo.item.exists return value is different from asserting how xdep.get_item mock was called? I could have replaced self.assertTrue(item_exists) with foo.xdep.get_item.assert_called_once_with(1) 2) What about having both assertions, would that break the single assertion rule? self.assertTrue(item_exists) foo.xdep.get_item.assert_called_once_with(1) I'm not concern about breaking the rule as technical convention, but as: am I testing multiple things here? 3) AFAIU, it's natural that unit tests are coupled with implementation of method/behaviour they are testing, foo.exists function in my case. So, given that foo.exists function calls three functions of the legacy xdep module xdep.open xdep.get_item xdep.close should I mock all the three function and verify how they were called? Would that still belong to scope of test_exists_ExistingItemId_ReturnTrue test or I better create a new dedicated test case(s), something like test_exists_IfCalled_xdepOpenCalled test_exists_IfCalled_xdepCloseCalled test_exists_IfCalled_xdepGetItemCalled and do assert_called_once_with() appropriately. Above, I count each mock for each xdep function as a separate mock, so "single mock per test" rule seems to suggests I should verify they are called in separate tests, doesn't it? Also, some of other xdep functions need to be called with multiple parameters, and as setting up and verifying their mocks may be quite elaborate,my gut feeling tells me that single unit test per "legacy API call expectation" as listed above is a good approach for readability and maintainability of tests. Am I right? 4) What other, if any, approach to single assert/single mock rules would you take for testing similar case as above? Best regards, -- Mateusz ?oskot, http://mateusz.loskot.net
Started by Mateusz ?oskot @
[TDD] Re: A worked example of TDD in D, with some personal ruminations on my own style, and notes on the D language..
Wow, I had missed that blog post. Fascinating. Thanks! R Ron Jeffrieswww.XProgramming.comPerfectionism is the voice of the oppressor -- Anne Lamott
Started by Ron Jeffries @
[TDD] Re: A worked example of TDD in D, with some personal ruminations on my own style, and notes on the D language..
Missed the original post ... so many thanks for sharing! Wish this group were more active.
Started by Luther Baker @
A worked example of TDD in D, with some personal ruminations on my own style, and notes on the D language.. 2
So I have being doing TDD for years now. But I started noting I tend not to do it exactly "By The Book". So as an exercise I tried going back to doing it... * Very fine grained steps. * Small change so Test fails - commit. * Small change so Test passes - commit. * Refactor so test passes - Commit. As small as I could. Oh, and just for the fun of it, I'm learning the D language, so I did it in D. So here is the result, complete with a blow-by-blow Mercurial Repository of every step. https://bitbucket.org/JohnCarter/roman/src/47ab019ccdf7a4d5d64c1f10ffc7418e67d6f916/roman.d?at=default Conclusions from the exercise. Very fine grained steps resulted in fewer bugs and fewer backtracks. Very fine grained steps resulted in better factored code. Watching others do the same exercise led me to the attitude "adding more test cases is Bad". (Slower, hard to maintain tests, more lines of code) Very fine grained steps slowed me down compared to my more usual somewhat loose style. Thoughtfully adding Provocative test cases in the order of "What I need to Handle Next" is Very Very Good. Replacing "Fine Grained Steps" with, whenever stuck, pull out a smaller chunk and TDD that first (with Provocative test cases) works Very Very Well. Bottom Line? In future I will be doing... Thoughtfully choosing a minimal number of provocative test cases in the order that challenges a single new behaviour, ie. A test case that requires a single additional behaviour in the code. I will take the largest steps I can where I can go from test fail to test pass in a single change. Whenever I misjudged and take too large a step, I will factor out a smaller function and test and develop that first via the same process. Factoring out works best like this... Revert to last passing state, leaving failing test commented out. Copy pasta the code you wish to factor / enhance into a small function leaving original function untouched. Get tests for new function to pass. Wire new function into parent cleaning out original copy. Get tests to pass. Reenable commented out test... hopefully it passes now. What do I mean by provocative test cases? For example, when converting Roman numerals. "I" is provocative. "II" is provocative. "III" is NOT provocative, it merely is extra Lines of Code (and hence a liability). "IV" is provocative, but a bad choice for next test case as it adds two new behaviours at once. "V" is provocative and adds a single new behaviour. "IV" is now provocative and adds only a single new behaviour. Conclusions about D. I love it. It is C / C++ with the worst stuff removed, and the best stuff stolen from it's competitors. If you are serious about industrial grade, high quality, defect free, efficient programming, you urgently need to be looking at D as your next language. Sigh! Unicode. That's not D's fault. D handles Unicode remarkably smoothly, but ye ancient 7bit ASCII is always going to be faster and conceptually easier than variable length code point UTF8. It took a bit of time and effort to get my head around D's template system (richer, safer, better than C++) It took even more time to get my head around Ranges, (again, richer, more flexible, safer than C++ iterators, more efficient than generators, coroutines or enumerators.) The choices D has made are rich in very powerful, very efficient implications. Possibly the most striking is Compile Time Function Evaluation. If it can be evaluated at compile time.... in D it will be. And that is startling powerful. -- John Carter Phone : (64)(3) 358 6639 Tait Electronics PO Box 1645 Christchurch New Zealand This email, including any attachments, is only for the intended recipient. It is subject to copyright, is confidential and may be the subject of legal or other privilege, none of which is waived or lost by reason of this transmission. If you are not an intended recipient, you may not use, disseminate, distribute or reproduce such email, any attachments, or any part thereof. If you have received a message in error, please notify the sender immediately and erase all copies of the message and any attachme
Started by John Carter @ · Most recent @
[TDD] A worked example of TDD in D, with some personal ruminations on my own style, and notes on the D language..
#likedthispost -- Osias, o Osias
Started by Osias Jota @
I'm looking for a new challenge
Hi All. I hope this isn't spamming the list, but I could not think of a better suited place to post. I'm looking for a job and I would love to hear from you if you live in a place warmer than Norway :) Why and where: http://osherove.com/blog/2013/10/20/looking-for-a-new-adventure-and-challenging-work-in-2014.html My cv is at http://cv.osherove.com -- Thanks, Roy Osherove - @RoyOsherove - Author of "The Art Of Unit Testing"http://ArtOfUnitTesting.com ) - My blog for team leaders: http://5Whys.com - My favorite keyboard shortcuts: http://key.bo - +972-524-655388 (GMT+2)
Started by Roy Osherove @
Agile & Web programming SURVEY 2013
Dear IT manager/project manager/developer, We are two software engineering research groups working on improving methodologies and practices for Web development. We kindly ask you to contribute ten minutes of your time to answer a survey we prepared on the use of Agile and Lean Methodologies, and other practices, in Web development. The survey can be found at this link : http://agilewebsurvey2013.polldaddy.com/s/agilewebsurvey2013 If you choose to provide your email address we shall send you a complimentary report with the results of this survey. We shall use your email address only for this purpose. Thank you in advance for your availability and for your time. AGILAB, DITEN, University of Genoa and AGILE GROUP, DIEE, University of Cagliari, Italy.
Started by Erika C. Daniele G. @
Current Image
Image Name
Sat 8:39am