Skip to content

Commit

Permalink
feat(DependencyInjector): throw ArgumentNullException in SetDependency
Browse files Browse the repository at this point in the history
  • Loading branch information
jonisavo committed May 1, 2022
1 parent 53826c0 commit caa2e1b
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 2 deletions.
8 changes: 6 additions & 2 deletions Core/DependencyInjector.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;

namespace UIComponents.Core
Expand Down Expand Up @@ -63,11 +64,14 @@ private static object CreateInstance(Type dependencyType)
return instance;
}

public void SetDependency<T>(T instance) where T : class
public void SetDependency<T>([NotNull] T instance) where T : class
{
if (instance == null)
throw new ArgumentNullException("Dependency can not be set as null.");

DependencyDictionary[typeof(T)] = instance;
}

public T Provide<T>() where T : class
{
var type = typeof(T);
Expand Down
44 changes: 44 additions & 0 deletions Tests/DependencyInjectorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using NUnit.Framework;
using UIComponents.Core;

namespace UIComponents.Tests
{
[TestFixture]
public class DependencyInjectorTests
{
private interface IDependency {}

public class DependencyOne : IDependency {}

public class DependencyTwo : IDependency {}

[TestFixture]
public class SetDependency
{
[Test]
public void Switches_The_Dependency()
{
var injector = new DependencyInjector();

injector.SetDependency<IDependency>(new DependencyOne());

Assert.That(injector.Provide<IDependency>(), Is.InstanceOf<DependencyOne>());

injector.SetDependency<IDependency>(new DependencyTwo());

Assert.That(injector.Provide<IDependency>(), Is.InstanceOf<DependencyTwo>());
}

[Test]
public void Throws_Exception_If_Null_Is_Given_As_Parameter()
{
var injector = new DependencyInjector();

Assert.Throws<ArgumentNullException>(
() => injector.SetDependency<IDependency>(null)
);
}
}
}
}
3 changes: 3 additions & 0 deletions Tests/DependencyInjectorTests.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit caa2e1b

Please sign in to comment.