SlideShare a Scribd company logo
1 of 19
Download to read offline
GenerativeArt—MadewithUnity
Christian Warnecke and Richard Fine
Unite Copenhagen 2019
In this talk
3
— What’s new in the Unity Test Framework
— Putting the Test Framework into practice
— Live demo
4
Unity Test Framework -
what’s new?
What’s new?
5
— Big push towards more flexibility and customization
— Migrated to a package so we can ship updates faster
– This means you get the source code, too!
TestRunner API
6
— Programmatically launch tests
— Retrieve the list of tests
— Register/unregister callbacks
New Callbacks
7
— When a test run starts/stops
— When a test starts/stops
— When building a player for tests
8
Putting it into practice
Splitting Build and Run
9
— Customize the test player build process to:
– Disable auto-run
– Save to a known location, instead of temporary
— Add custom result reporting to save results to a file
Splitting Build and Run - Build
10
[assembly:TestPlayerBuildModifier(typeof(SetupPlaymodeTestPlayer))]
public class SetupPlaymodeTestPlayer : ITestPlayerBuildModifier {
public BuildPlayerOptions ModifyOptions(BuildPlayerOptions playerOptions) {
playerOptions.options &= ~(BuildOptions.AutoRunPlayer | BuildOptions.ConnectToHost);
var buildLocation = Path.GetFullPath("TestPlayers");
var fileName = Path.GetFileName(playerOptions.locationPathName);
if (!string.IsNullOrEmpty(fileName))
buildLocation = Path.Combine(buildLocation, fileName);
playerOptions.locationPathName = buildLocation;
return playerOptions;
}
}
Splitting Build and Run - Save results in run
11
[assembly:TestRunCallback(typeof(ResultSerializer))]
public class ResultSerializer : ITestRunCallback {
public void RunStarted(ITest testsToRun) { }
public void TestStarted(ITest test) { }
public void TestFinished(ITestResult result) { }
public void RunFinished(ITestResult testResults) {
var path = Path.Combine(Application.persistentDataPath, "testresults.xml");
using (var xw = XmlWriter.Create(path, new XmlWriterSettings{Indent = true}))
testResults.ToXml(true).WriteTo(xw);
System.Console.WriteLine($"***nnTEST RESULTS WRITTEN TOnnt{path}nn***");
Application.Quit(testResults.FailCount > 0 ? 1 : 0);
}
}
Launching specific tests from a menu item
12
— Method wired up to menu item as usual ([MenuItem] etc)
— Create instance of a ScriptableObject callback object
— Register/deregister the callbacks in OnEnable/OnDisable
— Set up filters
— Execute
— When finished, display message, open results window, etc
Launching specific tests from a menu item
13
public class RunTestsFromMenu : ScriptableObject, ICallbacks {
[MenuItem(“Tools/Run useful tests”)] public static void DoRunTests() {
CreateInstance<RunTestsFromMenu>().StartTestRun();
}
private void StartTestRun() {
hideFlags = HideFlags.HideAndDontSave;
CreateInstance<TestRunnerApi>().Execute(new ExecutionSettings {
filters = new [] { new Filter{ categoryNames = new[] { “UsefulTests” }}}
});
}
public void OnEnable() { CreateInstance<TestRunnerApi>().RegisterCallbacks(this); }
public void OnDisable() { CreateInstance<TestRunnerApi>().UnregisterCallbacks(this); }
/* ...RunStarted, TestStarted, TestFinished... */
public void RunFinished(ITestResultAdaptor result) {
…
DestroyImmediate(this);
}
}
Running tests before the build
14
— Implement IPreprocessBuildWithReport
— Register a callback to get test results
— Use TestRunnerApi to run specific (Editor) tests
– Filtering by category is a good idea!
– Run synchronously!
— Check for what the results were
— Throw BuildFailedException if anything failed
Running tests before the build - result collector
15
public class ResultCollector : ICallbacks {
public ITestResultAdaptor Result { get; private set; }
public void RunStarted(ITestAdaptor testsToRun) { }
public void TestStarted(ITestAdaptor test) { }
public void TestFinished(ITestResultAdaptor result) { }
public void RunFinished(ITestResultAdaptor result)
{
Result = result;
}
}
Running tests before the build - preprocessor
16
public class RunValidationTestsBeforeBuild : IPreprocessBuildWithReport {
public void OnPreprocessBuild(BuildReport report) {
var results = new ResultCollector();
var api = ScriptableObject.CreateInstance<TestRunnerApi>();
api.RegisterCallbacks(results);
api.Execute(new ExecutionSettings {
runSynchronously = true,
filters = new[] { new Filter {
categoryNames = new[] { $"PreBuildValidationTests" },
testMode = TestMode.EditMode
} }
});
if (resultCollector.results.FailCount > 0)
throw new BuildFailedException($"One or more of the validation tests did not pass.");
}
}
17
Live demo!
Further Resources
18
— https://tinyurl.com/UnityTestFrameworkDocs
— https://tinyurl.com/UnityTestForum
— Ask The Experts
— Questions?
GenerativeArt—MadewithUnity
#unity3d

More Related Content

What's hot

2015年度GPGPU実践プログラミング 第5回 GPUのメモリ階層
2015年度GPGPU実践プログラミング 第5回 GPUのメモリ階層2015年度GPGPU実践プログラミング 第5回 GPUのメモリ階層
2015年度GPGPU実践プログラミング 第5回 GPUのメモリ階層
智啓 出川
 

What's hot (20)

Hyper-V、オンプレミスでもコンテナを
Hyper-V、オンプレミスでもコンテナをHyper-V、オンプレミスでもコンテナを
Hyper-V、オンプレミスでもコンテナを
 
ARM LinuxのMMUはわかりにくい
ARM LinuxのMMUはわかりにくいARM LinuxのMMUはわかりにくい
ARM LinuxのMMUはわかりにくい
 
Google Sheets経由でUnity Localization Packageのデータを更新する & ADXの多言語ボイス音声切り替え機能連携
Google Sheets経由でUnity Localization Packageのデータを更新する & ADXの多言語ボイス音声切り替え機能連携Google Sheets経由でUnity Localization Packageのデータを更新する & ADXの多言語ボイス音声切り替え機能連携
Google Sheets経由でUnity Localization Packageのデータを更新する & ADXの多言語ボイス音声切り替え機能連携
 
一歩進んだXen仮想化環境構築
一歩進んだXen仮想化環境構築一歩進んだXen仮想化環境構築
一歩進んだXen仮想化環境構築
 
Star Ocean 4 - Flexible Shader Managment and Post-processing
Star Ocean 4 - Flexible Shader Managment and Post-processingStar Ocean 4 - Flexible Shader Managment and Post-processing
Star Ocean 4 - Flexible Shader Managment and Post-processing
 
Best practices: Async vs. coroutines - Unite Copenhagen 2019
Best practices: Async vs. coroutines - Unite Copenhagen 2019Best practices: Async vs. coroutines - Unite Copenhagen 2019
Best practices: Async vs. coroutines - Unite Copenhagen 2019
 
ゲーム開発者のための C++11/C++14
ゲーム開発者のための C++11/C++14ゲーム開発者のための C++11/C++14
ゲーム開発者のための C++11/C++14
 
Parallel Futures of a Game Engine
Parallel Futures of a Game EngineParallel Futures of a Game Engine
Parallel Futures of a Game Engine
 
BPF Internals (eBPF)
BPF Internals (eBPF)BPF Internals (eBPF)
BPF Internals (eBPF)
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
An introduction to Realistic Ocean Rendering through FFT - Fabio Suriano - Co...
An introduction to Realistic Ocean Rendering through FFT - Fabio Suriano - Co...An introduction to Realistic Ocean Rendering through FFT - Fabio Suriano - Co...
An introduction to Realistic Ocean Rendering through FFT - Fabio Suriano - Co...
 
企業システムにSELinuxを適用するときの検討事項
企業システムにSELinuxを適用するときの検討事項企業システムにSELinuxを適用するときの検討事項
企業システムにSELinuxを適用するときの検討事項
 
Unite 2013 optimizing unity games for mobile platforms
Unite 2013 optimizing unity games for mobile platformsUnite 2013 optimizing unity games for mobile platforms
Unite 2013 optimizing unity games for mobile platforms
 
1076: CUDAデバッグ・プロファイリング入門
1076: CUDAデバッグ・プロファイリング入門1076: CUDAデバッグ・プロファイリング入門
1076: CUDAデバッグ・プロファイリング入門
 
Taking Killzone Shadow Fall Image Quality Into The Next Generation
Taking Killzone Shadow Fall Image Quality Into The Next GenerationTaking Killzone Shadow Fall Image Quality Into The Next Generation
Taking Killzone Shadow Fall Image Quality Into The Next Generation
 
Parallel Graphics in Frostbite - Current & Future (Siggraph 2009)
Parallel Graphics in Frostbite - Current & Future (Siggraph 2009)Parallel Graphics in Frostbite - Current & Future (Siggraph 2009)
Parallel Graphics in Frostbite - Current & Future (Siggraph 2009)
 
unique_ptrにポインタ以外のものを持たせるとき
unique_ptrにポインタ以外のものを持たせるときunique_ptrにポインタ以外のものを持たせるとき
unique_ptrにポインタ以外のものを持たせるとき
 
2015年度GPGPU実践プログラミング 第5回 GPUのメモリ階層
2015年度GPGPU実践プログラミング 第5回 GPUのメモリ階層2015年度GPGPU実践プログラミング 第5回 GPUのメモリ階層
2015年度GPGPU実践プログラミング 第5回 GPUのメモリ階層
 
UnboundとNSDの紹介 BIND9との比較編
UnboundとNSDの紹介 BIND9との比較編UnboundとNSDの紹介 BIND9との比較編
UnboundとNSDの紹介 BIND9との比較編
 
【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019
【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019
【Unite Tokyo 2019】Unityプログレッシブライトマッパー2019
 

Similar to QA your code: The new Unity Test Framework – Unite Copenhagen 2019

Tutorial ranorex
Tutorial ranorexTutorial ranorex
Tutorial ranorex
radikalzen
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
Tricode (part of Dept)
 

Similar to QA your code: The new Unity Test Framework – Unite Copenhagen 2019 (20)

UPC Testing talk 2
UPC Testing talk 2UPC Testing talk 2
UPC Testing talk 2
 
L08 Unit Testing
L08 Unit TestingL08 Unit Testing
L08 Unit Testing
 
Saucery for Saucelabs
Saucery for SaucelabsSaucery for Saucelabs
Saucery for Saucelabs
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
 
Android TDD
Android TDDAndroid TDD
Android TDD
 
N Unit Presentation
N Unit PresentationN Unit Presentation
N Unit Presentation
 
Nashville Symfony Functional Testing
Nashville Symfony Functional TestingNashville Symfony Functional Testing
Nashville Symfony Functional Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylight
 
Zend Framework 2 - PHPUnit
Zend Framework 2 - PHPUnitZend Framework 2 - PHPUnit
Zend Framework 2 - PHPUnit
 
Coded ui - lesson 4 - coded ui test
Coded ui - lesson 4 - coded ui testCoded ui - lesson 4 - coded ui test
Coded ui - lesson 4 - coded ui test
 
Android Unit Test
Android Unit TestAndroid Unit Test
Android Unit Test
 
Tutorial ranorex
Tutorial ranorexTutorial ranorex
Tutorial ranorex
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
So how do I test my Sling application?
 So how do I test my Sling application? So how do I test my Sling application?
So how do I test my Sling application?
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Testing your application on Google App Engine
Testing your application on Google App EngineTesting your application on Google App Engine
Testing your application on Google App Engine
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App Engine
 
Qtp training
Qtp trainingQtp training
Qtp training
 

More from Unity Technologies

More from Unity Technologies (20)

Build Immersive Worlds in Virtual Reality
Build Immersive Worlds  in Virtual RealityBuild Immersive Worlds  in Virtual Reality
Build Immersive Worlds in Virtual Reality
 
Augmenting reality: Bring digital objects into the real world
Augmenting reality: Bring digital objects into the real worldAugmenting reality: Bring digital objects into the real world
Augmenting reality: Bring digital objects into the real world
 
Let’s get real: An introduction to AR, VR, MR, XR and more
Let’s get real: An introduction to AR, VR, MR, XR and moreLet’s get real: An introduction to AR, VR, MR, XR and more
Let’s get real: An introduction to AR, VR, MR, XR and more
 
Using synthetic data for computer vision model training
Using synthetic data for computer vision model trainingUsing synthetic data for computer vision model training
Using synthetic data for computer vision model training
 
The Tipping Point: How Virtual Experiences Are Transforming Global Industries
The Tipping Point: How Virtual Experiences Are Transforming Global IndustriesThe Tipping Point: How Virtual Experiences Are Transforming Global Industries
The Tipping Point: How Virtual Experiences Are Transforming Global Industries
 
Unity Roadmap 2020: Live games
Unity Roadmap 2020: Live games Unity Roadmap 2020: Live games
Unity Roadmap 2020: Live games
 
Unity Roadmap 2020: Core Engine & Creator Tools
Unity Roadmap 2020: Core Engine & Creator ToolsUnity Roadmap 2020: Core Engine & Creator Tools
Unity Roadmap 2020: Core Engine & Creator Tools
 
How ABB shapes the future of industry with Microsoft HoloLens and Unity - Uni...
How ABB shapes the future of industry with Microsoft HoloLens and Unity - Uni...How ABB shapes the future of industry with Microsoft HoloLens and Unity - Uni...
How ABB shapes the future of industry with Microsoft HoloLens and Unity - Uni...
 
Unity XR platform has a new architecture – Unite Copenhagen 2019
Unity XR platform has a new architecture – Unite Copenhagen 2019Unity XR platform has a new architecture – Unite Copenhagen 2019
Unity XR platform has a new architecture – Unite Copenhagen 2019
 
Turn Revit Models into real-time 3D experiences
Turn Revit Models into real-time 3D experiencesTurn Revit Models into real-time 3D experiences
Turn Revit Models into real-time 3D experiences
 
How Daimler uses mobile mixed realities for training and sales - Unite Copenh...
How Daimler uses mobile mixed realities for training and sales - Unite Copenh...How Daimler uses mobile mixed realities for training and sales - Unite Copenh...
How Daimler uses mobile mixed realities for training and sales - Unite Copenh...
 
How Volvo embraced real-time 3D and shook up the auto industry- Unite Copenha...
How Volvo embraced real-time 3D and shook up the auto industry- Unite Copenha...How Volvo embraced real-time 3D and shook up the auto industry- Unite Copenha...
How Volvo embraced real-time 3D and shook up the auto industry- Unite Copenha...
 
Engineering.com webinar: Real-time 3D and digital twins: The power of a virtu...
Engineering.com webinar: Real-time 3D and digital twins: The power of a virtu...Engineering.com webinar: Real-time 3D and digital twins: The power of a virtu...
Engineering.com webinar: Real-time 3D and digital twins: The power of a virtu...
 
Supplying scalable VR training applications with Innoactive - Unite Copenhage...
Supplying scalable VR training applications with Innoactive - Unite Copenhage...Supplying scalable VR training applications with Innoactive - Unite Copenhage...
Supplying scalable VR training applications with Innoactive - Unite Copenhage...
 
XR and real-time 3D in automotive digital marketing strategies | Visionaries ...
XR and real-time 3D in automotive digital marketing strategies | Visionaries ...XR and real-time 3D in automotive digital marketing strategies | Visionaries ...
XR and real-time 3D in automotive digital marketing strategies | Visionaries ...
 
Real-time CG animation in Unity: unpacking the Sherman project - Unite Copenh...
Real-time CG animation in Unity: unpacking the Sherman project - Unite Copenh...Real-time CG animation in Unity: unpacking the Sherman project - Unite Copenh...
Real-time CG animation in Unity: unpacking the Sherman project - Unite Copenh...
 
Creating next-gen VR and MR experiences using Varjo VR-1 and XR-1 - Unite Cop...
Creating next-gen VR and MR experiences using Varjo VR-1 and XR-1 - Unite Cop...Creating next-gen VR and MR experiences using Varjo VR-1 and XR-1 - Unite Cop...
Creating next-gen VR and MR experiences using Varjo VR-1 and XR-1 - Unite Cop...
 
What's ahead for film and animation with Unity 2020 - Unite Copenhagen 2019
What's ahead for film and animation with Unity 2020 - Unite Copenhagen 2019What's ahead for film and animation with Unity 2020 - Unite Copenhagen 2019
What's ahead for film and animation with Unity 2020 - Unite Copenhagen 2019
 
How to Improve Visual Rendering Quality in VR - Unite Copenhagen 2019
How to Improve Visual Rendering Quality in VR - Unite Copenhagen 2019How to Improve Visual Rendering Quality in VR - Unite Copenhagen 2019
How to Improve Visual Rendering Quality in VR - Unite Copenhagen 2019
 
Digital twins: the power of a virtual visual copy - Unite Copenhagen 2019
Digital twins: the power of a virtual visual copy - Unite Copenhagen 2019Digital twins: the power of a virtual visual copy - Unite Copenhagen 2019
Digital twins: the power of a virtual visual copy - Unite Copenhagen 2019
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

QA your code: The new Unity Test Framework – Unite Copenhagen 2019

  • 1.
  • 2. GenerativeArt—MadewithUnity Christian Warnecke and Richard Fine Unite Copenhagen 2019
  • 3. In this talk 3 — What’s new in the Unity Test Framework — Putting the Test Framework into practice — Live demo
  • 4. 4 Unity Test Framework - what’s new?
  • 5. What’s new? 5 — Big push towards more flexibility and customization — Migrated to a package so we can ship updates faster – This means you get the source code, too!
  • 6. TestRunner API 6 — Programmatically launch tests — Retrieve the list of tests — Register/unregister callbacks
  • 7. New Callbacks 7 — When a test run starts/stops — When a test starts/stops — When building a player for tests
  • 8. 8 Putting it into practice
  • 9. Splitting Build and Run 9 — Customize the test player build process to: – Disable auto-run – Save to a known location, instead of temporary — Add custom result reporting to save results to a file
  • 10. Splitting Build and Run - Build 10 [assembly:TestPlayerBuildModifier(typeof(SetupPlaymodeTestPlayer))] public class SetupPlaymodeTestPlayer : ITestPlayerBuildModifier { public BuildPlayerOptions ModifyOptions(BuildPlayerOptions playerOptions) { playerOptions.options &= ~(BuildOptions.AutoRunPlayer | BuildOptions.ConnectToHost); var buildLocation = Path.GetFullPath("TestPlayers"); var fileName = Path.GetFileName(playerOptions.locationPathName); if (!string.IsNullOrEmpty(fileName)) buildLocation = Path.Combine(buildLocation, fileName); playerOptions.locationPathName = buildLocation; return playerOptions; } }
  • 11. Splitting Build and Run - Save results in run 11 [assembly:TestRunCallback(typeof(ResultSerializer))] public class ResultSerializer : ITestRunCallback { public void RunStarted(ITest testsToRun) { } public void TestStarted(ITest test) { } public void TestFinished(ITestResult result) { } public void RunFinished(ITestResult testResults) { var path = Path.Combine(Application.persistentDataPath, "testresults.xml"); using (var xw = XmlWriter.Create(path, new XmlWriterSettings{Indent = true})) testResults.ToXml(true).WriteTo(xw); System.Console.WriteLine($"***nnTEST RESULTS WRITTEN TOnnt{path}nn***"); Application.Quit(testResults.FailCount > 0 ? 1 : 0); } }
  • 12. Launching specific tests from a menu item 12 — Method wired up to menu item as usual ([MenuItem] etc) — Create instance of a ScriptableObject callback object — Register/deregister the callbacks in OnEnable/OnDisable — Set up filters — Execute — When finished, display message, open results window, etc
  • 13. Launching specific tests from a menu item 13 public class RunTestsFromMenu : ScriptableObject, ICallbacks { [MenuItem(“Tools/Run useful tests”)] public static void DoRunTests() { CreateInstance<RunTestsFromMenu>().StartTestRun(); } private void StartTestRun() { hideFlags = HideFlags.HideAndDontSave; CreateInstance<TestRunnerApi>().Execute(new ExecutionSettings { filters = new [] { new Filter{ categoryNames = new[] { “UsefulTests” }}} }); } public void OnEnable() { CreateInstance<TestRunnerApi>().RegisterCallbacks(this); } public void OnDisable() { CreateInstance<TestRunnerApi>().UnregisterCallbacks(this); } /* ...RunStarted, TestStarted, TestFinished... */ public void RunFinished(ITestResultAdaptor result) { … DestroyImmediate(this); } }
  • 14. Running tests before the build 14 — Implement IPreprocessBuildWithReport — Register a callback to get test results — Use TestRunnerApi to run specific (Editor) tests – Filtering by category is a good idea! – Run synchronously! — Check for what the results were — Throw BuildFailedException if anything failed
  • 15. Running tests before the build - result collector 15 public class ResultCollector : ICallbacks { public ITestResultAdaptor Result { get; private set; } public void RunStarted(ITestAdaptor testsToRun) { } public void TestStarted(ITestAdaptor test) { } public void TestFinished(ITestResultAdaptor result) { } public void RunFinished(ITestResultAdaptor result) { Result = result; } }
  • 16. Running tests before the build - preprocessor 16 public class RunValidationTestsBeforeBuild : IPreprocessBuildWithReport { public void OnPreprocessBuild(BuildReport report) { var results = new ResultCollector(); var api = ScriptableObject.CreateInstance<TestRunnerApi>(); api.RegisterCallbacks(results); api.Execute(new ExecutionSettings { runSynchronously = true, filters = new[] { new Filter { categoryNames = new[] { $"PreBuildValidationTests" }, testMode = TestMode.EditMode } } }); if (resultCollector.results.FailCount > 0) throw new BuildFailedException($"One or more of the validation tests did not pass."); } }
  • 18. Further Resources 18 — https://tinyurl.com/UnityTestFrameworkDocs — https://tinyurl.com/UnityTestForum — Ask The Experts — Questions?