Callback assertion Action was performed using nUnit

I have a class that has 2 callback actions:

public class MyClass { public void DoSomething(Action onSuccess, Action onFailure) { } } 

I am trying to write a test for this, but not sure how to β€œclaim” that my onSuccess been executed?

 [Test] public void ChangePassword_returns_false_if_user_does_not_exist() { var myClass = new MyClass(mockedDependency.Object); myClass.DoSomething( //what do i need to pass in, in order to Assert that onSuccess Action was executed?) } 
+4
source share
1 answer

You can create an action that changes some flag:

 [Test] public void ChangePassword_returns_false_if_user_does_not_exist() { var myClass = new MyClass(mockedDependency.Object); bool isExecuted = false; // flag to check Action success = () => isExecuted = true; // set flag to true when executed myClass.DoSomething(success, null); Assert.IsTrue(isExecuted); // check if flag changed } 

Or even use a local lambda to change the flag:

 [Test] public void ChangePassword_returns_false_if_user_does_not_exist() { var myClass = new MyClass(mockedDependency.Object); bool isExecuted = false; // flag to check myClass.DoSomething(() => isExecuted = true, null); Assert.IsTrue(isExecuted); // check if flag changed } 

Another approach - you can use Moq to check if the action is triggered or not. In this case, you do not need flags. First you need some interface with methods corresponding to the Action delegate signature:

 public interface IHelper // consider better name { void ShouldRun(); void ShouldNotRun(); } 

Then you can use mock to check how the actions were called:

 [Test] public void ChangePassword_returns_false_if_user_does_not_exist() { Mock<IHelper> helper = new Mock<IHelper>(); var myClass = new MyClass(ockedDependency.Object); myClass.DoSomething(helper.Object.ShouldRun, helper.Object.ShouldNotRun); helper.Verify(h => h.ShouldRun(), Times.Once()); helper.Verify(h => h.ShouldNotRun(), Times.Never()); } 
+5
source

Source: https://habr.com/ru/post/1488524/


All Articles