How do I assert a method was called on this mocked dependency with moq and mspec? - moq

I was testing a model repository to see if it calls the message bus. I am not sure if this is a good test at all but here is my thinking: I would normally put the bus.send into the controller (this is an MVC web app) but since I don't want to test my controllers specifically for logic, I moved this into the repository. Controllers are simple in my case. Repository uses the bus and the model database to build the view models.
Anyways, point of this problem is the moq test I am running. I mocked the bus and wanted to verify that it is called from the repository.
The test looks like this:
public class when_creating_new_clinic
{
Establish context = () =>
{
clinicID = Guid.NewGuid();
model = new ClinicModel
{
ClinicID = clinicID,
Alias = "alias",
Title = "title"
// stuff omitted
};
newClinicData = new NewClinicData
{
ClinicID = clinicID,
Alias = "alias",
Title = "title"
// stuff omitted
};
cmd = new CreateClinicCmd(newClinicData);
bus = new Mock<IMessageBusAgent>();
repository = new ClinicModelRepository(bus.Object);
bus.Setup(b => b.Send(cmd));
};
Because it = () => repository.Create(model);
It should_send_create_clinic_command_to_bus = () =>
{
bus.Verify(b => b.Send(cmd), Times.Exactly(1));
};
static ClinicModelRepository repository;
static ClinicModel model;
static Mock<IMessageBusAgent> bus;
static NewClinicData newClinicData;
static Guid clinicID;
static CreateClinicCmd cmd;
}
The gist of the repository is this:
public class ClinicModelRepository : IClinicModelRepository
{
private readonly IMessageBusAgent m_bus;
public ClinicModelRepository(IMessageBusAgent bus)
: this()
{
m_bus = bus;
}
public void Create(ClinicModel clinicModel)
{
// stuff omitted (data is mapped from clinicModel)
m_bus.Send(new CreateClinicCmd(data));
}
}
The IMessageBusAgent is declared as:
public interface IMessageBusAgent : IDomainCommandSender, IDomainEventPublisher, IUnitOfWork
{
}
The result of the test looks like this:
when creating new clinic
» should send create clinic command to bus (FAIL)
Test 'should send create clinic command to bus' failed:
Moq.MockException:
Expected invocation on the mock exactly 1 times, but was 0 times: b => b.Send(when_creating_new_clinic.cmd)
Configured setups:
b => b.Send<CreateClinicCmd>(when_creating_new_clinic.cmd), Times.Never
Performed invocations:
IDomainCommandSender.Send(ArReg.Commands.CreateClinicCmd)
IUnitOfWork.Commit()
at Moq.Mock.ThrowVerifyException(MethodCall expected, IEnumerable`1 setups, IEnumerable`1 actualCalls, Expression expression, Times times, Int32 callCount)
at Moq.Mock.VerifyCalls(Interceptor targetInterceptor, MethodCall expected, Expression expression, Times times)
at Moq.Mock.Verify[T](Mock mock, Expression`1 expression, Times times, String failMessage)
at Moq.Mock`1.Verify(Expression`1 expression, Times times)
Repositories\when_creating_new_clinic.cs(51,0): at ArReg.Tests.Specs.Repositories.when_creating_new_clinic.<.ctor>b__4()
at Machine.Specifications.Model.Specification.InvokeSpecificationField()
at Machine.Specifications.Model.Specification.Verify()
0 passed, 1 failed, 0 skipped, took 3.58 seconds (Machine.Specifications 0.4.24-f7fb6b5).
The Send() command is declared in the IDomainCommandSender so how do I need to setup the test so that I can verify the correct call?
Thanks

Your setup of the bus-moq has a little mistake. It should be like this:
bus.Setup(b => b.Send(It.IsAny<CreateClinicCmd>()));
Reason: You wrote your setup with an instance of CreateClinicCmd created two code lines above. In your class under test ClinicModelRepository you create another instance of that class and call your bus mock. This call doesn't match the call you wrote in your setup.

Related

How to convert to Xunit using mocking

I have these two methods in my service class
public class PatientService : IPatientService
{
private readonly IRestClient _restClient;
private readonly IAppSettings _appSettings;
public PatientService(IRestClient restClient, IAppSettings appSettings)
{
_restClient = restClient;
_appSettings = appSettings;
}
public async Task<IList<PatientViewModel>> GetPatients(int wardId)
{
var url = _appSettings.Server + _appSettings.PatientServiceEndPoint + wardId;
var token = _appSettings.Token;
return GetPatientList(await _restClient.GetAsync<List<PatientInfo>>(url, token));
}
public IList<PatientViewModel> GetPatientList(IList<PatientInfo> patientInfoList)
{
return patientInfoList.Select(p => new PatientViewModel(p)).ToList();
}
}
I need to add this code to my Xunit.cs. How to do it?
I've implemented this and I do not know how to proceed.
private readonly PatientListPageViewModel _patientListPageViewModel;
private readonly Mock<IPatientService> _patient;
public PatientServiceTests()
{
_patient = new Mock<IPatientService>();
_patientListPageViewModel = new PatientListPageViewModel(_patient.Object);
}
[Fact]
public void GetListByWard_PassingWardId_GetPatientsCountAccordingToWardId()
{
}
This is what I tried to do. How to convert those two methods in service to be testable?
You did get mocking a bit wrong. It is not the component under test that is mocked, but its dependencies. When unit-testing you'd like to test a unit in isolation. Your case of mocking would be kind of correct if you unit-tested the PatientListPageViewModel, but since your test class is named PatientServiceTests I assume that you really wanted to test PatientService. If you wanted to test the former, you would be quite right to mock IPatientService, but when testing PatientService, IRestClient and IAppSettings shall be mocked
public PatientServiceTests()
{
_restClientMock = new Mock<IRestClient>();
_appSettingsMock = new Mock<IAppSettings>();
_patientService = new PatientService(_restClientMock.Object, _appSettingsMock.Object);
}
And your test could be something like
[Fact]
public async Task ReturnsCorrectPatientList() // async supported as of xUnit 1.9
{
// set up the mock
_restClientMock.SetUp(restClient => restClient.GetAsync<List<Patient>>(It.IsAny<string>(), It.IsAny<string>())
.Returns(() => Task.FromResult(/* what patients it shall return */));
var result = await _patientService.GetPatients(0);
// compare whether the returned result matches your expectations
}
If you wanted to test whether the URL is formed correctly, you could use Verify
[Theory]
[InlineData("SERVER", "ENDPOINT", 12, "1234", "SERVERENDPOINT12")]
[InlineData("https://localhost:65000", "/patients/", 5, https://localhost:65000/patients/5")]
public void TestWhetherCorrectUrlIsCalled(string server, string endpoint, int wardId, string token, string expectedUrl)
{
_appSettingsMock.SetupGet(appSettings => appSettings.Server).Returns(server);
_appSettingsMock.SetupGet(appSettings => appSettings.PatientServiceEndPoint).Returns(endpoint);
_appSettingsMock.SetupGet(appSettings => appSettings.Token).Returns(token);
_restClientMock.SetUp(restClient => restClient.GetAsync<List<Patient>>(It.IsAny<string>(), It.IsAny<string>())
.Returns(() => Task.FromResult(new List<Patient>()));
// we do not need the result
await _patientService.GetPatients(wardId);
_restClientMock.Verify(restClient => restClient.GetAsync<List<Patient>>(exptectedUrl, token), Times.Once);
}
We are setting up the IRestClient in this case, since it would return null otherwise. And await null would cause your test to fail. After GetPatients has been called we are using Verify to verify that GetAsync has been called with the correct parameters. If it has not been called, Verify will throw and your test will fail. Times.Once means, that GetAsync shall have been called once and only once.
On a side note: Viewmodels shall have a meaning in the context of your user interface only. Services shall be independent and hence not return viewmodels, as you did, but POCOs (or maybe domain models). In this case the interface of your service should be
public interface IPatientService
{
public async Task<IList<Patient>> GetPatients(int wardId);
// ...
}

in API, create multiple controller constructor with one parameter

[Route("api/[controller]")]
public class DigitalDocumentController : Controller
{
private IDigitalDocumentService digitalDocumentService;
private IDatabaseInitializer databaseInitializer;
public DigitalDocumentController(IDigitalDocumentService digitalDocumentService)
{
this.digitalDocumentService = digitalDocumentService;
}
public DigitalDocumentController(IDatabaseInitializer databaseInitializer)
{
this.databaseInitializer = databaseInitializer;
}
i want two controller constructor in my project to Mock in xUnit Testing, but there was an error in my swagger interface {
"error": "Multiple constructors accepting all given argument types have been found in type 'i2ana.Web.Controllers.DigitalDocumentController'. There should only be one applicable constructor."
}
can anybody help me how i can do it ?
…
what i am try to do , is to test Uniquness of the Name Field in my database
My testing code:
[Fact]
public void AddNotUniqueName_ReturnsNotFoundObjectResult()
{
var digitalDocument = new DigitalDocument
{
Image = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 },
CreatedOn = DateTime.Today,
Id = 6,
Location = "temp",
Name = "Flower",
Tages = new List<Tag> { new Tag { Id = 1, Value = "Tag 1" }, new Tag { Id = 1, Value = "Tag 2" } }
};
// Arrange
var mockRepo = new Mock<IDatabaseInitializer>();
mockRepo.Setup(repo => repo.SeedAsync()).Returns(Task.FromResult(AddUniqueDigitalDocument(digitalDocument)));
var controller = new DigitalDocumentController(mockRepo.Object);
// Act
var result = controller.Add(digitalDocument);
// Assert
var viewResult = Assert.IsType<NotFoundObjectResult>(result);
var model = Assert.IsAssignableFrom<int>(viewResult.Value);
Assert.NotEqual(6, model);
}
the "AddUniqueDigitalDocument" returns 6 only to test that the new digitaldocumet is not the same id of my initialize data.
When using dependency injection, you should only have one constructor where all dependencies can be satisfied. Otherwise, how is the DI container to know which constructor to utilize? That's your issue here. Using the Microsoft.Extensions.DependencyInjection package, and since this is a controller you're injecting into, there's only one reasonable way to solve this: don't register one or the other of the services, IDigitalDocumentService or IDatatabaseInitializer. If only one is registered, the service collection will simply use the constructor it has a registered service for.
It's possible with a more featured DI container, you might be able to configure something to allow it choose the proper constructor. How to do that would be entirely dependent on the DI container you end up going with, though, so not much more can be said on the subject at this point. Just realize that the default container (Microsoft.Extensions.DependencyInjection) is intentionally simplistic, so if you needs are more complex, you should sub in a full DI container.
UPDATE
You should be doing integration testing with the test host and an in-memory database. The basic approach is:
public MyTests()
{
_server = new TestServer(new WebHostBuilder().UseStartup<TestStartup>());
_context = _server.Host.Services.GetRequiredService<MyContext>();
_client = _server.CreateClient();
}
In your app's Startup, create a virtual method:
public virtual void ConfigureDatabase(IServiceCollection services)
{
// normal database setup here, e.g.
services.AddDbContext<MyContext>(o =>
o.UseSqlServer(Configuration.GetConnectionString("Foo")));
}
Then, in ConfigureServices, replace your database setup with a call to this method.
Finally, in your test project, create a TestStartup class and override the ConfigureDatabase method:
public class TestStartup : Startup
{
public override void ConfigureDatabase(IServiceCollection services)
{
var databaseName = Guid.NewGuid().ToString();
services.AddDbContext<MyContext>(o =>
o.UseInMemoryDatabase(databaseName));
}
}
Now, in your tests you just make requests against the test client (which is just an HttpClient instance, so it works like any other HttpClient). You start by setting up your database with appropriate test data, and then ensure that the correct response is returned:
// Arrange
_context.Add(new DigitalDocument { Name = "Foo" });
await _context.SaveChanges();
// Act
// Submit a `DigitalDocument` with the same name via `_client`
// Assert
// Inspect the response body for some indication that it was considered invalid. Or you could simply assert that no new `DigitalDocument` was created by querying `_context` (or both)
This is admittedly a lot easier with an API, as with a web application, you're going to invariably need to do some HTML parsing. However, the docs and corresponding sample app help you with that.
Additionally, in actual practice, you'd want to use a test fixture to prevent having to bootstrap a test server for every test. Again, the docs have you covered there. One thing to note, though, is that once you switch to using a fixture, your database will then be persisted between tests. To segregate your test data, make sure that you call EnsureDeleted() on your context before each test. This can be easily done in the test class' constructor:
public class MyTests : IClassFixture<WebApplicationFactory<Startup>>
{
private readonly HttpClient _client;
private readonly MyContext _context;
public MyTests(WebApplicationFactory<Startup> factory)
{
factory = factory.WithWebHostBuilder(builder => builder.UseStartup<TestStartup>());
_client = factory.CreateClient();
_context = factory.Server.Host.Services.GetRequiredService<MyContext>();
_context.EnsureDeleted();
}
I don't even like this much bootstrapping code in my tests, though, so I usually inherit from a fixture class instead:
public class TestServerFixture : IClassFixture<WebApplicationFactory<Startup>>
{
protected readonly HttpClient _client;
protected readonly MyContext _context;
public TestServerFixture(WebApplicationFactory<Startup> factory)
{
factory = factory.WithWebHostBuilder(builder => builder.UseStartup<TestStartup>());
_client = factory.CreateClient();
_context = factory.Server.Host.Services.GetRequiredService<MyContext>();
_context.EnsureDeleted();
}
}
Then, for each test class:
public class MyTests : TestServerFixture
{
public MyTests(WebApplicationFactory<Startup> factory)
: base(factory)
{
}
This may seem like a lot, but most of it is one-time setup. Then, your tests will be much more accurate, more robust, and even easier in many ways.

Mock logger giving me error for ASP.NET Core

I was trying to verify whether my log warning message is written via NUnit mocking. I am getting this error message :
An exception of type 'System.NotSupportedException' occurred in Moq.dll but was not handled in user code
Additional information: Invalid verify on a non-virtual (overridable in VB) member: m => m.LogWarning(String.Format("comments not found for part number :{0}", (Object)0), new[] { "111" })
code:
mockLogger.Verify(m => m.LogWarning($"comments not found for part number :{0}", "111"), Times.Exactly(1));
This is happening because NUnit mocking framework does not support extension methods. A few people on stack overflow have suggested to use Log method instead of level wise methods.
What am I missing?
Firstly, you don't need the $ at the start of the string. That's for string interpolation. The LogWarning message is doing a string.format, hence the {0}
Mock frameworks cannot directly mock static methods. The problem in your case is the LogWarning method - that is the static (extension) method.
The simplest way of overcoming this issue is by using a wrapper class. Here's how I got it, in your case.
Firstly I created an interface
public interface IMyLogWarning
{
void LogWarning(string msg, params object[] args);
}
Then I created a class which implements that interface
public class MyLogWarning<T> : IMyLogWarning where T : class
{
private readonly ILogger _logger;
public MyLogWarning(ILogger<T> logger)
{
// Using constructor for DI
_logger = logger;
}
public void LogWarning(string msg, params object[] args)
{
_logger.LogWarning(msg, args);
}
}
The reason for these two is that I'll use these in my code as well as the unit test.
The constructor in the class is setup so it can be populated using dependency injection, something like this in your ConfigureServices method. Feel free to change this; was a quick stab at it on my part.
services.AddTransient<IMyLogWarning, MyLogWarning<MyViewModel>>();
You can then create a unit test that's roughly like this
[Test]
public void LoggingTest_LogAMessage_ConfirmedLogWasRun()
{
// TODO - add the rest of your test code
// Arrange
var warningMsg = "comments not found for part number :{0}";
var partNumber = "111";
var mockLogger = new Mock<IMyLogWarning>();
// Act
mockLogger.Object.LogWarning(warningMsg, partNumber);
// Assert
mockLogger.Verify(m => m.LogWarning(warningMsg, partNumber), Times.Exactly(1));
}

Moq: setting up for a method which returns no value

I'm trying to mock out a call to a repository. I can successfully do so when a repository call returns a value by using Setup().Returns:
mock.Setup(m => m.Get(param)).Returns(new CustomObject());
However, when I try to do the same sort of Setup for repository calls which return no values, Moq throws an exception and tells me this method was never called i.e.Expected invocation on the mock exactly 1 times, but was 0 times
Precisely, I'm doing this:
mock.Setup(m => m.UpdateRepository(param1)); // UpdateRepository returns no value
service.DoUpdate(param1);
mock.Verify(m => m.UpdateRepository(param1), Times.Exactly(1));
Note: DoUpdate method only calls repository.UpdateRepository(param1);
Am I not using Moq setup correctly in this instance? Is there a different way to Setup methods which return no value?
Thanks in advance!
You don't need to setup the call to UpdateRepository. Just verify it.
Given these types:
public interface IRepository
{
void UpdateRepository(string value);
}
public class Service
{
public Service(IRepository repository)
{
_repository = repository;
}
public void DoUpdate(string value)
{
_repository.UpdateRepository(value);
}
private IRepository _repository;
}
Your test method could be as follows:
const string param1 = "whatever";
var repoMock = new Mock<IRepository>();
var sut = new Service(repoMock.Object);
sut.DoUpdate(param1);
repoMock.Verify(x => x.UpdateRepository(param1), Times.Once());
Try using Verifiable:
mock.Setup(m => m.UpdateRepository(param1)).Verifiable();

Moq Verify not checking if a method was called

Hi I am getting an error and I don't understand why
[SetUp]
public void Setup()
{
visitService = new Mock<IVisitService>();
visitRepository = new Mock<IVisitRepository>();
visitUIService = new VisitUIService(visitRepository.Object, visitService.Object);
}
[Test]
public void VisitUIService_CanSoftDelete()
{
Mock<IVisitEntity> mockVisitEntity = new Mock<IVisitEntity>();
visitService = new Mock<IVisitService>();
visitRepository.Setup(x => x.GetVisitsByDocumentLineItems(It.IsAny<IEnumerable<int>>())).Returns(new List<IVisitEntity>() { mockVisitEntity.Object});
visitUIService.DeleteVisits(new VisitDeletionModel());
visitService.Verify(x => x.SoftDeleteVisit(It.IsAny<IVisitEntity>()),Times.AtLeastOnce());
}
Invocation was not performed on the mock: x => x.SoftDeleteVisit(IsAny())
I can't fix this I added visitService.Setup(x => x.SoftDeleteVisit(mockVisitEntity.Object)).Verifiable(); and a few other variations of the parameters but no luck
thank you
I think the problem is the consuming object visitUIService is already been initialized with the intial mocked interfaces and the setup that you are doing later is not useful.
Two approaches:
a) move the initialization of the class to the test i.e after the interface is setup
b) Lazy Load the mocks as follows, but you need to modify your class for the same using Func or Lazy. I will show it using Func
visitUIService = new VisitUIService(()=>visitRepository.Object, ()=>visitService.Object);

Resources