目次
はじめに
- この一連の記事は
- UnityのUnity Test Frameworkを使ったテストに関して調べたメモ書きに補足を足したもの
- Unityのテスト、およびDIコンテナ、モックライブラリの基本的な使い方やそれぞれの役割など入門レベルの解説
- ライブラリのリファレンス的な使い方などについては公式や他の記事参照
- 実機テストやCIは含まない
- TDDに関しては考慮しない
シリーズの目次
環境
- Unity 2021.3.29f1
- Package
- Test Framework 1.3.8
- com.unity.test-framework / 1.3.8
- Extenject 9.2.0
- VContainer 1.13.2
https://github.com/hadashiA/VContainer.git?path=VContainer/Assets/VContainer#1.13.2
- Moq
- 4.7.99 (Extenject内蔵)
- 4.20.69 (NuGet)
- NSubstitute
- v2.0.3.0 for .Net v4.5 (Extenject内蔵)
- 5.0.0 (NuGet)
https://github.com/neuecc/UniRx.git?path=Assets/Plugins/UniRx/Scripts
https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask
サンプル
public interface IUniRxSample
{
IReadOnlyReactiveProperty<int> OnReactiveProperty { get; }
IObservable<int> OnSubject { get; }
}
Moq
[Test]
public void UniRxMoqTest()
{
var reactiveDummy = new ReactiveProperty<int>();
var subjectDummy = new Subject<int>();
var mock = new Mock<IUniRxSample>();
mock.Setup(x => x.OnSubject).Returns(subjectDummy);
mock.Setup(x => x.OnReactiveProperty).Returns(reactiveDummy);
mock.Object.OnSubject.Subscribe(x => Assert.That(x, Is.EqualTo(1)));
subjectDummy.OnNext(1);
var results = new List<int>();
mock.Object.OnReactiveProperty.Subscribe(x => results.Add(x));
reactiveDummy.Value = 2;
Assert.That(results.Count, Is.EqualTo(2));
Assert.That(results[0], Is.EqualTo(0));
Assert.That(results[1], Is.EqualTo(2));
}
NSubstitute
[Test]
public void UniRxNSubstituteTest()
{
var reactiveDummy = new ReactiveProperty<int>();
var subjectDummy = new Subject<int>();
var mock = Substitute.For<IUniRxSample>();
mock.OnSubject.Returns(subjectDummy);
mock.OnReactiveProperty.Returns(reactiveDummy);
mock.OnSubject.Subscribe(x => Assert.That(x, Is.EqualTo(1)));
subjectDummy.OnNext(1);
var results = new List<int>();
mock.OnReactiveProperty.Subscribe(x => results.Add(x));
reactiveDummy.Value = 2;
Assert.That(results.Count, Is.EqualTo(2));
Assert.That(results[0], Is.EqualTo(0));
Assert.That(results[1], Is.EqualTo(2));
}