Are there any disadvantages in using a private accessor to test a piece of code?
I'm weighing the option of using a private accessor only to test my GUI, as opposed the the methods/properties that are publically exposed.
This will allow some GUI testing i need, i just wanted to make sure their were not any hidden "pitfalls" in using a private accessor in how it behaves.
So to recap, your stated goal is:
I'm weighing the option of using a private accessor only to test my GUI... This will allow some GUI testing i need...
In short, yes there are pitfalls. The code you are testing is still tightly coupled to the user interface.
In the comments you clarify your goal/problem as:
What about in the case if i want to test, Drag/drop. Custom Controls, Overriden events?
All I can say is welcome aboard. The software industry has struggled with this for nearly half a century. The fact remains that testing UI is hard, Really HARD. Yes you can take a piece of code that is tightly coupled with a UI element and try and automate it; however, your going to be fighting tooth-and-nail to make headway against poor assumptions.
The 'trick' to testable UI is not to make your UI testable, but to remove the code you want to test from the UI. Thus the wide acceptance of N-Tier application development and presentation design patterns like MVC, MVVM, etc.
see the following:
Model View Controller
Model View ViewModel
Model–view–adapter
Model–view–presenter
The primary goal or driving force behind many of these design patterns is to remove the tight coupling between behavior and presentation. This enables you to then test a behavior like drag-n-drop without a user interface. My recommendation is review the patterns, choose one you like, and then start refactoring the code as you write your unit tests.
Another way to think of writing UI for testing is to remove every if, else, for, while, switch, or other control statement from your user interface code. The resulting 'shell' of a UI should be very resilient to change. Just be careful when using things like data binding that rely on reflection (which is generally an acceptable practice). The primary downside to this is that the compiler can not tell you that a member no longer exists.
Updated
#timmy you wrote:
... for example if i want to test mouse click behavior...
So what about the mouse click behavior cannot be moved to a controller rather than being embedded into the form? I guess the "Close" button might have a problem, but beyond that why not move the logic to another class that can then be tested?
BTW, You don't have to pick just one pattern MVC, MVVM, etc, they are 'guidelines' or 'suggestions' not hard rules so don't get ridiculous with it. Just try and make the logic separate from the UI and independently testable. As an example, perhaps your "Click" event fits better with a simple command class? Using a command pattern is easy, new up an object and execute it. Consider this example code for a folder copy form:
private void OnCopyClick(object sender, EventArgs args)
{
var cmd = new MyCopyCommand(this.FolderPath, this.txtTargetFolderPath.Text);
new ErrorHandler(this).Perform(cmd);
}
This works well, it has no 'real' logic other than what to provide the command and has no conditional code paths. Notice we don't even directly invoke the command but rather defer that to someone who can handle an error appropriately. Usually this 'ErrorHandler' would be provided to the Form rather than constructed directly, but you get the idea.
From this we should be easily able to verify the correct behavior of the MyCopyCommand. In the end you should wind up with a bunch of "flat functions" in the UI, ie. functions that have no nesting or curly braces. Of course this is a rule of thumb, not to be taken to such an extreme as to prevent you from being productive.
I know this may seem like a lot of work, but truthfully it is not when you are already working to write a set of tests. You can be productive AND write solid code. You just need to know when to cheat, and when not to. That comes with experience and after 20 years, 10 of those writing NUnits, I still fail once in a while. When something breaks because you didn't do this, first extract the logic from the UI, then write a unit test to prove it's broken, then fix it.
It's better not to use them, instead try to find out if you can inject any dependency. Unless you're working on a legacy code where you want to create some unit tests using private accessors, I'd suggest not to use them and even in this case, I'd recommend you do that temporarily until you refactor legacy code.
In addition to what AD.NET said.
I could use those private properties in tests only until I finish my refactoring (to Model View Controller, Model View Presenter, Model View ViewModel) so that I don't have to test GUI at all!
Related
Lately I've been trying to follow the TDD methodology, and this results in lot of subclasses so that one can easily mock dependencies, etc.
For example, I could have say a RecurringProfile which in turn has methods / operations which can be applied to it like MarkAsCancel, RenewProfile, MarkAsExpired, etc.. Due to TDD, these are implemented as 'small' classes, like MarkAsCancelService, etc.
Does it make sense to create a 'facade' (singleton) for the various methods/operations which can be performed on say a RecurringProfile, for example having a class RecurringProfileFacade. This would then contain methods, which delegate code to the actual sub-classes, eg.:
public class RecurringProfileFacade
{
public void MarkAsCancelled(IRecurringProfile profile)
{
MarkAsCancelledService service = new MarkAsCancelledService();
service.MarkAsCancelled(profile);
}
public void RenewProfile(IRecurringProfile profile)
{
RenewProfileService service = new RenewProfileService();
service.Renew(profile);
}
...
}
Note that the above code is not actual code, and the actual code would use constructor-injected dependencies. The idea behind this is that the consumer of such code would not need to know the inner details about which classes/sub-classes they need to call, but just access the respective 'Facade'.
First of all, is this the 'Facade' pattern, or is it some other form of design pattern?
The other question which would follow if the above makes sense is - would you do unit-tests on such methods, considering that they do not have any particular business logic function?
I would only create a facade like this if you intend to expose your code to others as a library. You can create a facade which is the interface everyone else uses.
This will give you some capability later to change the implementation.
If this is not the case, then what purpose does this facade provide? If a piece of code wants to call one method on the facade, it will have a dependency on the entire facade. Best to keep dependencies small, and so calling code would be better with a dependency on MarkAsCancelledService tha one on RecurringProfileFacade.
In my opinion, this is kind of the facade pattern since you are abstracting your services behind simple methods, though a facade pattern usually has more logic I think behind their methods. The reason is because the purpose of a facade pattern is to offer a simplified interface on a larger body of code.
As for your second question, I always unit test everything. Though, in your case, it depends, does it change the state of your project when you cancel or renew a profile ? Because you could assert that the state did change as you expected.
If your design "tells" you that you could use a Singleton to do some work for you, then it's probably bad design. TDD should lead you far away from thinking about using singletons.
Reasons on why it's a bad idea (or can be an ok one) can be found on wikipedia
My answer to your questions is: Look at other patterns! For example UnitOfWork and Strategy, Mediator and try to acheive the same functionality with these patterns and you'll be able to compare the benefits from each one. You'll probably end up with a UnitOfStrategicMediationFacade or something ;-)
Consider posting this questions over at Code Review for more in depth analysis.
When facing that kind of issue, I usually try to reason from a YAGNI/KISS perspective :
Do you need MarkAsCancelService, MarkAsExpiredService and the like in the first place ? Wouldn't these operations have a better home in RecurringProfile itself ?
You say these services are byproducts of your TDD process but TDD 1. doesn't mean stripping business entities of all logic and 2. if you do externalize some logic, it doesn't have to go into a Service. If you can't come up with a better name than [BehaviorName]Service for your extracted class, it's often a sign that you should stop and reconsider whether the behavior should really be extracted.
In short, your objects should remain cohesive, which means they shouldn't encapsulate too many responsibilities, but not become anemic either.
Assuming these services are justified, do you really need a Facade for them ? If it's only a convenient shortcut for developers, is it worth the additional maintenance (a change in one of the services will generate a change in the facade) ? Wouldn't it be simpler if each consumer of one of the services knows how to leverage that service directly ?
The other question which would follow if the above makes sense is -
would you do unit-tests on such methods, considering that they do not
have any particular business logic function?
Unit testing boilerplate code can be a real pain indeed. Some will take that pain, others consider it not worthy. Due to the repetitive and predictable nature of such code, one good compromise is to generate your tests automatically, or even better, all your boilerplate code automatically.
I have a class that can be called either from a GUI or form a Non-Graphical Environment (Batch mode)
What is the most convenient an best practice way to "tell" the GUI-related parts of the code NOT to execute when executed in batch mode.
I think of something like
public MyMethod()
{
[#TAG: DOTHIS_ONLY_IF_GUIMODE]
ShowPanels();
....
}
And the GUI_MODE_ACTIVATED would be set to true or false on runtime somewhere, depending on where the program is called from
I want to avoid the ugly tracing if/else stuff scattered all over my code.
My little thumb tells me AOP is the way to go (but if I manage to find a simpler alternative I'll go for it)So, what is the SIMPLEST and most straightforward way to do this ?
Update:
As most contributors pointed out, separating GUI Code from Business code is a rule of thumb, But I am still interested in knowing ways to do this even if NO GUI is involved (ie, two different BATCH modes for two different environments, for example)
I think your best bet is to take the GUI-specific code out of the class and implement events triggered at key times in the class's processing. When called by the GUI, the GUI code subscribes to those events and 'does the right thing.' The batch-code ignores the events and all is well.
What is the most convenient an best practice way to "tell" the GUI-related parts of the code NOT to execute when executed in batch mode.
This is why you separate business logic concerns from UI concerns.
So, what is the SIMPLEST and most straightforward way to do this ?
Separate business logic concerns from UI concerns.
The simplest and most straightforward way is to use an if statement.
A less straightforward, but more structured, way would be to make the ShowPanels method abstract, then derive two classes: one for GUI mode and one for batch mode.
Add Aspects to Object Using Dynamic Decorator
.
Your classs should concern only business logic not presentation (GUI or Batch, etc.). At runtime, you can attach presentation (GUI or non-GUI) code to objects of the class as needed.
No need to have the ugly attribute code in your class definition.
When working with legacy code, and trying to create tests, I often break out dependencies from classes or methods so I can write unit tests using mocks for these dependencies. Dependencies most often come in the form of calls to static classes and objects created using the new keyword in the constructor or other locations in that class.
In most cases, static calls are handled either by wrapping the static dependency, or if its a singleton pattern (or similar) in the form of StaticClass.Current.MethodCall() passing that dependency by its interface go the constructor instead.
In most cases, uses of the new keyword in the constructor is simply replaced by passing that interface in the constructor instead.
In most cases, uses of the new keyword in other parts of the class, is handled either by the same method as above, or by if needed create a factory, and pass the factory's interface in the constructor.
I always use Resharpers refactoring tools to help me all of these break-outs, however most things are still manual labour (which could be automated), and for some legacy classes and methods that can be a very very tedious process. Is there any other refactoring plugins and/or tools which would help me in this process? Is there a "break out all depencencies from this class in a single click" refactoring tool? =)
It sounds to me like all these steps are common for many developers and a common problem, and before I attempt writing plugin to Resharper or CodeRush, I have to ask, because someone has probably already attempted this..
ADDED:
In reflection to answers below: even if you might not want to break out everything at once (one click total break out might cause more problems than it helps) still being able to simply break out 1 methods dependencies, or 1-2 dependencies easily, would be of big difference.
Also, refactoring code has a measure of "try and see what happens just to learn how everything fits together", and a one click total break out would help that process tons, even if you dont check that code in..
I don't think there is any tool that can automate this for you. Working with legacy code means -as you know- changing code with little steps at a time. The steps are often deliberately small to prevent errors from being made. Usually the first change you should make is one that makes that code testable. After you've written the test you change that part of the code in such way that you fix the bug or implement the RFC.
Because you should take small steps I believe it is hard to use a refactoring tool to magically make all your dependencies disappear. With legacy systems you would hardly ever want to make big changes at once, because the risk of breaking (and not finding out because of the lack of tests) is too big. This however, doesn’t mean refactoring tools aren’t useful in this scenario. On the contrary; they help a lot.
If you haven't already, I'd advise you to read Michael Feathers' book Working Effectively with Legacy Code. It describes in great details a series of patterns that help you refactor legacy code to a more testable system.
Good luck.
When it comes to static call dependencies, you might want to check out Moles. It's able to do code injection at run-time to stub out any static or non-virtual method call with your own test implementation. This is handy for testing legacy code that wasn't designed using testable dependency-injected interfaces.
What is the best way to write the code ?
(1) Like directly writing the code in the button_click() event.
or
(2) Make the function of that code which I write in button_click() event and write this function in one class and then that function I should call in the button_Click() event.Like is it called three-tier approach to write the code ?
Like in button_Click() event I write the code to save the records in csv file from datatable.So I should write that code in button_Click() event or I should make one new function and one new class and write that code in that function which is the new class and calling that function in button_Click() event.
This is only one example but I am talking about all the code written in my application that which is the appropriate and best way to write the code and what are the benefits ? Note that I write the code in Winforms with c#.
You should go for the separate function in a different class. You should do that because you'll make the code reusable and create a decent separation between the user interface and application logic. Like this, you could for example change the UI without affecting the rest of the application.
Also take a look at MVC pattern, you'll understand better the whole idea.
The only situation where i think that the first option should be used is when it does some action that will affect the UI, and still i'll create this in a separate function inside the Form class.
If it's affecting the UI, it should be in the same class because it's related and for example if it's a code to refresh a grid i'll put this in a separate method inside the same Form class because this could be used in different places inside it. So changing the UI has no impact on the application, you just make your code reusable & maintainable.
It all depends on situation.
If you are going to make updates to the Form, then it's better to have the updating code in the Form. However, if there are lots of processing, then surely it's better design to have a separate class handle the job.
It all depends on situation.
Generally, you don't want any logic in the event handler, since GUIs tend to provide redundant mechanisms (context menu, menu bar, toolbar, accelerator key) for triggering the same command, and the event signatures aren't compatible for all of these. Then the question becomes whether your common function should go in the Form class or into the data model.
I often start out with the logic in the Form and then refactor it into model classes as needed. Many small apps will never get large enough that multiple classes are required for maintainability. As long as you avoid code duplication (i.e. copy+paste) then refactoring will be straightforward later if you find you need it.
It is always good to develop classes for jobs. As it makes your code reusable and it also implement three tier Architecture. The benefit is that it is easy to understand.
The important thing is that, it is only beneficial if you develop your classes appropriately. Develop methods in the class which can be reusable for you.
The another benefit is that it hides the complexity of your code.
There are two general approaches to adding structure to code: top down and bottom up. Top down structure comes from design work that can involve a formal or informal process and pure design artifacts like UML diagrams or functional specs. The ultimate goal in a top down process is to create classes and interfaces in your code that will provide appropriate structure to make your code maintainable. This can happen before you write the code, or as part of an iteration, but the idea is that you create the structure first, then create the code.
Bottom up structure comes from refactoring. For example, start with all your logic in a button click. When you add a menu item that does the same thing as the button click, move the code for your button click function into a private member function on the form. When you need the same features in a different part of the application, encapsulate the code and state variables used by your private member function into a class.
I'd recommend using both approaches. The right mix for your situation depends on the development team (size, location, ability to communicate) and the size of your application. Generally speaking, large applications require more top down, and on very small applications a minimal amount of top down design is adequate. But there should always be some high level planning, even for a small app.
I've seen a few articles on unit testing view models in MVVM and how the tests themselves are consumers of the view models, testing the functionality of the viewModel and model. However, I'm left wondering how I go about testing the views (UI) to ensure they are wired up to my view models properly. I don't want to write a test that, for instance, presses a button to make sure something is written to the db as this is effectively testing my VM, which i've already done.
For instance, I'd like to be able to write a test to make sure that a button is wired up to a specific command. Therefore preventing anyone from coming along and removing the button's command, making it no longer functional.
Is this possible? thanks.
But what if someone (hopefully a designer) wants to change the Button to a MenuItem? Your test will break and you'll have to fix it. One of the major boons of MVVM is that designers can really be free to arrange and rearrange the interface however they like without requiring too much back-and-forth with the developers. Writing unit tests against the UI annuls that boon.
I'm kind of playing Devil's advocate here. I'm not saying testing the UI is completely useless and never has a place in anyone's code base. What I'm saying is that the returns are diminishing, and that you may be trading one problem for another.
As for how you actually test a view in "isolation" . . . the easiest way I think would be to use view models with injected mock services. Your view models can use a service locator to grab dependent services, so your unit tests can inject dummy services. You could then use a combination of named-element references, visual tree crawling, and the WPF UI automation APIs to assert that different visual elements have properties set as expected.
I think there is something from Telerik (Art of test) which can help automate the raw UI.
http://www.artoftest.com/products/webaii.aspx
Though now I have looked it up that is Silverlight rather than WPF. Hopefully its a good starting point at least.