Cybersecurity, obsolescence – and why testing alongside system development is the key to secure infrastructure

Cybersecurity, obsolescence – and why testing alongside system development is the key to secure infrastructure

Cybersecurity, obsolescence

-and why testing alongside system development is the key to secure infrastructure

by Nadia Hutchings | Jan 29, 2025

In our 2024 paper, The Challenge of Obsolescence in UK Critical Infrastructure, we highlighted an area of growing concern; the intersection of cybersecurity and obsolescence.

The UK’s National Cyber Security Centre (NCSC) wrote that 2023 has seen the addition of state-aligned actors to the ongoing threat from state actors, as a new and emerging cyber threat to Critical National Infrastructure (CNI). While the cyber activity of these groups often focuses on DDoS attacks, website defacements and/or the spread of misinformation, some have stated a desire to achieve a more disruptive and destructive impact against western CNI, including in the UK.  In fact, the UK is the third most targeted country in the world for cyber attacks

The convergence of outdated infrastructure and the rapidly evolving cyber threat landscape presents significant challenges for the UK's CNI. Recent reports and legislative initiatives highlight the urgent need to modernise these legacy systems and implement comprehensive cybersecurity measures to protect against current and future threats.

But what exactly are the risks? Are lives at stake? And how can cybersecurity be better managed in ageing software systems?

Zircon’s panel of experts explores the key risks associated with cybersecurity and obsolescence in this article, with key insights from our Principal Software Engineer, Matt Endicott – joined by Mark Parsons from our Board of Directors, and Nadia Hutchings, our Marketing Manager.

Why is obsolescence a cybersecurity issue?

Obsolescence is an inevitable byproduct of long-term infrastructure and technology investments.

Systems like railway signalling, ticketing platforms, electronic road signage, and industrial control mechanisms were all designed to last decades – mostly without considering modern cybersecurity threats. This is understandable; the shapeshifting technological landscape means that, while educated predictions can be made, future threats can’t be known in advance.

As, these systems age, they are less likely to receive updates or patches, leaving them exposed to vulnerabilities.

Historically, critical systems were built to operate autonomously and disconnected from wider networks. While this limited external attacks, modern demands for connectivity have introduced new risks.  Key examples being the 2015 Jeep hack, 2016’s Mirai Botnet, 2021’s Verkada Hack and of course the now infamous Stuxnet (an event we cover below).

Mark introduces the risks with interconnected systems that have known (or unknown) vulnerabilities – and why they might be exploited;

“You could easily cause disruption to the UK infrastructure, be it road, rail, nuclear – or whatever industry you’re talking about. It would be fairly easy to take down the power grid… or cause traffic chaos.”

As for motives? Mark adds;

“Financial gain is the most obvious one for non-state actors. Private hacking companies – they're after cash, of course. But state actors … They would be more after disruption and embarrassment.”

In sectors like energy, defence, road, and rail, connectivity introduces serious cybersecurity vulnerabilities. But exactly how big are the risks?

What are the biggest risks of cybersecurity vulnerabilities in obsolete systems?

The risks associated with outdated systems can impact safety. But the risk to life is actually quite low.

As Nadia explains;

“Trains are designed to fail safely… It’s not like in the movies where someone’s taken control of the train remotely – it’s actually really hard to do that – but you can create chaos without even touching the core systems… you can cause massive disruption to Rail Operators just by stopping people from getting tickets.”

The key risks are financial and operational. Disruption is usually the key goal of cyber attacks, along with ransom – but state-sponsored actors are also a threat.

1. Operational disruption

Hackers targeting critical infrastructure can cause significant delays and inefficiencies. For example, disabling ticketing systems or luggage tracking at an airport can lead to cascading disruptions across the entire network.

As an example, in September 2024, a major cyber attack targeted 20 railway stations across the United Kingdom – disrupting services and highlighting vulnerabilities within the transport network's digital systems.

This came shortly after a separate attack on TfL, which exposed sensitive consumer data and prompted a wave of attacks in its wake. The incident is ongoing.

2. Ransomware attacks

As famously seen with the NHS cyber attack, an event that cost the NHS approximately £92m, ransomware exploits outdated systems to encrypt critical files, demanding payment to restore access.

3. State-sponsored attacks

Countries may target critical infrastructure in “enemy states”, not for financial gain, but to cause embarrassment, disruption, or chaos. These attacks can provide a political or tactical advantage, be used as a show of strength – or a demonstration of opponents’ weaknesses.

Matt adds;

“...If you want to read about what's really possible, read about Stuxnet, which was maybe 15 years ago, but that was… A virus that could be installed on controller devices. These are embedded bits of kit… They had a virus that could install on these controllers and report back where it was, where it was being run from…”

Stuxnet was a sophisticated digital weapon, and one of the most prominent cyberwarfare moments in history. It is known to have attacked several nuclear weapons programmes, with varying levels of success –  as well as telecoms systems. Stuxnet highlighted to the world that CNI  networks we all depend on are more vulnerable than we like to think, and arguably could be said to have provided the catalyst for the approaches we have developed to secure these critical infrastructures today.

What about safety risks?

Critical systems are designed to fail safely. They tend to be highly isolated from wider networks, to mitigate risk – and have layered subsystems that prevent catastrophic failure.

While some disruptions can pose indirect safety risks, attacks that target critical safety systems – like the railway’s interlocking system – would require an “inside job” of considerable effort to pull off. And such an effort wouldn’t go unnoticed.

That said, any successful attack would be highly localised, and human intervention at the point of failure would provide an additional layer of security.

Mark adds that to sabotage a safe system would require intricate knowledge of how it works and how it's configured – as well as direct access to it;

“The best you could hope for is to turn it off… It'll be very difficult to make them act in a way that will put somebody's life in danger.”

How often is critical infrastructure targeted?

Cyberattacks on railway systems have increased by 220% in the last five years, with incidents increasing worldwide over the last decade.

Attacks on road infrastructure are rarer – but as Mark explains;

“... If you set all of the signals at a set of traffic lights to red – that's going to cause chaos.

And if you set them all to green, that will cause chaos. But in both cases, they're unlikely to cause somebody to do something that's going to have a serious impact.”

“Because, as I'm sure you're aware, green does not mean go. It means ‘proceed with caution’, as stated in section 17.3 of the Highway Code...”

Again, human intervention will add another layer to reduce the risk.

In the industrial sector, the UK government’s Cyber security breaches survey 2024 reveals that;

“Half of businesses (50%) and around a third of charities (32%) report having experienced some form of cyber security breach or attack in the last 12 months.”

“This is much higher for medium businesses (70%), large businesses (74%) and high-income charities with £500,000 or more in annual income (66%).”

Attacks are increasing across the board. So – why can’t we just update these systems?

Why are security updates challenging in critical infrastructure?

Updating ageing systems is easier said than done.

Many were not designed with regular updates in mind, and the environments they operate in – like railways or nuclear power stations – pose significant logistical challenges.

Matt says that because of these challenges, many systems have simply been ignored;

“In the past, people just kind of ignored it. There are systems where regular security updates have been considered, but many others didn’t account for it until probably the last five years, and maybe not even that long.”

These overlooked systems now represent a massive risk, as they weren’t designed to handle today’s demands for connectivity.

That being said, some systems are not connected to broader networks at all, making remote updates impossible. These require engineers on-site, to manually install updates – but even this may not be possible due to ageing hardware, unsupported software, and everything else that can arise with legacy systems.

Shutting down infrastructure for updates is also hugely disruptive to operations, and can potentially cost millions. UK railways, for example, have to carefully coordinate any operational downtime to reduce disruption. Highways face a similar issue, although to a lesser extent.

How can industries rise to these challenges – and make sure that critical infrastructure is kept as secure as possible?

The solution combines proactive testing, robust system design, and continuous monitoring.

Addressing the challenge of obsolescence and cybersecurity

1. Developing rigorous testing environments

In software development, testing often gets left to the last minute. Project deadlines overrun, and testing is often what suffers.

Mark says;

“Projects always run late. Testing comes at the end of the project, so it gets squeezed. That’s bad for a million reasons, but the main one is that people don’t spend enough time creating a test environment to properly test the system before deployment.”

For critical systems, it’s absolutely vital to begin testing alongside system development.

This can be achieved by creating test environments; simulated systems where code can be validated against a variety of scenarios, including cyber threats.

An example of where testing failed was the CrowdStrike outage of July 2024, which caused approximately 8.5 million Microsoft Windows operating systems to crash worldwide, leading to global disruption of critical services.

As Mark notes;

“CrowdStrike fell over on one of the most basic errors that you can possibly believe in software engineering… Does it fail properly? In the case of CrowdStrike, that was a zero length file.”

Failure to test adequately is what led to the “largest outage in the history of information technology”. This could have been avoided with a more diligent and rigorous testing procedure, and a robust testing environment running in parallel.

2. Implementing Continuous Integration and Deployment (CI/CD)

CI/CD allows systems to be continuously updated and tested in smaller increments, reducing the risks associated with larger, more infrequent updates. Automated pipelines can identify vulnerabilities as they arise, for faster resolutions without significant downtime.

Matt explains the advantages of CI/CD;

“With modern development techniques like continuous integration, everything is automated. Developers write unit tests, and those tests run automatically whenever code is pushed. It saves time and ensures everything is repeated exactly the same way, every time.”

In CI/CD, software developers build the right unit, integration and system tests to run automatically as soon as code is pushed to repositories. After these automated tests, the system creates releases automatically.

This is far more rigorous than human testing could ever be, and far more efficient. It does take more time to develop initially, with a greater effort required at the start – but after the initial investment, updates are swift, precise, and reliable. As Matt puts it;

“Ten weeks writing some automated tests, then suddenly you can release every two weeks.”

Organisations should invest up front, building that environment once, so that they can continuously update without the traditional risks of downtime and disruption.

As systems approach obsolescence, or evolve into modern technologies, this cycle of continuous integration and deployment can help alleviate backlog – as new items can be bolted on to testing scripts.

3. Retrofitting legacy systems

Even older systems can benefit from modern testing and update mechanisms. Retrofitting may include:

  • Adding automated testing environments to legacy software systems
  • Introducing network connectivity for remote updates
  • Updating documentation to ensure current functionality aligns with system specifications

Documentation is often a big stumbling block with obsolescence management, and sometimes the lack of good documentation requires software to be reverse-engineered, so that it can be properly documented and understood.

Nadia reflects on some past retrofitting challenges;

“We’ve worked with clients where the documentation didn’t match the actual functionality. Some systems were written by one engineer 20 years ago, and now no one knows how they work. Bringing them up to date is a big task, but it’s worth it in the long run.”

Retrofitting, in both hardware and software, needs to be carefully managed, to close any security loopholes that might lead to breaches. Documentation can help this process greatly.

4. Addressing technical debt

Organisations that prioritise ongoing maintenance of software and hardware systems are less likely to fall into "technical debt". This is where neglected systems become costlier to repair or replace over time, because of a buildup of issues.

In the first instance, tackling technical debt can be intensive and costly – but the benefits include increased resilience to cyber threats, as well as smoother operations.

5. Continued best practice in cybersecurity

Organisations should implement cybersecurity measures across all systems, including regular vulnerability assessments, multi-layered security protocols, and employee training to recognise and mitigate cyber threats.

Cyber attacks are all too often a human and social engineering issue as much as they are a software engineering one, so training should always be up to date.

The UK government offers several resources on standards.

There’s guidance freely available from the National Cyber Security Centre (NCSC), the UK’s cybersecurity authority. The NCSC developed the Cyber Assessment Framework (CAF) for operators of essential services – which is the best place to start.

There’s also GovS 007 – a cybersecurity standard that sets out expectations and reasons for the security activities which organisations need to carry out, to protect government assets specifically.

Next steps for infrastructure and industry

While initial investments in automated testing, CI/CD pipelines, or system retrofits may seem costly, the long-term savings and risk reduction far outweigh these expenses.

Mark highlights the cost-benefit dynamic;

“It’s scary when you see the upfront costs, but in the long run, it’s worth it. The cost isn’t in replacing the equipment – it’s in accessing the infrastructure to replace it.”

Matt says;

“Software doesn’t rust – but the environments it runs in change. If you don’t maintain it, technical debt will catch up with you. It costs more in the long run not to act.”

Cybersecurity and obsolescence present a significant challenge. But it’s not insurmountable.

By addressing the issues facing infrastructure and industry now, we can collectively ensure smoother operations, reduced risks, and greater resilience – in an increasingly connected world.

How can Zircon help?

With our 25 years of expertise in Software and Systems engineering, one area we have come to specialise in is the analysis, update and securing of ageing infrastructure systems.

Our obsolescence management solutions include a thorough system analysis, to identify vulnerabilities and recommend solutions – giving our partners better documentation and an actionable plan.

From there, we oversee the implementation of CI/CD pipelines for continuous updates, and the retrofitting of legacy systems with modern integrations.

And we provide ongoing support, to ensure systems remain secure and compliant.

If you’re interested in learning more, get in touch – call 01225 764 444, or send your message to enquiries@zirconsoftware.co.uk.

The Challenge of Obsolescence in UK Critical Infrastructure

The Challenge of Obsolescence in UK Critical Infrastructure

Bridging the gap: The challenge of obsolescence in UK critical infrastructure

by Nadia Hutchings | Dec 18, 2024

Overview

Critical infrastructure in the UK—its railways, highways, and industrial frameworks—is designed for the long haul. But the digital systems powering and monitoring these structures tell a different story.

This disparity between physical and digital asset longevity creates significant operational, financial, and security challenges. As digital systems age faster than their physical counterparts, outdated software becomes a liability, threatening the functionality and safety of critical infrastructure.

In its latest observation paper, Zircon Software delves into the complexities of software obsolescence in sectors like transportation and industry, highlighting:

  • The Lifespan Disparity: Physical infrastructure assets are regularly designed with lifespans ranging from 50 to 100 years.  Digital assets on the other hand have an average lifecycle of around a decade or less.
  • Sectoral Challenges: From ageing railway signalling systems to highways racing to keep up with the adoption of modern predictive traffic management systems, each sector faces unique obstacles in keeping digital systems functional and secure.
  • The Drivers of Obsolescence: Hardware advancements, cybersecurity vulnerabilities, and compatibility issues with modern systems exacerbate the problem.
  • Solutions for the Digital Age: Proactive lifecycle management, modular software, digital twin technology, and government-backed innovation pave the way to mitigating these challenges.

The paper concludes that addressing software obsolescence requires strategic foresight, investment in innovation, and coordinated industry effort. By adopting these measures, the UK can future-proof its critical systems and ensure operational resilience in a rapidly evolving digital landscape.

Interested in learning more?
Read the full white paper: The Challenge of Obsolescence in UK Critical Infrastructure.

TIDS Progress Update – Live Platform Testing

TIDS Progress Update – Live Platform Testing

TIDS Progress Update - Live Platform Testing

by Nadia Hutchings | Oct 27, 2021

Since the last update back in July, we are pleased to announce that the TIDS hardware has successfully been installed onsite at the first of our trial stations. For the next 5 months, the TIDS system will remain in place to assess both its accuracy and how effective the audible deterrent is.

Currently the system is being run without the audible deterrent element in order to ascertain the accuracy of the trespass detection element.  For the duration of the test phase there will be an ongoing process of minimising the frequency of false positives via the alteration of parameters in the software, as well as experimentation with both the "restricted regions" (the areas of trespass detection) and "blanking regions" (the areas where detection does not occur).  If needs be alterations can be made to the physical camera set up in order to capture the key areas of trespass.

As we head into the winter months we will also be able to establish the efficiency of the system in more volatile weather conditions, where detection may be more difficult as a result of changes in light and visibility.

A second installation will soon be under way at the station at a second test site to undergo a similar test set up until the middle of next year.  Once the initial live test phase is complete we will use the findings from the trial to further develop the functionality of the anti-trespass deterrent and how it alerts station staff to trespass events. We will also be looking at developing TIDS as a marketable product.

Keep an eye on the blog for future updates on how the system is coping with the pressures of a live environment.

Update: Second Site Installation

The system has since successfully been installed at the second test site and the testing process is now under way.

Exposed to the Elements: Trespass Identification and Deterrent System (TIDS) is put to the Test

Exposed to the Elements: Trespass Identification and Deterrent System (TIDS) is put to the Test

Exposed to the Elements: Trespass Identification and Deterrent System (TIDS) is put to the Test

by Nadia Hutchings | Jul 18, 2021

Last year we announced our participation in an SBRi funding call from Network Rail to produce a system aimed at reducing trespass across the UK rail network. Since then, alongside the continued development of the software element behind the system, we have been busy working on our preparation for the upcoming onsite testing period.

Alterations to Hardware Set Up

In our original outline the plan was to install a pole to which the different pieces of hardware could be attached. Following surveys of the two sites the plan was altered so that the detection equipment would instead be fitted to one of the gantry's already in place.

Where the original pole installation accounted for the protection of equipment from potential weather and public damage, this was not the case with new gantry plan. There was also a need to minimise the number of separate "installations" to obtain permission for live site testing.

As a solution to the new problem, one of our engineers produced designs for an enclosure that would hold all of the detection equipment, including the camera and speaker. Not only would this provide the necessary level of protection, but would also reduce the number of installations to one.

SOAK Testing

Currently we are undertaking something a bit new to us here at Zircon, with access to the finished casing we have started the process of SOAK testing the final system set up. Up to this point the system has been only been run and tested within the comfort of an office environment, however before it goes into the more volatile environment of an active station we need to have confidence in its ability to run constantly for the duration of the live testing phase regardless of the conditions. This means detecting incidents and running the deterrent regardless of light level and varying weather conditions.

You may have also noticed from the CAD drawings that there are there are gaps in the casing to permit air to flow around the casing to allow for ventilation and to prevent overheating in the CPU's. The obvious downside to this layout is that it does present an opportunity for moisture to enter or build up within the casing. As a means to prevent water damage each component that makes up the system is IP66 rated and we have ensured that any water that does build up within the casing can drain out of the base. Ensuring that these measures are effective will be another element during this stage of testing.

As you can probably tell we may not have a fancy lab or test site in which to conduct this process, however this has not got in the way of progress. In the last couple of weeks the British weather has stayed true to its reputation and thrown pretty much all it can at us, swinging from beautiful sunshine and heat to heavy rain and humidity. We are pretty pleased to say that, so far under the watchful eye of one of our engineers and their family, there has been no break in the system's ability to detect intrusions into the defined incursion areas.

As stated previously, this step in the preparation process also provides a means for us to ensure that low light levels will have no impact on the accuracy of detection and sounding of the deterrant system. In order to allow for detection without a light source, the system is has infrared capabilities and we need to establish how this change in image quality could impact detection. So far we have discovered that the system seems to be much more sensitive once the change to infrared occurs. With this in mind we are working on finding the correct level of balance between accurate detection in the two extreme levels of light.

Unexpected Test Helps to Prove The Detection Capability

When you test in a controlled environment like an office it is all to easy to subconciously make sure the system is set up in a way that allows for the best results or, when working with video analytics, to behave in a specific manner that you know the system will be able to pick up on. This is a big part of why we are taking as many steps as we can in the testing of TIDS, to be sure that it will be a system that can be trusted. So it is always nice when you get to have a third party come in to run a test of their own. One of the engineers on the TIDS project was in for quite a suprise one weekend, when he recieved a notification of unauthorised incursion from the unit still located at our office in Trowbridge. Luckily it was not a burglar breaking in, but one of the cleaners happily going about his duties.

The Next Steps

Realistically the next big step forward for the TIDS solution will be it's installation on an active platform. Currently our aim is to obtain all of the permissions to allow for placement by the end of July with the system set to run for several months. This testing phase should help us establish the effectiveness of the deterrent and give us guidance on how to further improve the system.

Could Video Analytics Make a Difference on your Project?

If you are considering exploring Video Analytics, Machine Learning or AI and how it could enhance your product or system, our team of experts are here to help.

Avoiding Repeated Test Behaviour Across Multiple Tests with Test Fixtures

Avoiding Repeated Test Behaviour Across Multiple Tests with Test Fixtures

Avoiding Repeated Test Behaviour Across Multiple Tests with Test Fixtures

by Nadia Hutchings | Nov 16, 2020

For anyone who has had the pleasure of writing/maintaining tests for code that require the use of external dependencies, you will (hopefully!) have incorporated the use of a mock of a function/object. In gMock, you need to define the behaviour of a mock via the EXPECT_CALL & ON_CALL macros in each test before it is used. When multiple tests rely on the same use of a mock, the common method I see far too frequently is to either, copy-paste the mock's behaviour across each test case that relies it, or just dump all your assertions into a single monolithic test case to avoid copy-pasting. Both are terrible habits to fall into that lead to tests that are brittle and harder to read.

In this guide, I want to demonstrate ways in which you can recognise repeated test setups, and where utilising a Test Fixture class to resolve this can simplify production & maintenance of tests.

Bad Examples of Tests

Consider the following procedural function written in C. Let's say that we've been tasked to write a series of tests on some legacy code that when called retrieves some data from an external module (retrieveExternalData), before passing it on to a function that exists in another external module (sendMessage). For now, ignore the fact that this code is absolute trash and should have been refactored; it's hard to think of a good example!

Source Code
int functionUnderTest( enum DataType data_type )
{
int error_code;
struct SourceDataStructure external_data;
struct DestinationDataStructure modified_data;
    error_code = retrieveExternalData( &external_data );
     if( error_code == 0 )
{
// Modify data according to the data type
switch( data_type )
{
case 0:
// Modify data one way
...
break;
            case 1:
// Modify data another way
...
break;
            default:
// Return error
error_code = -1;
break;
     if( error_code == 0 )
{
error_code = sendMessage( &modified_data );
}
}
    return error_code;
}

In between these 2 external function calls, some manipulation of data occurs that varies depending on the value of data_type passed into this function. For now our tests will focus on testing that the data passed into 'sendMessage' was performed to specification according to the value of data_type.

But because of the fact that there are external dependencies that we need to mock in order to take full control over how the tests will operate, for many of the tests the mocked behaviour may be identical. As a result, different tests may exhibit the same patterns. See for example the following:

Repeating Test Cases
TEST( ModifyingData, ShallSetXWhenDataTypeIs0 )
{
struct SourceDataStructure source_data;
struct DestinationDataStructure output_data;
int error_code;
      //----------------------------- ARRANGE ----------------------------
// Configure relevant variables
source_data.SomeProperty1 = FOO;
source_data.SomeProperty2 = BAR;
      // Initialise output_data to invalid values
output_data.SomeProperty1 = INVALID_VALUE;
output_data.SomeProperty2 = INVALID_VALUE;
      // Configure the mock behaviour of retrieveExternalData
EXPECT_CALL( *_MockObject, retrieveExternalData )
.Times( 1 )
.WillOnce( DoAll( SetArgPointee<0>( source_data ), // Provide the source data when it is called
Return( 0 ) ) ); // Return no error
      // Configure the mock behaviour of sendMessage to capture the modified data
// and store it in output_data to allow us to assert on its properties later
EXPECT_CALL( *_MockObject, sendMessage )
.Times( 1 )
.WillOnce( DoAll( SaveArg<0>( &output_data ), // Capture the modified data
Return( 0 ) ) ); // Return no error
      //------------------------------- ACT ------------------------------
// Call the function under test with data type 0
error_code = functionUnderTest( 0 );
      //------------------------------ ASSERT -----------------------------
// Check that no error was returned
ASSERT_THAT( error_code, 0 );
      // Check that the modified data captured is correct for this data type
ASSERT_THAT( output_data.SomeProperty1, EXPECTED_FOR_DATATYPE_0 );
ASSERT_THAT( output_data.SomeProperty2, EXPECTED_FOR_DATATYPE_0 );
}
TEST( ModifyingData, ShallSetXWhenDataTypeIs1 )
{
struct SourceDataStructure source_data;
struct DestinationDataStructure output_data;
int error_code;
      //----------------------------- ARRANGE ----------------------------
// Configure relevant variables
source_data.SomeProperty1 = FOO;
source_data.SomeProperty2 = BAR;
      // Initialise output_data to invalid values
output_data.SomeProperty1 = INVALID_VALUE;
output_data.SomeProperty2 = INVALID_VALUE;

// Configure the mock behaviour of retrieveExternalData
EXPECT_CALL( *_MockObject, retrieveExternalData )
.Times( 1 )
.WillOnce( DoAll( SetArgPointee<0>( source_data ), // Provide the source data when it is called
Return( 0 ) ) ); // Return no error

      // Configure the mock behaviour of sendMessage to capture the modified data
// and store it in output_data to allow us to assert on its properties later
EXPECT_CALL( *_MockObject, sendMessage )
.Times( 1 )
.WillOnce( DoAll( SaveArg<0>( &output_data ), // Capture the modified data
Return( 0 ) ) ); // Return no error
      //------------------------------- ACT ------------------------------
// Call the function under test with data type 1
error_code = functionUnderTest( 1 );
      //------------------------------ ASSERT -----------------------------
// Check that no error was returned
ASSERT_THAT( error_code, 0 );
      // Check that the modified data captured is correct for this data type
ASSERT_THAT( output_data.SomeProperty1, EXPECTED_FOR_DATATYPE_1 );
ASSERT_THAT( output_data.SomeProperty2, EXPECTED_FOR_DATATYPE_1 );
}

We can clearly see that these tests are almost identical in every way except for the values that we're actually trying to test for. If the number of data types that change the behaviour of this function was to increase, this would add to the number of test cases that were needed. To make matters even worse, what happens if something changes to the external dependency that affects our code? It would probably lead to a lot of broken test cases and time would be wasted in trying to fix them all. Such pitfalls makes the process of refactoring code far more tedious than it ought to be.

Now the most natural conclusion to make when seeing code repeated would be to place that behaviour in its own function. That would be great, except for the fact that gMock will not allow the behaviour of the mocks to be defined in a function that can be called from a TEST macro. So how can this problem be solved? Thankfully, googletest provides us with...

Test Fixtures

In googletest, a Test Fixture is a class that allows us to control how a group of tests behave. We can use this to define a common behaviour for mocks and initialise data at the beginning of each test without having to continually repeat ourselves.

To begin with, the following is a bare-bones implementation of a test group derived from the TestFixture class:

TestFixture Implementation
class ModifyingData: public TestFixture
{
public:
// Constructor. Allows any data that needs to be created once, but
// used many times, to be initialised here.
ModifyingData() : TestFixture()
{
}
      // Test setup. This gets called before each test is run
void SetUp()
{
}
      // Test tear down. This gets called after each test has run
void TearDown()
{
}
}

With this class, we can now place the default behaviours of the mocks and initialise any data within the SetUp method as follows:

TestFixture with common behaviour
class ModifyingData: public TestFixture
{
public:
struct SourceDataStructure source_data;
struct DestinationDataStructure output_data;
      // Constructor. Allows any data that needs to be created once, but
// used many times, to be initialised here.
ModifyingData() : TestFixture()
{
}
      // Test setup. This gets called before each test is run
void SetUp()
{
// Configure relevant variables
source_data.SomeProperty1 = FOO;
source_data.SomeProperty2 = BAR;
          // Initialise output_data to invalid values
output_data.SomeProperty1 = INVALID_VALUE;
output_data.SomeProperty2 = INVALID_VALUE;
          // Configure the mock behaviour of retrieveExternalData
ON_CALL( *_MockObject, retrieveExternalData )
.WillByDefault( DoAll( SetArgPointee<0>( source_data ), // Provide the source data when it is called
Return( 0 ) ) ); // Return no error
          // Configure the mock behaviour of sendMessage to capture the modified data
// and store it in output_data to allow us to assert on its properties later
ON_CALL( *_MockObject, sendMessage )
.WillByDefault( DoAll( SaveArg<0>( &output_data ), // Capture the modified data
Return( 0 ) ) ); // Return no error
}
      // Test tear down. This gets called after each test has run
void TearDown()
{
}
}

Now for each test run, we no longer have to define the behaviour of the mocks, nor do we have to initialise commonly used data.

You may have also noticed that the mock behaviour is using the ON_CALL method instead of the EXPECT_CALL method. The reason that this is done is that I actually do not want to actually test whether a mocked function is called by default, I just want to define how that mocked function behaves if and when it is called. If I were to use EXPECT_CALL, then I am demanding that all tests for this group must always call these functions. This may not always be the case when tests focus on control flow that may result in sendMessage never being called, causing a test to fail unnecessarily. There's an interesting read that goes into more detail on why you would use ON_CALL over EXPECT_CALL here: Knowing When to Expect.

With this common setup out of the way, we can refactor the tests so that they are easier to read and far more maintainable. This time, all tests will use the TEST_F macro instead:

Improved Test Cases
TEST_F( ModifyingData, ShallSetXWhenDataTypeIs0 )
{
int error_code;
      //----------------------------- ARRANGE ----------------------------
// Nothing to do here anymore...
      //------------------------------- ACT ------------------------------
// Call the function under test with data type 0
error_code = functionUnderTest( 0 );
      //------------------------------ ASSERT -----------------------------
// Check that no error was returned
ASSERT_THAT( error_code, 0 );
      // Check that the modified data captured is correct for this data type
ASSERT_THAT( output_data.SomeProperty1, EXPECTED_FOR_DATATYPE_0 );
ASSERT_THAT( output_data.SomeProperty2, EXPECTED_FOR_DATATYPE_0 );
}
TEST_F( ModifyingData, ShallSetXWhenDataTypeIs1 )
{
int error_code;
      //----------------------------- ARRANGE ----------------------------
// Nothing to do here anymore...
      //------------------------------- ACT ------------------------------
// Call the function under test with data type 1
error_code = functionUnderTest( 1 );
      //------------------------------ ASSERT -----------------------------
// Check that no error was returned
ASSERT_THAT( error_code, 0 );
      // Check that the modified data captured is correct for this data type
ASSERT_THAT( output_data.SomeProperty1, EXPECTED_FOR_DATATYPE_1 );
ASSERT_THAT( output_data.SomeProperty2, EXPECTED_FOR_DATATYPE_1 );
}

Already, these tests become far easier to read, and are far more maintainable. This simplifies the process of modifying tests when changes to the source code are planned, or allows for quick updates to the behaviour of external dependencies if they are changed.

On a side note, you have probably noticed that the tests still repeat themselves. The good news is that unlike gMock's macros, googletest's assertion macros can be placed into a function, with parameters allowing us to define what values we want to assert against. Bad news is that a very useful feature of googletest's Test Explorer window in Visual Studio becomes slightly less useful. For any test that fails, the Test Explorer allows you to jump to the assertion that failed. If that assertion is within a function, it jumps to the line within that function, making it more difficult to see the overall context in which it failed. However, having less code overall is more beneficial in the long term than the slight annoyance introduced by having assertions within a function. In the interest of good coding practice, let's refactor the tests to make them even more maintainable:

Improved & Refactored Test Cases
void assertModifiedDataIsCorrect( int error_code,
                                 int expected_value_property1,
                                 int expected_value_property2 )
{
      // Check that no error was returned
    ASSERT_THAT( error_code, 0 );
      // Check that the modified data captured is correct for this data type
    ASSERT_THAT( output_data.SomeProperty1, expected_value_property1 );
    ASSERT_THAT( output_data.SomeProperty2, expected_value_property2 );
}
TEST_F( ModifyingData, ShallSetXWhenDataTypeIs0 )
{
      //----------------------------- ARRANGE ----------------------------
      // Nothing to do here anymore...
      //------------------------------- ACT ------------------------------
      //------------------------------ ASSERT -----------------------------
    assertModifiedDataIsCorrect( functionUnderTest( 0 ),
                                 EXPECTED_FOR_DATATYPE_0,
                                 EXPECTED_FOR_DATATYPE_0 ); 
}
TEST_F( ModifyingData, ShallSetXWhenDataTypeIs1 )
{
      //----------------------------- ARRANGE ----------------------------
      // Nothing to do here anymore...
      //------------------------------- ACT ------------------------------
      //------------------------------ ASSERT -----------------------------
    assertModifiedDataIsCorrect( functionUnderTest( 1 ),
                                 EXPECTED_FOR_DATATYPE_1,
                                 EXPECTED_FOR_DATATYPE_1 ); 
}

Deviating a Mock's Default Behaviour

It should be clear by now how we can avoid repeating ourselves when defining a mock's behaviour, but what do you do when testing for edge cases that may need a mock to do something differently? Referring back to the source code, we can observe that there is control flow within the function that will not modify any data when retrieveExternalData returns an error code other than 0:

Source Code: different control flow
error_code = retrieveExternalData( &external_data );
if( error_code == 0 )
{
// Modify data
....
}

The great thing about gMock is that it allows us to create a new behaviour for a mock, and gMock will use the most recent definition that matches, allowing us to use the same Test Fixture. An example of a test case for testing this control flow could be as follows:

Overriding Default Mock Behaviour
TEST_F( ModifyingData, ShallNotOccurWhenExternalDataIsNotAvailable )
{
int error_code;
int expected_error_code = -1;
      //----------------------------- ARRANGE ----------------------------
// Configure the mock behaviour of retrieveExternalData
ON_CALL( *_MockObject, retrieveExternalData )
.WillByDefault( Return( expected_error_code ) ) ); // Return an error
      // Ensure that data is not passed to sendMessage
EXPECT_CALL( *_MockObject, sendMessage )
.Times( 0 );
      //------------------------------- ACT ------------------------------
error_code = functionUnderTest( 0 );
      //------------------------------ ASSERT -----------------------------
ASSERT_THAT( error_code, expected_error_code );
}

 

In the above example, the mock's behaviour in ON_CALL is defined after the one in the Test Fixture's SetUp method, so it will take precedence over the one in SetUp.

It is also interesting that ON_CALL and EXPECT_CALL both follow this rule. This means that the most recent EXPECT_CALL can take precedence over an ON_CALL for the same mock, and vice-versa. This is useful as demonstrated in the above example, where it is important that we assert that sendMessage is never called when the function under test fails to retrieve any data from retrieveExternalData. We achieve this by specifying the cardinality of the mocked function's call as 0 ( .Times(0) ).

Other Tests to Consider

With this knowledge, consider how the default behaviours would differ when testing the following edge cases, and whether ON_CALL or EXPECT_CALL would be appropriate:

  • Passing a data_type outside of the range accounted for within this function. The function retrieveExternalData would still be called in the same way, but what happens to sendMessage?
  • How could a test be written in the same Test Fixture that forces sendMessage to return an error?

When Not To Deviate Default Mock Behaviour

If you ever find yourself having to deviate a mock's default behaviour in the same way more than once, it's probably a good time to ask yourself whether the Test Fixture has done everything that it can reasonably do. To avoid falling into the same trap and repeating yourself, it is probably a good idea to create a new Test Fixture and defining the default behaviour for those mock(s) in its SetUp method. At the end of the day, the less code there is to maintain, the better it is for everyone. If it helps, always pretend that the person lumped with the misfortune of maintaining your code is a psychopath who knows where you live...

More From The Blog

No Results Found

The page you requested could not be found. Try refining your search, or use the navigation above to locate the post.