The other day I answered a question on StackOverflow on how to unit test code from a separate project. To increase its exposure I also added it here.
Say you have a TwinCAT project called MyProject which you want to test with the TcUnit library. For this you create another project MyProject_Tests. So you have the following folder structure:
repos
├── MyProject
| ├── MyProject
| | ├── Plc
| | | ├── POUs
| | | └── Plc.plcproj
| | └── MyProject.tsproj
| └── MyProject.sln
|
├── MyProject_Tests
| ├── MyProject_Tests
| | ├── Plc
| | | ├── POUs
| | | └── Plc.plcproj
| | └── MyProject_Tests.tsproj
| └── MyProject_Tests.sln
|
└── hardlinkPousToTestProject.bat
You then:
- Add a folder Tests under Plc in the MyProject_Tests project.
- Add a method you want to test to MyProject/MyProject/Plc/POUs.
- Edit the path names in
hardlinkPousToTestProject.batsuch that they point to the correct folders. So for the current example:for %%i in (.\path\to\project\POUs\*.TcPOU) do (becomesfor %%i in (.\MyProject\MyProject\Plc\POUs\*.TcPOU) do (- and
mklink /H .\path\to\testproject\POUs\%%~nxi %%ibecomesmklink /H .\MyProject_Tests\MyProject_Tests\Plc\POUs\%%~nxi %%i
- Run the batch script.
- Manually add the
.TcPOUfiles to the_MyProject\_Tests_ project - Add the MyProject_Tests\MyProject_Tests\Plc\POUs folder to the
.gitignorefile since these files are already in MyProject.
Your file structure should now look like this:
repos
├── MyProject
| ├── MyProject
| | ├── Plc
| | | ├── POUs
| | | | └── Function.TcPOU # Original file
| | | └── Plc.plcproj
| | └── MyProject.tsproj
| └── MyProject.sln
|
├── MyProject_Tests
| ├── MyProject_Tests
| | ├── Plc
| | | ├── POUs
| | | | └── Function.TcPOU # Hard linked file
| | | ├── Tests
| | | | └── Function_Tests.TcPOU
| | | └── Plc.plcproj
| | └── MyProject_Tests.tsproj
| └── MyProject_Tests.sln
|
└── hardlinkPousToTestProject.bat
Now you can change Function.TcPOU from either MyProject or MyProject_Tests!
What is hard linking?
With hard linking, identical copies of a file are created. All the copies still point to the original file. So, whenever a change is made to a hard linked file, or the original, the changes show up in all the files. Hard linking basically creates multiple access points to the same file from different locations.
Discuss: Github snippet.