Dependency Injection

Written by Adrian Yong


Hands
Adrian Yong
09 July 2018

To improve our coding skills, we strive for better delivery and lower bugs.

To do this, we strive to test as much as possible; like unit testing.

This can lead to more often than not the need to change the way we code, for instance, the sole purpose of testing or testability.

Dependency injection is technique to realise the above.

The examples below will show a function that is not testable

Example
function ProcessFile()
{
dim objTransfer as new transfer
File.Move(objTransfer.fromSource,objTransfer.toSource) }

There is also a dependancy created.

Notice that this function does not have a parameter or property
You can call this function but unable to set the necessary conditions to test its effectiveness.

The example below shows minor changes to make it testable
Example
class Transfer
property fromSourceFile as string
property toDestFile as string
end class

function ProcessFile(objTransfer as Transfer)
{
File.Move(objTransfer.fromSourceFile, objTransfer.toDestFile)
}

The following examples illustrate a unit test in some detail

Example of unit test
Sub ReturnTrueOnMovingFile()
Dim obj as Process()
obj.ProcessFile(fileFrom, fileTo)
Dim result As Boolean = File.IsExist(filePath)
Assert.IsTrue(result)
End Sub

Author(s) Shoutout

Written by Adrian Yong

Hi everyone, if you have any question, feel free to message me. If you like this article or would like me to extend more on the subject you can email me. Feedback is always appreciated. I will write more. If I get a two thumbs up. =)

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL).