Thursday, 17 July 2008

Design for Testability - Dependencies

Hello,


This post is a continuation on previous posts about design-for-testability (here and here).

Control and observation are important characteristics in test-automation. If our code under test makes an effort to facilitate this , we improve the testability of our code. Improving the testability should lead to find any errors in our code more easily. The more we errors we find early in the development cycle, the cheaper it is to correct them. We early testing and defect correction, we get a good feel on the quality of the software. We can make educated decisions on when to promote the code to QA and/or production. When our customer can use our software to do their job , they create value for the company they work for ….(I will stop rambling here) . But you see , testability (and in a broader sense quality assurance) should be baked into the software. The entire organization can benefit from it.

Let’s start on the “control” aspect of our code under test (CUT) and specifically on the controlling the dependencies of our CUT with other parts of the program or the environment it runs in.

It is in the nature of an object-oriented language to build up a program from lot of different “units” where some “units” or better classes work closely together to make something happen. Object-oriented principles like single-responsibility, information-hiding , inheritance , etc are common in this world. So it is quite natural that classes have dependencies on other classes. The term coupling is often used to state the existence of relationships between class (inheritance, composition , etc). coupling is evitable. If there were no coupling we would end up with monolithically part of codes, actually they would be separate programs. The large classes would be too complex and the cohesion of the operations and member data would very low.

In the realm of testability we sometimes want to be able to test a class in a controlled way, maybe even in total isolation. In order to do that we must be able to control the dependencies. The fewer the dependencies the easier it will be. Hence “managed” coupling can increase testability.

Programs run on machines and make also use of their environment. For example the file system, Message Queue system, database systems , web services, etc. These resource dependencies are expressed in the programs usually via string tokens. For example a folder name, database connection string, queue name, web service URL etc. A good practice of course is to externalize the values for these resources for example in a configuration file. These practice is also beneficial for testability. Avoiding “hard-coded” resource strings in your code is of course not a good programming practice. Because many times the resource string are depended on where the program actually will run. For example development , production or …testing. So controlling the resource tokens outside the program can give us flexibility will setting up tests.
.NET has excellent support to easily consume these externalized resource identifiers in your programs. In the Visual Studio test framework you can easily let the test framework pick up these configuration files and let your code under test use the configured element just like if the code under test was running in their proper host (windows app, web service, etc). In other words , you will copy the configuration info that you need for the code under test from the base app.config or web.config in your test project and modify it as needed.

Let’s focus again on class dependencies. So dependencies are inevitable but we can make them more manageable for testing purposes ( or other reasons). In order to continue our discussion lets introduce some terms. If a class A depends on another class B to fulfil its functionality A is called a client class and B is called a server class. During unit test we want to test a class in isolation. Therefore we want to substitute its server classes by stubs or mock objects . Hard-wired dependencies to server classes hinder this. A dependency on a server class is hard-wired if the server class can not be substituted by some other class (e.g. a subclass of the server class) without changing the source code of the client class. Similar problems arise during integration testing if a server class should be stubbed because it is not test-ready. So how can we manage class dependencies that will benefit testability.
One of the areas lies in the construction of the dependencies. We don’t control them. So our solution strategy should revolve around getting control about the creation of the dependencies. Several techniques can help us to come up with a solution:

  • Interface-based programming : Separating the interface from the implementation is core principle. Our client class uses an abstraction of a server class (interface) , not a particular implementation of it (object). So during testing we could create another implementation of the server class that implements the correct interface. This “test-double” (Gerard Meszaros , xUnit patterns) version of our server class can for example always give a fixed set of values back or just ignores the fact that we ask it to do something. Interfaces are first-class citizen in .NET so you should have no problems with this. But this technique is just a first step toward the solution. We still need to hook up an implementation of the server class into the client class at test time.
  • Service locator: We would delegate the creation of objects to a specialized object that for example would fabricate objects based on a string identifier.
  • Provider model : Variation of Interface-based programming :. Abstract class , concrete implementation hooked up at runtime (configuration file). You can a test-specific implementation of the provider in order to control the tests
  • Manual Dependency injection : We will make another class responsible to establish the link between the client and the server. We will add a parameter of the server type to a method of the client class (a constructor, or a method that requires access to a server instance, or a dedicated setup method) which allows other objects to set the link. During testing the parameter(s) can be used to establish a link to a “test-double” instead.
  • Automatic dependency injection : a DI container framework takes care of the details of which objects are interconnected, so you can build each one independently. No need for passing the dependencies along with the constructor or methods or assigning properties with dependent objects

Still there some concerns (or trade-offs) you should take into account;

  • Information hiding :Why can’t leave it up to A to know its dependencies : Exposing the dependencies in a constructor function can be viewed a violation of encapsulation because now a client of Class A would have to create instances of Class B first before calling the constructor function of class A
  • The ability to substitute a server class is not always important for the “production” implementation. So is testability a good enough reason for implementing this possibility?
    We could make a special constructor that will accept the dependencies. The default constructor would use that hard-wired implementations.
    If there are dependencies on many server classes, this approach would result in too many parameters.
  • DI Framework to the rescue ...but Someone has to know the dependencies
    Assembler , DI Framework via declarations or via config files

There are still other things besides managed coupling you can work on to improve testability , hence the quality of our software : cohesion, encapsulation, ... But that's for another post.

Maybe you have others techiques to improve testability? If you would like to share them, don't hesitate to drop a commont.

Thanks in advance.

Best regards,

Alexander

Tuesday, 15 July 2008

Winforms (VS2005) DataGridViewComboBoxColumn, CTRL+0 and Cannot set Column 'myColumnName' to be null. Please use DBNull instead.

Hello,

I recently had some trouble with setting a dataGridViewComboboxColumn to a dbNull value with the CTRL+0 (zero) keystroke. As you may know, the datagrid supports the CTRL+0 keycode to force a dbNull value into cell and subsequentialy into the bound datasource (a datatable in my case). In other words you can use that to clear out a combo box's value and set it back to "nothing". At least when the bound datatable column allows DbNull to be true.

This is where I experienced some strange behaviour. I used a datagridView to display some customer data. One of the fields specifies an optional characteristic , namely the qualification of a customer. At database level this is enforced with a referential integrity constraint in the form of foreign key specification with a look-up table. The primary key of this look-up table is an integer. Of course in the datagrid , on the comboxbox showing the customer qualification , you will see a description (cfr. valuemember versus DisplayMember).

This is where it goes wrong. When I try to clear an existing value in the combobox , I get the following error message. Cannot set Column '' to be null. Please use DBNull instead.

What is even more strange is that when you have a combobox in the datagridview where the valueMember's type is System.String, You will not have this exception. It just works. It is also only apparent with a datagridViewComboxBoxColumn. Because if I would use a
DataGridViewTextBoxColumn for the "integer" case, I would neither experince any problem with CTRL+0.

I looked for a solution on Google and I stumbled on this post . Somewhere on the middle you will see an entry by Mark Rideout , DataGridView Program Manager Microsoft (27 Jan 2006, 3:34 PM ) . ...And he talks about a bug. But more interssenting for me he also hints a possible work-around.

He talks about overriding the DataGridView.ProcessDataGridViewKey Method . This method calls the key-processing method appropriate to the key pressed. In this method you could check for the CTRL+0 keystroke (D0) . That is exactly what I immediately tried out. I made a custom DataGridView (i.e. I created a class inheriting from the System.Windows.Forms.DataGridView and overrided the ProcessDataGridViewKey(see MSDN) . In this method I check for the CTRL+0 keystroke and some other characteristics . And if everything is true, I programmatically set the value for the currentcell to system.DbNull.Value.




Public Class CustomDataGridView : Inherits System.Windows.Forms.DataGridView


Protected Overrides Function ProcessDataGridViewKey(ByVal e As System.Windows.Forms.KeyEventArgs) As Boolean

If (e.KeyCode = Keys.D0 or e.KeyCode = keys.NumPad0) _
AndAlso TypeOf MyBase.Columns(MyBase.CurrentCell.ColumnIndex) Is _
System.Windows.Forms.DataGridViewComboBoxColumn _
AndAlso MyBase.Columns(MyBase.CurrentCell.ColumnIndex).ValueType IsNot _
GetType(System.String) Then
MyBase.CurrentCell.Value = System.DBNull.Value
Return True
Else
Return MyBase.ProcessDataGridViewKey(e)
End If


End Function
End Class


And guess what? It works (at least for me)! I also tried it in VS2008. There the same error is thrown ( I gues the bug report got lost somewhere ). But the same trick with ProcessDataGridViewKey works in VS2008.

I haven't tried it yet on other dataTypes like guid's and so. That why i check for datatypes in the code. But for my situation, this solution is OK .

Maybe there is another solution? If you know of one, don't hesitate to let me know...

Meanwhile if you like, you can download my test-program.

Thanks for reading.

Best regards,

Alexander

Wednesday, 9 July 2008

Design for testability - developer testing context

Hello,

Some more thoughts on design for testatbility in the developer testing context (see previous post ).

Test automation plays an important role in the developer testing context. The advent of the xUnit testing concept , nUnit and the integration of xUnit concept in Visual Studio, has put developer testing more in focus.
The test case is a description that tells us how we can see whether to system has done something as we expected it do that something.
Before executing a test , we must put the put the system in state so our test can actually operate. For example before testing the deletion of an order in our order system, the system must contain an order that we know of. For example a order record in a database.
The act of deleting an order necessitates that we can say to the system that we want to delete that explicit order . So not only to we need control of the initial situation, but we also need control of specifying the input and controlling the place where the order is physically kept (i.e. our test database with Order record with ID ORD1)
After executing the functionality, we must be able to verify if the system has actually done its piece of work. We must “see” the result of its processing. We need to compare this outcome with our initial expectations. A discrepancy can mean either the behaviour of the system was not correct or test case was not correct in terms of initial situation , the actions we took or the expected results.

An automated test (case) in xUnit terms can be viewed as follows (freely adapted on drawings found on http://xunitpatterns.com/ (Gerard Meszaros)).











Automated means that important steps in the execution of a test are preformed “automatically” . In other words exercising a test case on a unit (a method ) involves programmatically

  • supplying the initial situation (setup)
  • doing the actions (execute)
  • comparing the actual results with expected values (assert)
  • Cleaning up (teardown) so the next test case can proceed in a clean situation.

So how can we improve the testability in a developer context. On which aspects of the code can we influence the ease of performing developer test and facilitate the localisation of defects.

  • Control : In order make automation possible we need to be control of the initial situation as of the all the input that a method needs, so we can steer the processing of the unit in such a way it will produce the outcome we expect.
  • Observation : In order to compare actual and expected results , we must be able to observe what the outcome of the processing of a unit is.
  • Complexity: Network integration, database integration, Message queuing, Security , Registry, Windows services, COM+ , …. Makes it difficult to set up a test environment.
    Large methods with complex conditional flow necessitates many test case in order to get desired test coverage.
    Inheritance : abstract base class can not be instantiated.
    Large inheritance tree : may test cases to see if combination of base and specialized code works as expected.
  • Isolation: Ability to isolate certain dependencies and replacing them with test-doubles improves testability because we control what the test-doubles will do. That way we can concentrate on the logic in the CUT . The DUT will replaced by a test-double. Any calls from the CUT to the DUT (replaced by the test-double) will result in “controlled answers or behaviour”. Hence our test case for the CUT will be easier to setup
  • Separation of concerns : The class with a clear responsibility should improve testability in terms of knowing what to test in the first place.
    Smaller things to test
  • Heterogenity : Single language or language framework improves testability

If you have remarks or other thoughts, don't hesitate to drop a comment.

Best regards,

Alexander

Friday, 23 May 2008

Design for Testability

Hello,

I have been reading up on "design for testability" because some of the code I deal with is not always easy to test. Some thoughts ....

Context


“Business” wants software application to help them do their job. They use them because they bring “value” to them. In order to make that happen software application must do what they are required to do (fit for purpose) and must be “reliable”.

Through a mixture of process guidance, technology and human skills, to use the previous to elements efficiently and effectively, IT tries to deliver those application on time while adhering to the intrinsic quality attributes like for example reliability. Quality processes are put in place to ensure achievement. In order to assess the if the quality attributes are indeed incorporated into the software product, we need to check it. This is where testing comes in. Testing should give us insight into the quality of a system. This insight should help us decide to release the software for usage by the business because it can bring value to the business. Or it can tell us that there are still some discrepancies and we need to improve quality before handing it over to the business.

Testing is some something we must do although it does not immediately raises the quality of the system. It reports only. Many times “business” can not understand why we can’t deliver something right the first time. Testing costs money! Software creation is still an error-prone endeavour for many reasons despite all advancement in processes , technology and skills of people. In other words we start off with the assumption (certainty!) that software contains errors. Both functional and programming wise. Testing is about finding those. So it is important that we make the best possible test cases to reveal them. Use tooling to support our testing effort etc. Bust beside the test process it self , we can do more.

During the inception and construction of software we can introduce measures to make this testing effort even more efficient and effective. In other words we must make our system as “testable” as possible in order to and to facilitate performing the test and finding the errors.


Testability



Testability is about the ease of performing test against your system and ability of the tests to reveal any defects in a certain context. The context of the test , system testing (functional and non-functional) or developer testing, puts different meanings to testability. Also is it important that other software artefacts beside code, affect testability ; for example the requirement specification documents.

These are some aspects that influence the testability :

  • Understanding: The better you know what the thing is supposed to do , the better you can test for it.
  • Controlling ; You must be able to manipulate the input , in order to verify the correctness of the output.
  • Operational : We can only test it when it works !
  • Visibility : You can only verify the result , if you can see the output.
  • Simplicity : The less there is to test , the more quickly we can test it
  • Stability : The fewer the changes to less test if need to re-do and/or re-write

So manipulating the influencers, can change the testatbility !

It is important to acknowledge that testability does not come on its own. We must take testing into account from the beginning of our software development endeavour. Because we know our software will contain errors (this will only increase with the size and complexity of today’s systems), we must prepare for it to easily test our system and find them before we ship the code.

In other words we must design for testability. It is important because testing costs money. Also faulty software systems can cost the business money (in the best case or worse in case of threat to safety or life) . Therefore we must make the testing as effective and efficient as possible. But Business will benefit from this as well in the long run because we should be able to find defects thus raise the quality of the system, thus raise the value to the business.

Also future changes to the software to incorporate new requirements will benefit from this testability feature because we should be more confident to change working code with regression testing. Also external factors such as SOX compliance make it important for the business to assemble test evidence. Testable systems certainly can aid .

Design For testability



To increase both the ease and value of testing we can tack different areas of the software development process and the software product itself. For example

  • The software development methodology (“testable” requirement concept, etc)
  • The software technology (Procedural vs. Object-Oriented, Mainframe, etc )
  • The software architecture & design (Layered vs. monolithic, Coupling , Encapsulation , etc)
  • The code (Assertions , mocks/stubs , etc )
  • Tool support (Automation , Xunit framework , etx)
  • The developer (Training and education , code reviews , etc)

This broad spectrum calls for an holistic approach of course. The test context will put certain focus in that approach. For example

  • For functional testing you need good test reference in form requirements documents to establish your test cases
  • For System testing , you must be able to let system work under operational condition together with data and sometimes external systems.
  • For developer testing , you must sometimes be able test your unit in isolation and sometimes you would like to integrate a set of unit together.

Currently I'm interested in the developer testing context . So if you have experiences in raising the testability of your code and wish to share them , please do so. I would to hear from you how dependency injection help you ( or not) , how unit testing helped you find defects easily , etc.

Best regards,

Alexander

Tuesday, 13 May 2008

Application taxonomies

A classification of software application can help you to think about an architecture and/or determine a reference architecture in your catalogue.
Multiple characteristics can be used to set up a taxonomy. These taxonomies can help you I think because it sets up a context for making a software architecture and the usage of reference architectures. Usually one classification criterion alone doesn’t fit the entire application . Multiple axes.

I think one of the main message would be : Don’t be fooled that one reference architecture can be used in all scenarios.


  • Front-end technology
    o Windows (classic / touch screen)
    o Web-based (classic / Rich Internet client )
  • Distribution
    o Desk-top
    o Mobile/PDA
    o Sever
    o Distributed
  • Connected
    o On-line
    o Disconnected with on-line capabilities (smart client)
  • Communication
    o Asynchronous
    o Synchronous
  • Target
    o Consumer ( E-commerce, PDA)
    o Business (Traditional administrative data keeping or/and decision support)
    o Industry (MES, CIM, MRP, SCADA, real-time systems, PLC, Robotics)
    o Government E-government
    o Entertainment (Games)
  • Connectivity
    o Internet
    o LAN
    o WAN
    o VPN
  • Function
    o OLTP applications
    o Reporting applications ,Data warehouse, BI
    o Batch application
    o Service–oriented apps
    o Mobile device applications
    o Integration Applications ( ERP, Mainframe , etc)
    o Office applications and Office integration
    o Portals
    o System software
  • Organisation boundaries
    o Departmental
    o organisation
  • Usage pattern
    o Collaboration
    o Transactional, data keeping
    o Decision support
  • Time pattern
    o Long running “transactions” (Workflow)
    o Short running business transactions
  • Expected life-time
    o Short-term
    o Long term
  • Business area
    o Medical
    o Financial
    o Government
    o Industry
    o Commerce
    o Etc
  • Saas (Software as a Service ) software.
  • Etc.

What do you think?

Best regards,

Alexander

Software architecture decisions

Hello,

I recently had to give a definition of what a software architecture is . Not always that easy because Software Architecture is a much loaded term. If you want some formal definitions what a software architecture is , I recommend reading the information on http://www.sei.cmu.edu/architecture/published_definitions.html#Modern

General tone in these definitions is that you need to make high-level decisions about the system you' re going to build;
  • What style are you going to use? What is the structure?
  • How is it going to function? How do structural components of the architecture work together?
  • How does it meet the needs of all the stakeholders?

These high-level decisions have a high impact on the application. You can not change them easily if wanted or needed. Unless you’re prepared to put enough resources on the table.

In the bullets below I tried to sum up the different aspects of a software architecture. This list is not intended to be exhaustive.

  • Windows front-end or web front-end ( Rich Internet clients)
  • Layering, organization of code, separation of concerns,
  • Representing “business objects” persisted in a database
  • Exposed domain model or using Data transfer Objects / Presentation Model
  • DataSets versus classic classes
  • Organization of “back-end” logic
  • Organization of “Presentation” logic
  • Organization of “data-access” logic
  • Distribution or not
  • Remoting technology
  • Authentication, authorization, Audit
  • Data binding
  • Synchronous / asynchronous
  • ORM tools or raw ADO.NET
  • Multi-language
  • Exception handling versus status code
  • Instrumentation /Logging
  • Configuration
  • Caching
  • Database schema fixed or freely adaptable to need of design designs
  • Long-running “transactions” (conversations)
  • Reporting needs
  • Validation rules placement (Attribute based, Intra object based, Inter object based)
  • Etc.


It is important to take holistic approach towards the desicions. You will need to take some trade-offs and influencing criteria into account.

  • Kind of application built (taxonomy)
  • Tooling can constrain how you organize your application (code generators, frameworks, application building blocks, software factories ,etc)
  • Availability/knowledge of people can constrain the “feasibility” of your architecture
  • Process (top-down versus bottom up, behaviour-centric versus data-centric)
  • External / internal regulation can influence your architecture (SOX, internal Audit rules
  • Availability of reference architecture.
  • Non-functional requirements
  • Patterns
  • Time-to-Market
  • etc.

If I missing some points or you want to comment on this. Please feel free.

Best regards,

Alexander

Wednesday, 23 April 2008

Comparing to Linq to SQL

Hello,

Recently I took some time to investigate Entity Framework (CTP3) and Linq to SQL (RTM) further. While going through the examples I compiled following list with benefits & concerns. Maybe you have made a list for your own? Maybe you would care to comment. Please do so!


Linq to SQL



Benefits


  • Already available in VS2008 RTM
  • Generation of partial classes based on the database schema
  • Relationship are also detected and modelled as special properties in the entity classes
  • You work with these entity classes in you application.
  • Generated classes can be augmented with custom methods
  • Generated classes can be augmented with partial methods
  • LINQ support to specify queries
  • Dynamic generation of SQL (you do not have to write SQL your self)
  • Databinding support
  • Lazy loading (default) and immediate loading flexibility
  • Updating only changed columns
  • Optimistic Concurrency support through mapping directives.

Concerns


  • Basis mapping capabilities ( 1 table -> 1 Entity)
  • Only SQLServer
  • Distributed application requires special attention (dataContext)
  • Designer lets you start from a blank model but I haven't found something to create a database schema from the entity model.
  • Serialization of entity classes only set if generated with SQLMetal command-line tool option.

Entity Framework

Benefits

  • Generation of partial classes based on the database schema
  • Designer lets you start from a blank model but I haven't found something to create a database schema from the entity model.
  • You work with these entity classes in you application.
  • Generated classes can be augmented with custom methods
  • LINQ support to specify queries
  • Dynamic generation of SQL (you do not have te write SQL your self)
  • Databinding support
  • Normally foreseen to accommodate multiple database systems
  • More flexible mapping capabilities than Linq To SQL (fine-grained entity model, Inheritance mapping flexibility, etc)
  • Generated classes by default serializable
  • Data driven Object-modelling point of view
  • Lazy loading (default) and immediate loading flexibility

Concerns

  • Promised to be shipped with SP1 VS2008
  • Distributed application requires special attention (ObjectContext)
  • Designer lets you start from a blank model but I haven't found something to create a database schema from the entity model.
  • In the designer you can not add behaviour in the model( somewhat normal because it is a DSL for data persistence but still....). Entity are now more geared towards a data-container role.
  • Two flavours to query the databases system (linq to entities and entity SQL). At this moment I'm not very sure when to use which.

So if you have other points of interest or remarks , I would like to hear them.

Thanks in advance.

Best regards,

Alexander