r/Zenject•
Luisoft

Testing scenes

Hello Zenjecters.

My team is trying to perfom some test with Zenject but we find a wall. We use a simple MVC system so to make it symple we have a class *View for every scene.

The problem comes when we want to test the state of the scene when the View class do something into it.

To make it works I just have a scene with a GameObject. This GameObject has a Zenjenct Binding with his Transform also as ID: SomeGameObject.

To keep it simple this is the View.

public class SampleView: IInitializable
{
    [Inject] private AEvent _event;
    [Inject(Id="SomeGameObject")] private _gameObject;
    public void Initialize()
    {
        _event += SetGameObjectActive;
    }

    private void SetGameObjectActive(bool enabled)
    {
        _gameObject.SetActive(enabled);
    }
}

Now we want to check that this GameObject is actually enabled when we fire the _event event.

So when I try to recreate the whole thing Zenject rejects me with no love.

The errors are: The object of type 'GameObject' has been destroyed but you are still trying to acess it.

Also: ZenjectException: Assert hit! Expected '' but found SampleTest. (Name of the scene)

This is the test that I'm trying to aproach, any ideas about testing scenes?

using Zenject;

public class SceneTests : ZenjectIntegrationTestFixture
{
    [Test]
    public void SceneTestZenject()
    {
        Container.InstantiateComponent<Transform>();
        var path = "Assets/Resources/SampleTest.unity";
        UnityEngine.EditorSceneManager.OpenScene(path);
        Zenject.Container.Bind<GameObject>().AsSingle();
        Initialize();
        var _gameObject = Container.Resolve<GameObject>();
        Assert.IsTrue(_gameObject.activeSelf);
    }
}

Thank you in advance.

Posted Jun 12, 2017, 9:22 AM UTC

21
brain_emesis•

Testing multiple scenes at once using Unity's Test Runner can be a bit tricky sometimes. It helps to understand how it works under the hood. When Unity executes a unit test via the test runner, it creates an empty scene with an empty name and makes that the active scene. This is where any game objects that you create get placed. This is also where ZenjectIntegrationTestFixture places a temporary SceneContext which it uses to run each test within.

So what seems strange about your test is that you load this SampleTest scene, but then bind a GameObject using the container in the main test scene. So the container you're binding to will not be used to inject on the SampleTest scene. Does the SampleTest scene have a SceneContext inside it?

2