I have some entity in my application called Offer. It has some fields like price, description and 3-4 more. As I'm learning TDD at the moment I don't want to introduce those fields without tests requiring them. The problem is field like title does not have any business meaning I can require so the test would be:
user creates offer with title "xyz"
assert that offer has title xyz
Is there any other way to introduce this kind of field. Should I even bother writing test for such case?
In TDD you write tests for functionality. In your case the field itself is not important. You want that an instance keeps an specific value. A test for this could be:
sut.setProperty(value)
assertThat(sut.getProperty(), is(value)
But i would not write tests for this since there is no real functionality in it. You should have other tests which uses those properties and cover getter/setter for it. Exception is when getter/setter contains some kind of logic for example that a value has a upper limit.
The core aspect here: good OOP focuses on behavior not, on state. In other words: at least when talking about object oriented languages, you prefer to not expose fields to the outside of your class.
Instead you think in terms of behavior - aka methods. In that sense, the other answer is correct; you would rather create getter/setters and verify those.
One disclaimer here: if possible, avoid setters. Rather make sure that your fields are assigned exactly once (by the constructor). In other words: strive to write immutable classes.
Coming back to my initial point: how a "field" is implemented is an internal implementation detail. That is something that you do not want the outside world to know about - so that you are free to change the implementation if required!
Related
I'm starting to develop website that use the spring framework.I have three controller.There are newCustomerController,editCustomerController and deleteCustomerController.These controllers are mapped with view that use for create update and delete, but I create only customer.
So, I would like to know.Is it appropriate to declare the controllers like this.
Thank
The answer to this question is subjective and maybe more a topic for https://softwareengineering.stackexchange.com/. However, there is something very spring related about it that I would like to comment.
There are a few principles that attempt at guiding developers of how to strike a good balance when thinking about designing the classes. One of those is the Single responsibility principle.
In object-oriented programming, the single responsibility principle
states that every class should have a single responsibility, and that
responsibility should be entirely encapsulated by the class. All its
services should be narrowly aligned with that responsibility
A catchier explanation is
A class or module should have one, and only one, reason to change.
However, its still often hard to reason about it properly.
Nevertheless, Spring gives you means for it (think of this statement as a poetic freedom of interpretation). Embrace constructor based dependency injection. There are quite a few reasons why you should consider constructor based dependency injection, but the part relevent to your question is adressed in the quote from the blog
An often faced argument I get is: “Constructors just get too verbose
if I have 6 or 7 dependencies. With fields only, this is fine”.
Awesome, you’ve effectively worked around a clear indicator that the
code you write is doing way too much. An increase in the number of
dependencies a type has should hurt, as it makes you think about
whether you should split up the component into multiple ones.
In other words, if you stick to constructor based injection, and your constructor turns a bit ugly, the class is most likely doing too much and you should consider redesigning.
The same works the other way around, if your operations are a part of the logical whole (like CRUD operations), and they use the same dependencies (now "measurable" by the count and the type of the injected deps) with no clear ideas of what can cause the operations to evolve independently of each other, than no reason to split to separate classes/components.
It should be better if you define one controller for Customer class and in that class you should have all methods related to customer operations (edit,delete,create and read).
Its (almost) my first time trying to create code by TDD principles. But i'm having troubles how to start.
In example: I want to mutate some information about a person.
To make it easy, a person has only these values:
- FirstName
- LastName
- Email
What i need at the end:
- A person DTO
- A person entity (Nhibernate)
- Functionality to store the dto values in the Database. At the end i need to return a succes or an error (possibly a boolean).
With the given information, how to start at all? It's a global question, but that's because i have no clue how to start. I've red many articles but somehow i get stuck already.
Edit:
- I'm using MVC: MVC will give a DTO (filled from form fields) back.
So the MVC start call could be something like this:
public JsonResult MutatePerson(PersonDto person){
//Call functions by TDD here
return Json(true);
}
You've described the objects involved, but not the operations.
Presumably you need a read() operation, a write() operation. Perhaps a list() operation ?
All of the above should have tests associated with them e.g.
testCanReadViaId();
testCanThrowExceptionOnReadingInvalidId();
testCanWrite();
etc.
For a lot of work you should mock your datasources etc. and position (say) hardcoded data under your persistenc elayer such that you don't rely on a database. However for something like the above I would definitely test the basic database interaction.
As such you may need to (initially) point a test suite against a database with canned data. If you want to be more flexible, then your test setup code could write the entities into the database first, prior to running the tests.
Your tests should test different permutations of data and operations e.g. in the above I've suggested a test to read an object via a valid id (say, 1) and a similar operation against an invalid id (say, -1). You may also want to check different data combinations (e.g. does everything work if the email address isn't populated - this may be valid if the database column is nullable)
Using TDD, you should use interfaces as arguments. Interfaces can be mocked, and with a mock you test the MutatePerson method, and ONLY that. In a unit test, you only want to test how a method reacts to input, not how the object reacts to the method. If you test how the DTO object behaves as well, you are writing an integration test.
So, use the interface of PersonDto (create one if it doesn't exist). And use that as method argument instead of the concrete class.
It might be just me, but I have the feeling that you're starting off with little idea of what your global system should look like in terms of layers, modules and the dependencies and interactions between them.
TDD's emergent design sure works at the level of a small object graph, but you won't get away without doing some amount of overall architectural design first (not big upfront design, but enough to get you started).
With that in mind, I think you'll have a far better idea of what to test.
Once you've figured that out, I think you should :
Learn about object-oriented unit testing techniques, and by unit testing I mean testing things in isolation. Roy Osherove's Art Of Unit Testing is an excellent place to start for a .NET developer.
Learn about architecture-level TDD strategies. With the articles you read you certainly got an idea of how to do TDD in the small, but you need a more global approach : what should you TDD first, in what order, etc. A book like GOOS might help you in that department.
I'm looking at some code I've written and thinking "should I be passing that object into the method or just some of its properties?".
Let me explain:
This object has about 15 properties - user inputs. I then have about 10 methods that use upto 5 of these inputs. Now, the interface looks a lot cleaner, if each method has 1 parameter - the "user inputs object". But each method does not need all of these properties. I could just pass the properties that each method needs.
The fact I'm asking this question indicates I accept I may be doing things wrong.
Discuss......:)
EDIT: To add calrity:
From a web page a user enters details about their house and garden. Number of doors, number of rooms and other properties of this nature (15 in total).
These details are stored on a "HouseDetails" object as simple integer properties.
An instance of "HouseDetails" is passed into "HouseRequirementsCalculator". This class has 10 private methods like "calculate area of carpet", "caclulateExtensionPotential" etc.
For an example of my query, let's use "CalculateAreaOfCarpet" method.
should I pass the "HouseDetails" object
or should I pass "HouseDetails.MainRoomArea, HouseDetails.KitchenArea, HouseDetails.BathroomArea" etc
Based on my answer above and related to your edit:
a) You should pass the "HouseDetails"
object
Other thoughts:
Thinking more about your question and especially the added detail i'm left wondering why you would not just include those calculation methods as part of your HouseDetails object. After all, they are calculations that are specific to that object only. Why create an interface and another class to manage the calculations separately?
Older text:
Each method should and will know what part of the passed-in object it needs to reference to get its job done. You don't/shouldn't need to enforce this knowledge by creating fine-grained overloads in your interface. The passed-in object is your model and your contract.
Also, imagine how much code will be affected if you add and remove a property from this object. Keep it simple.
Passing individual properties - and different in each case - seems pretty messy. I'd rather pass whole objects.
Mind that you gave not enough insight into your situation. Perhaps try to describe the actual usage of this things? What is this object with 15 properties?, are those "10 methods that use upto 5 of these input" on the same object, or some other one?
After the question been edited
I should definitely go with passing the whole object and do the necessary calculations in the Calculator class.
On the other hand you may find Domain Driven Design an attractive alternative (http://en.wikipedia.org/wiki/Domain-driven_design). With regard to that principles you could add methods from calculator to the HouseDetails class. Domain Driven Design is quite nice style of writing apps, just depends how clean this way is for you.
I'm reading through the (still beta) rspec book by the prag progs as I'm interested in behavioral testing on objects. From what I've gleaned so far (caveat: after only reading for 30 min), the basic idea is that I want ensure my object behaves as expected 'externally' i.e. in its output and in relation to other objects.
Is it true then that I should just be black box testing my object to ensure the proper output/interaction with other objects?
This may be completely wrong, but given all of the focus on how my object behaves in the system, it seems this is ideology one would take. If that's so, how do we focus on the implementation of an object? How do I test that my private method is doing what I want it to do for all different types of input?
I suppose this question is maybe valid for all types of testing?? I'm still fairly new to TDD and BDD.
If you want to understand BDD better, try thinking about it without using the word "test".
Instead of writing a test, you're going to write an example of how you can use your class (and you can't use it except through public methods). You're going to show why your class is valuable to other classes. You're defining the scope of your class's responsibilities, while showing (through mocks) what responsibilities are delegated elsewhere.
At the same time, you can question whether the responsibilities are appropriate, and tune the methods on your class to be as intuitively usable as possible. You're looking for code which is easy to understand and use, rather than code which is easy to write.
If you can think in terms of examples and providing value through behaviour, you'll create code that's easy to use, with examples and descriptions that other people can follow. You'll make your code safe and easy to change. If you think about testing, you'll pin it down so that nobody can break it. You'll make it hard to change.
If it's complex enough that there are internal methods you really want to test separately, break them out into another class then show why that class is valuable and what it does for the class that uses it.
Hope this helps!
I think there are two issues here.
One is that from the BDD perspective, you are typically testing at a higher level than from the TDD perspective. So your BDD tests will assert a bigger piece of functionality than your TDD tests and should always be "black box" tests.
The second is that if you feel the need to test private methods, even at the unit test level, that could be a code smell that your code is violating the Single Responsibilty Principle
and should be refactored so that the methods you care about can be tested as public methods of a different class. Michael Feathers gave an interesting talk about this recently called "The Deep Synergy Between Testability and Good Design."
Yes, focus on the exposed functionality of the class. Private methods are just part of a public function you will test. This point is a bit controversial, but in my opinion it should be enough to test the public functionality of a class (everything else also violates the OOP principle).
I have created a factory and a set of specifications to create and validate an aggregate root. Currently I have some tests for the factory that call the specifications on the product of the factory, but I'm wondering if that's enough. It might be better from a design perspective to couple the factory to the specifications of it's product, since they are closely interrelated.
If a specification for an aggregate root product is being used for validation, rather than for creation, does it make sense to call it from inside the factory?
Or is a unit test good enough?
The answer probably depends on how you are using your specifications, and whether the code is breaking a lot during the creation process.
Specifications can be used for almost anything you can think of. At a basic level specifications are merely controllable conditional statements encapsulated into objects. Wherever the code uses conditional logic one could probably refactor that logic into specifications, if the developer felt there was some justification.
There is nothing wrong with using specifications in the actual code, so long as it makes the code more usable, maintainable, or readable. There is also nothing wrong with creating specifications that are only used in tests. Specifications are simple objects, coupling code to specifications in one way or another doesn't seem to have much of a negative impact on maintenance or reusability due to the relative simplicity of most specifications.
If a specification for an aggregate
root product is being used for
validation, rather than for creation,
does it make sense to call it from
inside the factory?
Yes, but probably only if you are having trouble or a lack of confidence in the product of the factory.
Or is a unit test good enough?
Yeah calling a specification from a unit test can be good enough to prove the validity of a factory's product (at least in regard to what the specification covers). I don't often use specifications in my unit tests however, only when I'm having a tough time with something, or it's part of the logic that I'm testing.