Is there a way to verify that a UnityEngine.Object.Destroy() method is called for a specific GameObject? Since the UnityEngine.Object is no interface I cannot mock it and check for Verifiable(). I am using C#, NUnit and Moq.
For example:
UnityEngine.Object.Destroy(audioSource);
The only thing I found was this How to Mock (with Moq) Unity methods but this is not what I need.
I appreciate any help or further information about this topic!
One thing I also did was that I extract the call from above into the calling interface and verify that this method is called, but this way I only shift the problem to another layer.
public interface IAudioSource
{
void DestroyUnityObject();
}
Then I can call the Unity Destroy method in there.
public void DestroyUnityObject()
{
UnityEngine.Object.Destroy(mAudioSource);
}
And mock the upper method call.
audioSourceMock.Setup(s => s.DestroyUnityObject()).Verifiable();
But as I said, this only puts the problem elsewhere and I can still not verify that the Unity method is called correctly.
With its current state, UnityEngine doesn't support mocking with Moq. This is because Moq (or any other framework based on DynamicProxy1) can't mock member which is not overridable/implementable (in case of interfaces).
Your best bet would be to create a wrapper as you suggested and inject it to classes that would normally use UnityEngine. This way, you can properly unit test those classes. Unfortunatelly, wrapper itself remains untestable (with Moq that is) and nothing can be done here, unless you use different isolation framework which supports static members mocking or use real implementation of UnityEngine (as regular integration test would).
1 I explained bit of details behind this limitation in my blog post - How to mock private method?
I successfully did this using the following system
public interface IUnityComponentDestroyer
{
void Destroy(Component component);
}
public class UnityComponentDestroyer : IUnityComponentDestroyer
{
/// <inheritdoc />
public void Destroy(Component component)
{
if (!Application.isPlaying)
{
Debug.Log($"Destroy called for {component.name} but it's not runtime, so ignoring call.");
return;
}
Object.Destroy(component);
}
}
Then you can call it in code like this:
IUnityComponentDestroyer backingFieldComponentDestroyer;
public IUnityComponentDestroyer ComponentDestroyer
{
get
{
backingFieldComponentDestroyer ??= new UnityComponentDestroyer();
return backingFieldComponentDestroyer;
}
set => backingFieldComponentDestroyer = value;
}
//Then call it with
ComponentDestroyer.Destroy(this);
And use it in a test like this:
IUnityComponentDestroyer fakeDestroyer = Substitute.For<IUnityComponentDestroyer>();
// do stuff
fakeDestroyer.Received().Destroy(Arg.Any<CurveAnimator>());
Related
I have a bunch of methods with varying signatures. These methods interact with a fragile data connection, so we often use a helper class to perform retries/reconnects, etc. Like so:
MyHelper.PerformCall( () => { doStuffWithData(parameters...) });
And this works fine, but it can make the code a little cluttery. What I would prefer to do is decorate the methods that interact with the data connection like so:
[InteractsWithData]
protected string doStuffWithData(parameters...)
{
// do stuff...
}
And then essentially, whenever doStuffWithData is called, the body of that method would be passed in as an Action to MyHelper.PerformCall(). How do I do this?
So, I just went to a AOP session this weekend, and here's a way to do it with PostSharp:
[Serializable]
public class MyAOPThing : MethodInterceptionAspect
{
public override void OnInvoke(MethodInterceptionArgs args)
{
Console.WriteLine("OnInvoke! before");
args.Proceed();
Console.WriteLine("OnInvoke! after");
}
}
And then decorate methods with [MyAOPThing]. Easy!
.NET Attributes are meta-data, not decorators / active components that automatically get invoked. There is no way to achieve this behaviour.
You could use attributes to implement decorators by putting the decorator code in the Attribute class and call the method with a helper method that invokes the method in the Attribute class using Reflection. But I'm not sure this would be a big improvement over just calling the "decorator-method" directly.
"Decorator-Attribute":
[AttributeUsage(AttributeTargets.Method)]
public class MyDecorator : Attribute
{
public void PerformCall(Action action)
{
// invoke action (or not)
}
}
Method:
[MyDecorator]
void MyMethod()
{
}
Usage:
InvokeWithDecorator(() => MyMethod());
Helper method:
void InvokeWithDecorator(Expression<Func<?>> expression)
{
// complicated stuff to look up attribute using reflection
}
Have a look at frameworks for Aspect Oriented Programming in C#. These may offer what you want.
This type of problem is pretty much what AOP (aspect oriented programming) aims to solve.
Tools such as PostSharp can provide cross-cutting concerns by re-writing the compiled code.
Scott Hanselman's podcast recently discussed AOP, so it might be worth having a listen.
Without the use of code generation, you can't do much against it. You could probably make the syntax better.
But what about using an extension method?
class static MyHelper
{
Wrap<T>(this object service, Action<T> action)
{
// check attribute and wrap call
}
}
usage:
RawFoo foo = ...
foo.Wrap(x => x.doStuffWithData(parameters...));
This is trivial, but you can't make sure that Wrap had been used.
You could implement a generic decorator. This decorator would be used once to wrap the service and then you can't call it without wrapping.
class Decorator<T>
{
private T implementor;
Decorator(T implementor)
{
this.implementor = implementor;
}
void Perform<T>(Action<T> action)
{
// check attribute here to know if wrapping is needed
if (interactsWithData)
{
MyHelper.PerformCall( () => { action(implementor) });
}
else
{
action(implementor);
}
}
}
static class DecoratorExtensions
{
public static Decorator<T> CreateDecorator<T>(T service)
{
return new Decorator<T>(service);
}
}
Usage:
// after wrapping, it can't be used the wrong way anymore.
ExtendedFoo foo = rawFoo.CreateDecorator();
foo.Perform(x => x.doStuffWithData(parameters...));
Check out aspect oriented frameworks. But be aware that while they hide complexity in each method, the existence of AoP features could make your program harder to maintain. It's a tradeoff.
It seems like what you want is similar to behavior of an IoC container or test runner framework, where it isn't actually executing from your assembly, but is running a dynamically emitted assembly built around your code. (Smarter folks than I have called this AOP in other answers)
So maybe in a stub for your app you could scan the other assemblies, build those emitted assemblies (which call MyHelper.PerformCall with the body of the decorated methods) then your program runs against the emitted code.
By no means would I start down the road of trying to write this without evaluating whether some existing AOP framework could accomplish what you need. HTH>
Seeing that you're willing to add a line of code to every method that needs this, why not just make the call to MyHelper from within the method itself, like this?
protected string doStuffWithData(parameters...)
{
MyHelper.PerformCall( () => { doStuffWithDataCore(parameters...) });
}
private string doStuffWithDataCore(parameters...) {
//Do stuff here
}
I'm studying Microsoft Fakes to implement unit tests in a project of mine.
If i've understood correctly, i use stubs to set the behavior of external components (that implement interfaces) that the main component i want to test is dependent from.
I use shibs to simulate the behavior of specific pieces of code at runtime.
My goal is to test a method of a manager class that has dependencies to other components all implementing interfaces. This method, among the other things, calls a private method.
In the test method i need to force the result of that private method.
The scenario is similar to the following code:
public class MyManager : IMyManager {
private IMyDependentManager _myDependentManager;
public MyManager(IMyDependentManager myDependentManager) {
this._myDependentManager = myDependentManager;
}
public void MyMethodToTest(data1, data2,...) { // method to test
...
byte[] res = MyPrivateMethod(data1); // i want to set the result of this method in order to NOT execute it, otherwise the test will fail
...
}
private byte[] MyPrivateMethod(data1) {
}
}
Any suggestion on how to setup the test would be very helpful.
The implication from the question and the private method's signature is that you need to separate the concerns.
Consider what the responsibility of your manager class is. Now consider what that private method is doing. I suspect you will find that the private method is not something that the manager class is (directly) responsible for - it is doing something that the manager should be delegating.
Move that private method into a separate class (as a public method), and use dependency injection to give it to the manager class, I would suggest doing this via an interface.
Now when testing your manager, you can supply it's constructor with a mock of the new class's interface to return whatever you like.
public Class Test{
GetDataset(RandomBoolean uncertain);
GetDataset2();
GetDataset3();
}
where method definitions are
public virtual void GetDataset2(){}
public virtual void GetDataset3(){}
public virtual void GetDataset(RandomBoolean uncertain)
{
if (uncertain.State){
GetDataset2();
}
else{
GetDataset3();
}
}
//mocking uncertain.State to return true
//ACT
testObject.GetDataset(uncertainMock);
I want to test if GetDataset2() was called internally when I act on testObject.GetDataset();
I am not mocking the testObject because it's the test object so if I try to do
testObject.AssertWasCalled(x => x.GetDataset2());
It won't let me do this because testObject is not a mocked object.
I am using Rhino Mocks 3.5, I am definitely missing something here.
What is the best way to achieve this.
The short answer is: you can't. On the other thing usually you don't want to. When you are unit testing the class, you want to make sure that the class does its computation correctly and that it has correct side effects. You shouldn't test the internals of the class, because this causes the coupling of the real code and the tests to be too strong. The idea is that you can freely change the implementation of your class and use your tests to make sure it still works correctly. You wouldn't be able to do it if your tests inspect the internal state or flow.
You have 2 options (depending on context)
You can structure your tests in a way that they only look at externally visible behaviour
If (1) is too hard, consider refactoring GetDataset2 into a separate class. Then you would be able to mock it while testing GetDataset method.
That's generally not how unit testing with mocks works.
You should be concerned with collaborators (which you stub/mock) and with results (state changes in the case of void methods), not with the internal workings of the system under test (calls to collaborators notwithstanding).
That is both because and why you can't make those types of behavioural observations (at least not without changing your classes to accommodate testing, by exposing private members or adding state-revealing members -- not good ideas).
Besides using a partial mock via Rhino Mocks, you could also create class derived from Test that replaces the implementation of GetDataSet2() with a function that records it was called. Then check that in your test.
It is a code smell that you're doing too much in one class though.
There is some info about partial mocks here. Here are some code snippets on how to do that with RhinoMocks and Moq.
Try this:
using Rhino.Mocks;
public class TestTest {
[Test]
public void FooTest()
{
var mock = new MockRepository().PartialMock<Test>();
mock.Expect(t => t.GetDataset2());
mock.GetDataset((RandomBoolean)null);
}
}
I have a bunch of methods with varying signatures. These methods interact with a fragile data connection, so we often use a helper class to perform retries/reconnects, etc. Like so:
MyHelper.PerformCall( () => { doStuffWithData(parameters...) });
And this works fine, but it can make the code a little cluttery. What I would prefer to do is decorate the methods that interact with the data connection like so:
[InteractsWithData]
protected string doStuffWithData(parameters...)
{
// do stuff...
}
And then essentially, whenever doStuffWithData is called, the body of that method would be passed in as an Action to MyHelper.PerformCall(). How do I do this?
So, I just went to a AOP session this weekend, and here's a way to do it with PostSharp:
[Serializable]
public class MyAOPThing : MethodInterceptionAspect
{
public override void OnInvoke(MethodInterceptionArgs args)
{
Console.WriteLine("OnInvoke! before");
args.Proceed();
Console.WriteLine("OnInvoke! after");
}
}
And then decorate methods with [MyAOPThing]. Easy!
.NET Attributes are meta-data, not decorators / active components that automatically get invoked. There is no way to achieve this behaviour.
You could use attributes to implement decorators by putting the decorator code in the Attribute class and call the method with a helper method that invokes the method in the Attribute class using Reflection. But I'm not sure this would be a big improvement over just calling the "decorator-method" directly.
"Decorator-Attribute":
[AttributeUsage(AttributeTargets.Method)]
public class MyDecorator : Attribute
{
public void PerformCall(Action action)
{
// invoke action (or not)
}
}
Method:
[MyDecorator]
void MyMethod()
{
}
Usage:
InvokeWithDecorator(() => MyMethod());
Helper method:
void InvokeWithDecorator(Expression<Func<?>> expression)
{
// complicated stuff to look up attribute using reflection
}
Have a look at frameworks for Aspect Oriented Programming in C#. These may offer what you want.
This type of problem is pretty much what AOP (aspect oriented programming) aims to solve.
Tools such as PostSharp can provide cross-cutting concerns by re-writing the compiled code.
Scott Hanselman's podcast recently discussed AOP, so it might be worth having a listen.
Without the use of code generation, you can't do much against it. You could probably make the syntax better.
But what about using an extension method?
class static MyHelper
{
Wrap<T>(this object service, Action<T> action)
{
// check attribute and wrap call
}
}
usage:
RawFoo foo = ...
foo.Wrap(x => x.doStuffWithData(parameters...));
This is trivial, but you can't make sure that Wrap had been used.
You could implement a generic decorator. This decorator would be used once to wrap the service and then you can't call it without wrapping.
class Decorator<T>
{
private T implementor;
Decorator(T implementor)
{
this.implementor = implementor;
}
void Perform<T>(Action<T> action)
{
// check attribute here to know if wrapping is needed
if (interactsWithData)
{
MyHelper.PerformCall( () => { action(implementor) });
}
else
{
action(implementor);
}
}
}
static class DecoratorExtensions
{
public static Decorator<T> CreateDecorator<T>(T service)
{
return new Decorator<T>(service);
}
}
Usage:
// after wrapping, it can't be used the wrong way anymore.
ExtendedFoo foo = rawFoo.CreateDecorator();
foo.Perform(x => x.doStuffWithData(parameters...));
Check out aspect oriented frameworks. But be aware that while they hide complexity in each method, the existence of AoP features could make your program harder to maintain. It's a tradeoff.
It seems like what you want is similar to behavior of an IoC container or test runner framework, where it isn't actually executing from your assembly, but is running a dynamically emitted assembly built around your code. (Smarter folks than I have called this AOP in other answers)
So maybe in a stub for your app you could scan the other assemblies, build those emitted assemblies (which call MyHelper.PerformCall with the body of the decorated methods) then your program runs against the emitted code.
By no means would I start down the road of trying to write this without evaluating whether some existing AOP framework could accomplish what you need. HTH>
Seeing that you're willing to add a line of code to every method that needs this, why not just make the call to MyHelper from within the method itself, like this?
protected string doStuffWithData(parameters...)
{
MyHelper.PerformCall( () => { doStuffWithDataCore(parameters...) });
}
private string doStuffWithDataCore(parameters...) {
//Do stuff here
}
I use RhinoMocks for a very simple test (I have to say I'm a beginner here). I tried to mock my object like this
var mock = MockRepository.GenerateMock<MyClass>();
create a helper stub :
var stubLinkedObject = MockRepository.GenerateStub<MyClass>();
then execute some logic which should call the method AddLink of the class MyClass with my stub argument. At the end of the test I simply assert that this method was actually called with
mockAction.AssertWasCalled(a => a.AddLink(stubLinkedObject));
I injected the correct dependency and the method is actually called. However, the problem is that the real implementation in MyClass is called and results in crash because some logic just can't be executed (link collection is not available etc.). How can I bypass the execution and simply check whether a method is called ? I have tried something like
mockAction.Stub(a => a.AddLink(null)).IgnoreArguments().Do(null);
before I go into the execution but this doesn't seem to work(I only get some exceptions). Any ideas and probably an explanation why the mock is executing the method logic at all ?
I've tried to reproduce. Here is the code which works fine for me
[Test]
public void Test()
{
var classMock = MockRepository.GenerateMock<MyClass>();
var linkedMock = MockRepository.GenerateStub<MyClass>();
classMock.Expect(c => c.MyMethod(linkedMock));
classMock.MyMethod(linkedMock);
classMock.AssertWasCalled(c => c.MyMethod(linkedMock));
}
public class MyClass
{
public virtual void MyMethod(MyClass linkedClass)
{
Console.WriteLine("MyMethod is called");
}
}
Your approach will only work if your method AddLink is virtual, otherwise the .Net runtime will always run the real implementation (and rightly so).
Usually the best practise is to use interfaces when doing dependency injection (so your class expects IMyClass instead of MyClass). This way it is much easier to use mocking frameworks - not only you don't have to remember to make all methods virtual, but you avoid the issues with passing correct arguments to MyClass's constructor (which in real world is a pain)