I got this really cool Moq method that fakes out my GetService, looks like this
private Mock<IGetService<TEntity>> FakeGetServiceFactory<TEntity>(List<TEntity> fakeList) where TEntity : class, IPrimaryKey, new()
{
var mockGet = new Mock<IGetService<TEntity>>();
mockGet.Setup(mock => mock.GetAll()).Returns(fakeList);
mockGet.Setup(mock => mock.Get(It.IsAny<int>())).Returns((int i) => fakeList.Find(fake => fake.Id.ToString() == i.ToString()));
mockGet.Setup(mock => mock.Get(It.IsAny<Expression<Func<TEntity, bool>>>())).Returns((Expression<Func<TEntity, bool>> expression) => fakeList.AsQueryable().Where(expression));
return mockGet;
}
and to use this...
var fakeList = new List<Something>();
fakeList.Add(new Something { Whatever = "blah" });
//do this a buncha times
_mockGetService = FakeGetServiceFactory(fakeList);
_fakeGetServiceToInject = _mockGetService.Object;
How do I toss this into Rhino.Mock?
Something along these lines (sorry, I don't have VS handy, so I can't test it):
private IGetService<TEntity> FakeGetServiceFactory<TEntity>(List<TEntity> fakeList) where TEntity : class, IPrimaryKey, new()
{
var mockGet = MockRepository.GenerateMock<IGetService<TEntity>>();
mockGet.Expect(mock => mock.GetAll()).Return(fakeList);
mockGet.Expect(mock => mock.Get(Arg<int>.Is.Anything)).Do((int i) => fakeList.Find(fake => fake.Id.ToString() == i.ToString()));
mockGet.Expect(mock => mock.Get(Arg<Expression<Func<TEntity, bool>>>.Is.Anything)).Do((Expression<Func<TEntity, bool>> expression) => fakeList.AsQueryable().Where(expression));
return mockGet;
}
Related
I tried following code but it's give exceptions:
var mockIdsDbContext = new Mock<IdentityServerDbContext>();
var applicationUser = new ApplicationUser()
{
Id = Guid.NewGuid().ToString(),
Email = "shashikant0423#gmail.com",
PhoneNumber = "999999999"
};
var usersTestData = new List<ApplicationUser>() { applicationUser };
var users = MockDbSet(usersTestData);
mockIdsDbContext.Setup(x => x.Users).Returns(userManager.Object.Users);
Mock<DbSet<T>> MockDbSet<T>(IEnumerable<T> list) where T : class, new()
{
IQueryable<T> queryableList = list.AsQueryable();
Mock<DbSet<T>> dbSetMock = new Mock<DbSet<T>>();
dbSetMock.As<IQueryable<T>>().Setup(x => x.Provider).Returns(queryableList.Provider);
dbSetMock.As<IQueryable<T>>().Setup(x => x.Expression).Returns(queryableList.Expression);
dbSetMock.As<IQueryable<T>>().Setup(x => x.ElementType).Returns(queryableList.ElementType);
dbSetMock.As<IQueryable<T>>().Setup(x => x.GetEnumerator()).Returns(() => queryableList.GetEnumerator());
//dbSetMock.Setup(x => x.Create()).Returns(new T());
return dbSetMock;
}
but I got error like:
Can not instantiate proxy of class: RenewPlus.IdentityServer.Data.IdentityServerDbContext. Could not find a parameterless constructor
Instead of mocking the rather complex DbContext I'd recommend instead using the Microsoft.EntityFrameworkCore.InMemory driver.
https://learn.microsoft.com/en-us/ef/core/providers/in-memory/
I use NUnitAdapter. I have unit test for my update method:
[Test]
public void UpdateBuisness()
{
var buis = new Buisness()
{
Name = "a",
Id = 4,
Enabled = true
};
_buisnessRepository.Insert(buis);
buis.Name = "b";
_buisnessRepository.Update(buis);
Assert.AreEqual(buis.Name, _buisnesses.Last().Name);
}
Update method:
public void Update(Buisness entity)
{
_context.Entry(entity).State = EntityState.Modified;
}
And I get error:
This is weird, because for my co-workers all works.
My mock:
var mockBuisnessesDbSet = new Mock<DbSet<Buisness>>();
mockBuisnessesDbSet.As<IQueryable<Buisness>>().Setup(m => m.Provider)
.Returns(new TestDbAsyncQueryProvider<Buisness>(_buisnesses.Provider));
mockBuisnessesDbSet.As<IQueryable<Buisness>>().Setup(m => m.Expression).Returns(_buisnesses.Expression);
mockBuisnessesDbSet.As<IQueryable<Buisness>>().Setup(m => m.ElementType).Returns(_buisnesses.ElementType);
mockBuisnessesDbSet.As<IDbAsyncEnumerable<Buisness>>()
.Setup(m => m.GetAsyncEnumerator())
.Returns(new TestDbAsyncEnumerator<Buisness>(_buisnesses.GetEnumerator()));
mockBuisnessesDbSet.As<IQueryable<Buisness>>().Setup(m => m.GetEnumerator()).Returns(_buisnesses.GetEnumerator());
mockBuisnessesDbSet.Setup(x => x.Add(It.IsAny<Buisness>()))
.Callback((Buisness bis) => _buisnesses = _buisnesses.Concat(new[] { bis }));
mockBuisnessesDbSet.Setup(x => x.Remove(It.IsAny<Buisness>()))
.Callback((Buisness bis) => _buisnesses = _buisnesses.Where(x => x.Id != bis.Id));
_mockContex = new Mock<ApplicationDbContext>() { CallBase = true };
_mockContex.Setup(x => x.Buisnesses).Returns(mockBuisnessesDbSet.Object);
_buisnessRepository = new BuisnessRepository(_mockContex.Object);
I have no idea what is causing this.
I have a ReactiveList with view models with a 'Selected' property. When I try to set this property from a unit-test, the subscription on ReactiveList.ItemChanged is not invoked. It works, however, when running the application and triggering the 'Selected' property from a check-box in the UI. Is there anything magic I have to do to make ReactiveList.ItemChanged work in a unit-test environment? I am using ReactiveUI 6.5 by the way.
WellsViewModels = new ReactiveList<WellViewModel> { ChangeTrackingEnabled = true };
var selectedWellsObservable =
Observable.Merge(
this.WhenAnyValue(vm => vm.WellSamplesFunc)
.Select(_ => Enumerable.Empty<IPropertyModelingWell>()),
WellsViewModels
.ItemChanged
.Where(x => x.PropertyName == nameof(WellViewModel.Selected))
.Throttle(TimeSpan.FromMilliseconds(100), RxApp.MainThreadScheduler)
.Select(_ => WellsViewModels.Where(vm => vm.Selected)
.Select(vm => vm.Well).ToList())
)
.Publish()
.RefCount();
selectedWellsObservable
.Select(_ => ComputeAllCheckedState(WellsViewModels))
.Subscribe(b => CheckAllWells = b) // <--- This is never invoked when unit-testing!?!
[Test]
public void CheckAllWells_UpdatedWhenWellsViewModelsSelectionChanges()
{
new TestScheduler().With(scheduler =>
{
// Arrange
...
...
// Act
_viewModel.WellsViewModels[0].Selected = true;
scheduler.AdvanceBy(TimeSpan.FromMilliseconds(200).Ticks);
// Assert
Assert.IsFalse(_viewModel.CheckAllWells.HasValue);
});
}
I am getting a "System.Reflection.TargetParameterCountException: Parameter Count mismatch" exception when attempting to mock our ApiClient.
I am using the following code to Setup the Moq response
private void SetupApiClientForGetZones(IEnumerable<Zone> zone)
{
this.MockHubApiClient.Setup(x => x.GetAsync<IEnumerable<Zone>>(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>()))
.Returns(
(string name) =>
{
return zone == null ? Task.FromResult<IEnumerable<Zone>>(null) : Task.Run(() => zone);
});
this.MockApiClientFactory.Setup(x => x.CreateClient(It.IsAny<string>()))
.Returns(this.MockHubApiClient.Object);
}
The iApiClient interface I attempting to Mock is
public interface IApiClientAsync : IApiClient
{
Task<string> GetAsync(string apiController);
Task<T> GetAsync<T>(string apiController) where T : class;
Task<string> GetAsync(string apiController, IDictionary<string, string> param, string queryString);
Task<T> GetAsync<T>(string apiController, IDictionary<string, string> param) where T : class;
}
My unit test is
[Test]
public void GetZonesNotCached()
{
var data = new List<Zone> { new Zone { ZoneId = 1, ZoneName = "Test Zone 1" }, new Zone { ZoneId = 2, ZoneName = "Test Zone 2" } };
this.SetupApiClientForGetZones(data);
this.MockCache.Setup(x => x.GetItemFromCache<IEnumerable<Zone>>(It.IsAny<string>()));
var organisationService = new OrganisationService(this.MockUnitOfWorkAsync.Object, this.MockApiClientFactory.Object, this.MockCache.Object);
var results = organisationService.GetZones(1, 1).ToList();
Assert.IsNotNull(results);
Assert.AreEqual(3, results.Count, "There should be 3 records returned");
this.MockCache.Verify(x => x.GetItemFromCache<IEnumerable<Zone>>(It.IsAny<string>()), Times.Once());
this.MockHubApiClient.Verify(x => x.GetAsync<IEnumerable<Zone>>(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>()), Times.Once());
}
I have found numerous other posts with the same exception but none of the solutions or examples are the same as mine.
I have been able to successfully Mock the response when calling the GetAsync method that only has the single string paramter.
private void SetupApiClientForAllDealerDetails(IEnumerable<DealerDetail> dealerDetails)
{
this.MockHubApiClient.Setup(
x => x.GetAsync<IEnumerable<DealerDetail>>(It.IsAny<string>()))
.Returns(
(string name) =>
{
return dealerDetails == null ? Task.FromResult<IEnumerable<DealerDetail>>(null) : Task.Run(() => dealerDetails);
});
this.MockApiClientFactory.Setup(x => x.CreateClient(It.IsAny<string>()))
.Returns(this.MockHubApiClient.Object);
}
Any ideas anyone?
If you use an expression in your .Returns instead of a value, then that expression's parameters must match those of the method signature you are mocking.
For example, I found this in SetupApiClientForGetZones:
this.MockHubApiClient.Setup(x => x.GetAsync<IEnumerable<Zone>>(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>()))
.Returns(
(string name) =>
{
return zone == null ? Task.FromResult<IEnumerable<Zone>>(null) : Task.Run(() => zone);
});
When really it should be:
this.MockHubApiClient.Setup(x => x.GetAsync<IEnumerable<Zone>>(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>()))
.Returns<string, IDictionary<string, string>>(
(name, dict) =>
{
return zone == null ? Task.FromResult<IEnumerable<Zone>>(null) : Task.Run(() => zone);
});
I would like to mock a WebViewPage and compare the output with an expected result.
here are my mockhelpers I'm using
public static class MockHelpers
{
public static HttpContextBase MockHttpContext(NameValueCollection queryStringCollection = null)
{
var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
if(queryStringCollection != null)
SetupMockRequestQuerystringValues(request, queryStringCollection);
request.SetupGet(x => x.ApplicationPath).Returns("/");
request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/a", UriKind.Absolute));
request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());
var response = new Mock<HttpResponseBase>(MockBehavior.Strict);
response.Setup(x => x.ApplyAppPathModifier(Moq.It.IsAny<String>())).Returns((String url) => url);
// response.SetupGet(x => x.Cookies).Returns(new HttpCookieCollection()); // This also failed to work
var context = new Mock<HttpContextBase>(MockBehavior.Strict);
context.SetupGet(x => x.Request).Returns(request.Object);
context.SetupGet(x => x.Response).Returns(response.Object);
context.SetupGet(x => x.Response.Cookies).Returns(new HttpCookieCollection()); // still can't call the Clear() method
context.SetupGet(p => p.User.Identity.Name).Returns("blah");
context.SetupGet(p => p.User.Identity.IsAuthenticated).Returns(true);
return context.Object;
}
private static void SetupMockRequestQuerystringValues( Mock<HttpRequestBase> request, NameValueCollection queryStringCollection)
{
request.SetupGet(x => x.QueryString).Returns(queryStringCollection);
}
public static ViewContext MockViewContext()
{
return CreateSimpleGenericMock<ViewContext>();
}
public static T MockWebViewPage<T>() where T : WebViewPage
{
var mock = new Mock<T>(MockBehavior.Loose) { CallBase = true };
mock.SetupGet(x => x.Context).Returns(MockHttpContext());
mock.SetupGet(x => x.Layout).Returns("layoutName");
mock.SetupGet(x => x.VirtualPath).Returns("virtualPathName");
mock.SetupGet(x => x.Page).Returns(new object{});
mock.SetupGet(x => x.PageData).Returns(new Dictionary<object, dynamic>()
{
{new object(), new object()}
});
var page = mock.Object;
//var helper = new HtmlHelper<object>(new ViewContext { ViewData = CreateSimpleGenericMock<ViewDataDictionary>() }, page, CreateSimpleGenericMock<RouteCollection>());
var helper = new HtmlHelper<object>(new ViewContext { ViewData = new ViewDataDictionary() }, page, new RouteCollection());
page.ViewContext = MockViewContext();
page.Html = helper;
return page;
}
public static T CreateSimpleGenericMock<T>() where T : class
{
var mock = new Mock<T>();
return mock.Object;
}
}
In the MockWebViewPage method you can see all that I have faked. My test method looks like so
[TestMethod]
public void TestMethod1()
{
var coreMasterTestClass = MockHelpers.MockWebViewPage<CoreMaster<object>>();
coreMasterTestClass.ExecutePageHierarchy();
var output = coreMasterTestClass.Html;
}
Is it possible to test the output that will be generated with mocking, and if not does anyone have any possible clues how I could test this. Please note that I'm not testing actual chstml pages but core pages within our own framework.