Do you prefer literal values or expressions in your Asserts in your unit tests? This little example demonstrates what I mean - please pay attention to the comments:
[Test]
public function fromXML_works() : void {
var slideshow : Slideshow = SlideshowConverter.fromXML(xmlSample);
// do you prefer literal value "1":
assertEquals(slideshow.id, "1");
// ... or an expression like this:
assertEquals(slideshow.id, xmlSample.#id);
}
private var xmlSample : XML =
<slideshow id="1">
<someOtherTags />
</slideshow>;
The nice thing about the expression is that when the XML sample changes, the unit test will not break. On the other hand, I've basically provided an implementation of one aspect of my SlideshowConverter directly in my unit test which I don't like (the test should test intent, not implementation). I can also imagine that tests using expressions will be more prone to programming errors (I could have, for example, made a mistake in my E4X expression in my test method).
What approach do you prefer? What advantage is usually more important on real world projects?
Particularly since you've tagged this TDD: stick with literals. Writing a test before code exists to pass it, you say to yourself, "Self: if I had this function and gave it those parameters, then this is what I would get back." Where this is a very specific value. Don't hide it away; don't abstract it - just put the value into the test. It enhances the documentation value of the test as well.
Personally, I like to use constants within my tests - it ensures that the test fixtures are simple and straightforward. Plus, as you mention, it avoids programming errors in the test itself, which may hide programming errors in the real code.
Related
I am refactoring some business rule functions to provide a more generic version of the function.
The functions I am refactoring are:
DetermineWindowWidth
DetermineWindowHeight
DetermineWindowPositionX
DetermineWindowPositionY
All of them do string parsing, as it is a string parsing business rules engine.
My question is what would be a good name for the newly refactored function?
Obviously I want to shy away from a function name like:
DetermineWindowWidthHeightPositionXPositionY
I mean that would work, but it seems unnecessarily long when it could be something like:
DetermineWindowMoniker or something to that effect.
Function objective: Parse an input string like 1280x1024 or 200,100 and return either the first or second number. The use case is for data-driving test automation of a web browser window, but this should be irrelevant to the answer.
Question objective: I have the code to do this, so my question is not about code, but just the function name. Any ideas?
There are too little details, you should have specified at least the parameters and returns of the functions.
Have I understood correctly that you use strings of the format NxN for sizes and N,N for positions?
And that this generic function will have to parse both (and nothing else), and will return either the first or second part depending on a parameter of the function?
And that you'll then keep the various DetermineWindow* functions but make them all call this generic function?
If so:
Without knowing what parameters the generic function has it's even harder to help, but it's most likely impossible to give it a simple name.
Not all batches of code can be described by a simple name.
You'll most likely need to use a different construction if you want to have clear names. Here's an idea, in pseudo code:
ParseSize(string, outWidth, outHeight) {
ParsePair(string, "x", outWidht, outHeight)
}
ParsePosition(string, outX, outY) {
ParsePair(string, ",", outX, outY)
}
ParsePair(string, separator, outFirstItem, outSecondItem) {
...
}
And the various DetermineWindow would call ParseSize or ParsePosition.
You could also use just ParsePair, directly, but I thinks it's cleaner to have the two other functions in the middle.
Objects
Note that you'd probably get cleaner code by using objects rather than strings (a Size and a Position one, and probably a Pair one too).
The ParsePair code (adapted appropriately) would be included in a constructor or factory method that gives you a Pair out of a string.
---
Of course you can give other names to the various functions, objects and parameters, here I used the first that came to my mind.
It seems this question-answer provides a good starting point to answer this question:
Appropriate name for container of position, size, angle
A search on www.thesaurus.com for "Property" gives some interesting possible answers that provide enough meaningful context to the usage:
Aspect
Character
Characteristic
Trait
Virtue
Property
Quality
Attribute
Differentia
Frame
Constituent
I think ConstituentProperty is probably the most apt.
I guess "it" is an abbreviation of a phrase. But I don't know what it is. Each time when I see this function I always try to find out its meaning.
Can somebody tell me about this?
it('is really much more simple than you think)
The it() syntax it is used to tell Jasmine what it('should happen in your test')
Jasmine is a testing framework for behavior driven development. And it function's purpose is to test a behavior of your code.
It takes a string that explains expected behavior and a function that tests it.
it("should be 4 when I multiply 2 with 2", function() {
expect(2 * 2).toBe(4);
});
It's not an abbreviation, it's just the word it.
This allows for writing very expressive test cases in jasmine, and if you follow the scheme has very readable output.
Example:
describe("My object", function () {
it("can calculate 3+4", function () {
expect(myObject.add(3, 4)).toBe(7);
}
});
Then, if that test fails, the output will be like
Test failed: My object can calculate 3+4
Message:
Expected 6.99999 to equal 7
As you can see, this imaginary function suffers from some rounding error. But the point is that the resulting output is very readable and expressive, and the code is too.
The basic scheme in the code is: You describe the unit that will be tested, and then test its various functions and states.
Jasmine is a BDD testing framework (Behavior Driven Development) and differently from "stanndard" TDD (Test Driven Development) you are actually testing against behaviors of your application.
So "it" refers to the object/component/class/whatever your are testing rather than a method.
Imagine you are writing a test for a calendar widget in which you want to test that once a user click on the next arrow the widget changes the displayed month, you will write something like:
it('should change displayed month once the button is clicked', function(){
// assertions
});
So, "it" is your calendar widget, you are practically saying "the calendar widget should change displayed month once the button is clicked".
In a TDD it would be instead something like:
testButtonArrowClickChangesDisplayedMonth()
In the end there isn't an actual difference, it's just a matter of style and readability.
Jasmine's tests are defined in a quite verbose manner, so developers can better understand what is the purpose of the test.
From the docs:
The name it is a pronoun for the test target, not an abbreviation of
anything. It makes the spec [abbr. for specification] more readable by connecting the function
name it and the argument description as a complete sentence.
https://jasmine.github.io/api/edge/global.html#it
What is the difference between the following lines of (rspec) code and regardless if they are the same or different, when should you use one instead of the other?
book = double("book")
allow(book).to receive(:title) { "The RSpec Book" }
versus
book = double("book")
book.stub(:title).and_return("The RSpec Book")
There are 2 differences but the result is exactly the same. Both are in regards to the rspec mocks/expectations syntax.
Use of #allow instead of #stub method. First case uses the new rspec syntax introduced this year. This is now the preferred way of using rspec. Altough the old syntax isn't deprecated, it will probably be disabled by default in rspec3. More info on this topic from the maintainer of rspec:
http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
http://myronmars.to/n/dev-blog/2013/07/the-plan-for-rspec-3
Use of block instead of #and_return to define the returning value. This has nothing to do with the mentioned syntax change; both approaches have been available for quite a while (since rspec 1). It is more appropriate to use the #and_return method, since it is (a) the default way, (b) more readable and (c) comes without any runtime overhead. The second approach using block is usually reserved to the corner cases, when you wish to return something of more dynamic nature - not a constant, but some kind of calculation.
The answer to your question would be to use combination of both:
use the #allow instead of #stub
use #and_return instead of block, unless you need to return dynamically calculated value
E.g.:
book = double('book')
allow(book).to receive(:title).and_return('The RSpec Book')
I have a method named RenderContent which returns object[]
In my unit test, I need to assert that this array does not contain any objects of type VerifyRequest
At the moment, I'm using the following Assert statement. Is there anything more concise?
Assert.That(
domain.RenderContent().OfType<VerifyRequest>().Count(),
Is.EqualTo(0)
);
I prefer to use fluent syntax. Note also that RenderContent returns object[], not IQueryable<object>.
If you are using NUnit 2.5, you could use something like:
Assert.That(domain.RenderContent(), Has.None.InstanceOf<VerifyRequest>());
But I'm not sure if other unit test frameworks support this assert-style.
Although I don't know the exact NUnit syntax for IsFalse assertion, the best fit for this kind of test is the Any extension method:
Assert.IsFalse(domain.RenderContent().OfType<VerifyRequest>().Any());
It might be tempting to use the Count method, but Any is more efficient, as it will break on the first occurrence.
The Any extension method, which can be given a lambda expression:
Assert.IsFalse(domain.RenderContent().Any(i => i is VerifyRequest));
You could shorten it a tad by using the Assert.AreEqual method instead:
Assert.AreEqual(domain.RenderContent().OfType<VerifyRequest>().Count(), 0);
I prefer the Assert.AreEqual approach; NUNit uses Assert.That for the internal Assert, STringAssert, etc objects. I like just doing Assert.AreEqual(0, domain.RenderContent().OfType().Count()); to check for the counts.
This way, it checks directly that no objects of a type have any number of records, but to a point the variations you see are preference and they all are equally valid. You have to choose what you like for your style of development.
I am trying to test whether a string can be converted into a number in FreeMarker. For example, "123" and "3.14" can be converted, but "foo" can't. I know that I can test for this by using the number method on the string (e.g. "123"?number) and seeing whether it produces an error, but I am looking for a way to test for this without causing an error.
I tried ?matches("^\d+$"), and it works fine for integers, but I am looking for something that works on all numbers.
I can probably do it using a more sophisticated regex, but I am wondering if there is a simpler way.
The simpler way is to not do it in FreeMarker :-) This sounds like something controller (or method on model) should be doing rather than view template. That said, you have a few options:
Use ?number built-in within <#attempt> / <#recover> block.
Write a method in one of your model objects to check whether your string into a number and invoke it from the template.
Write a custom directive to do this for you.