Reputation: 5075
I am working on .NET CORE 3.1 nUnit tests. I have class ClassX
with ServicesClassX
interface injected in its constructor. Within the ClassX, there is private method from where it is calling public method from ServiceClassX. I want to know, how I can verify that this method from ServiceClassX is been called??
I need to test if ServiceClassX.ProcessAzureMessage(message)
method been called/ verify.
ClassX
public class ClassX
{
private readonly IServiceClassX ServiceClassX;
public ClassX(IServiceClassX services){
ServiceClassX = services;
}
public Customer Run(){
var cus = MethodX();
return cus;
}
private Customer MethodX(){
bool valueExit = true;
string message = "myRecord";
if(valueExit){
ServiceClassX.ProcessAzureMessage(message);
}
}
nUnit
[TestFixture]
public class ClassXTests
{
private readonly ClassX _sut;
private readonly Mock<IServiceClassX> _serviceClassXMoq;
public ClassXTests(){
this._sut = new ClassX(_serviceClassXMoq.Object)
}
[Test]
public void Test1()
{
var customer = _sut.();
_serviceClassXMoq.Verify(?????????
}
Upvotes: 0
Views: 1415
Reputation: 232
Since you didn't specify you were using Moq, or had to, I'm going to suggest a slightly different route. Personally, I'm a fan of FakeItEasy over Moq because I feel it makes this type of testing much easier and it makes more sense in how it's implemented when you're reading through it.
Here's an example of how it could be done using the code you've given.
using FakeItEasy;
public class ClassXTests
{
private IServiceClassX _serviceClass;
private ClassX _sut;
public ClassXTests()
{
_serviceClass = A.Fake<IServiceClassX>();
this._sut = new ClassX(_serviceClass)
}
[Test]
public void Test1()
{
var customer = _sut.(); //Call your _sut method
//Verify the Verify method was called with any parameter of type MyType
A.CallTo(() => _serviceClass.Verify(A<MyType>._)).MustHaveHappened();
}
}
The A<MyType>._
is a shorthand for A<MyType>.Ignored
. When asserting that the call to the method happened, you have the option to pass in a specific expected value for the parameter or you can do .Ignored which will tell it not to care about what parameter values were passed in, just that the method was called with something.
If you had
public class Foo
{
public bool Verify(Bar bar);
}
public class Bar
{
public string Name { get; set; }
}
Your test might be that Verify was called with the name "K.Z", so you could do.
A.CallTo(() => _serviceClass.Verify(A<Bar>.That.Matches((x => x.Name.StartsWith("K")).MustHaveHappened();
They have some canned matching functions as well, but it's all well-documented.
Upvotes: 1