I need to mock a method from the google calendar api. But it gives an error everytime. I have the following code.
DateTime dateTimeNow = new DateTime(2018, 10, 10, 10, 10, 10);
Event events = new Event
{
Id = "EventA",
Summary = "Summary",
Description = "Desc",
Start = new EventDateTime { Date = "2018-10-10", DateTime = dateTimeNow},
End = new EventDateTime { Date = "2018-10-10", DateTime = dateTimeNow.AddHours(1) },
};
Mock<CalendarService> fakeCalendarService = new Mock<CalendarService>();
fakeCalendarService
.Setup(x => x.Events.Insert(It.IsAny<Event>(), It.IsAny<string>()).Execute())
.Returns(events);
I get the following error message:
Message: System.NotSupportedException : Invalid setup on a non-virtual (overridable in VB) member: x => x.Events.Insert(It.IsAny<Event>(), It.IsAny<String>()).Execute()
I was able to mock other functions but this function:
_service.Events.Insert(newEvent, _calendarId).Execute();
has .Execute() behind it. Because of this statement I don't know how to mock it.
Related
Trying to create a unit test for the filter in the method. But the test failed due to I have no database. Trying to mock the database, so I can test that filter in the method. The database call test is separate from the integration test.
namespace Repository
public async Task<IEnumerable<ContractCollection>> GetContractsForUpdate(DateTime date)
{
var builder = Builders<ContractCollection>.Filter;
var filter = builder.Lte(x => x.StartDate, date) & builder.Gte(x => x.EndDate, date);
return await _db.GetCollection<ContractCollection>().FindSync(filter).ToListAsync();
}
These are parts of my test class, I use the packages(FluentAssertions 6.8.0, Moq 4.18.4). Also, try using ReturnsAsync. It fails due ContractCollection is null.
using FluentAssertions;
using MongoDB.Driver;
using Moq;
namespace Repository.UnitTests
public class RepositoryTests
{
private IRepositoryHelper _repositoryHelper;
private Mock<IRepositoryHelper> _mockRepositoryHelper;
private Repository _sut;
private Mock<IDb> _dbMock;
private readonly Mock<IMongoCollection<ContractCollection>> _collectionMock =
new Mock<IMongoCollection<ContractCollection>>();
protected override void OnTestInitialize()
{
base.OnTestInitialize();
_repositoryHelper = new RepositoryHelper();
_dbMock = new Mock<IDb>();
_mockRepositoryHelper = new Mock<IRepositoryHelper>();
_sut = new Repository(_dbMock.Object, _mockRepositoryHelper.Object);
}
[TestMethod]
public async Task TestGetContractsForUpdate_FilterAsync()
{
//Arrange
var date = new DateTime(2023, 1, 9);
var expectedFilter = Builders<ContractCollection>.Filter.Lte(x => x.StartDate, date)
& Builders<ContractCollection>.Filter.Gte(x => x.EndDate, date);
var expectedContracts = new[]
{
new ContractCollection { StartDate = new DateTime(2023, 1, 1), EndDate = new DateTime(2023, 1, 31) },
new ContractCollection { StartDate = new DateTime(2023, 2, 1), EndDate = new DateTime(2023, 2, 28) }
};
_dbMock.Setup(db => db.GetCollection<ContractCollection>(It.IsAny<string>())).Returns(_collectionMock.Object);
_collectionMock.Object.InsertMany(expectedContracts);
var projection = Builders<ContractCollection>.Projection.Include(x => x.StartDate).Include(x => x.EndDate);
var options = new FindOptions<ContractCollection, ContractCollection> { Projection = projection };
//Act, Assert
var enumerable = await _sut.GetContractsForUpdate(date);
_collectionMock.Verify(x => x.FindAsync(
It.Is<FilterDefinition<ContractCollection>>(f => f.ToString() == expectedFilter.ToString()),
options, It.IsAny<CancellationToken>()), Times.Once());
}
}
filter to be comparable against expectedFilter in the Unit test TestGetContractsForUpdate_FilterAsync
I have .dotnet core web application. I'm trying to add event by Google Calendar Api but getting error. The error
Google.Apis.Requests.RequestError Forbidden [403] Errors [
Message[Forbidden] Location[ - ] Reason[forbidden] Domain[global] ]
My code is
Event myEvent = new Event
{
Summary = "Appointment",
Location = "Dhaka",
Start = new EventDateTime()
{
DateTime = new DateTime(2018, 9, 17, 10, 0, 0),
TimeZone = "Asia/Dhaka"
},
End = new EventDateTime()
{
DateTime = new DateTime(2018, 9, 17, 10, 30, 0),
TimeZone = "Asia/Dhaka"
},
Recurrence = new String[] {
"RRULE:FREQ=WEEKLY;BYDAY=MO"
},
Attendees = new List<EventAttendee>()
{
new EventAttendee() { Email = "alimcu08#gmail.com" }
}
};
var newEventRequest = calendarService.Events.Insert(myEvent, calendarId);
var eventResult = newEventRequest.Execute();
It's getting error when execute run. By using same calendar service I had got calendar and event list successfully but can't adding event. Any one can help?
Google provided 3 calendars whose have different id. I provided one id from them. That's why event not added. When I replace id by 'primary' it's working fine.
I need help to create a new event inside Google calendar. I followed this link
and its working fine but now I need to add new event and delete event(existing/new) and I couldn't able to figure out how to add events. I tried this example to insert new events in calendar:link
but when i compile it gives me an error and here is the screen shot.
I will really appreciate help.
To add new event and send invite:
Event myEvent = new Event
{
Summary = "Discussion on new project",
Location = "Mentor",
Start = new EventDateTime()
{
DateTime = new DateTime(2018, 8, 16, 10, 0, 0),
TimeZone = "America/Los_Angeles"
},
End = new EventDateTime()
{
DateTime = new DateTime(2018, 8, 16, 11, 30, 0),
TimeZone = "America/Los_Angeles"
},
Recurrence = new String[] { "RRULE:FREQ=WEEKLY;BYDAY=MO"},
Attendees = new List<EventAttendee>()
{
new EventAttendee() { Email = "abc#gmail.com" }
}
};
var recurringEvent = service.Events.Insert(myEvent, "primary");
recurringEvent.SendNotifications = true;
recurringEvent.Execute();
I am using httppostfilebase in form which is present in my viewmodel as:
public HttpPostedFileBase details { get; set;}
My test is on service to repository and I want to test the Form data which is bonded with viewmodel, with fileupload. But, it throws this error:
The type initializer for 'Moq.Mock`1' threw an exception.
Below is the testing code:
public void TestMethod1()
{
var get = getservice();
VSettlement ne = new VSettlement();//vm
ne.name = " N LTD";
ne.Settle_date = new DateTime(2017, 4, 26);
ne.sAmount = 0;
ne.SPerct = 0;
ne.kCharges = 0;
ne.AAmount = 0;
ne.AmountReceived = 88500;
var file = new Mock<HttpPostedFileBase>();
file.Setup(x => x.FileName).Returns("NLTD-52.xlsx");
ne.details = file.Object;(httppostfilebase in viewmodel)
var server = new Mock<HttpServerUtilityBase>();
server.Setup(x => x.MapPath("~/trax.Tests")).Returns(#"C:\Users\Development Team\documents\visual studio 2015\Projects\trax.Tests");
var httpContext = new Mock<HttpContextBase>();
httpContext.Setup(x => x.Server).Returns(server.Object);
VReceipt pay = new VReceipt();//vm
pay.AccountID = 1032;
pay.Amount = 88500;
pay.PaymentDate=new DateTime(2017, 4, 26);
pay.PaymentModes = new SelectList("Cash");
pay.Accounts = new SelectList("CHENNAI CASH");
// act
int? s = 0;
var res= get.Add(ne, pay, 1012, out s);
Assert.IsTrue(res);
}
Please help me resolve it.
I'm running into an issue where Moq doesn't return what I excpect using following code:
[TestMethod]
public void GetResultReturnsAResult()
{
var mockUnitOfWork = Arrange();
// Arrange
var controller = new ResultsController(mockUnitOfWork.Object);
controller.Request = new HttpRequestMessage();
controller.Configuration = new HttpConfiguration();
// Act
var response = controller.GetResult(2);
// Assert
Assert.IsTrue(response is OkNegotiatedContentResult<Result>);
var contentResult = response as OkNegotiatedContentResult<Result>;
Assert.IsNotNull(contentResult);
Assert.IsNotNull(contentResult.Content);
Assert.IsTrue(contentResult.Content.ID == 2);
}
[TestMethod]
public void GetResultReturnsNotFound()
{
var mockUnitOfWork = Arrange();
// Arrange
var controller = new ResultsController(mockUnitOfWork.Object);
controller.Request = new HttpRequestMessage();
controller.Configuration = new HttpConfiguration();
// Act
var response = controller.GetResult(100);
// Assert
Assert.IsTrue(response is NotFoundResult);
var contentResult = response as NotFoundResult;
Assert.IsNotNull(contentResult);
}
private Mock<IUnitOfWork> Arrange()
{
var results = new List<Result>()
{
new Result()
{
ID = 1,
Name = "Result 1",
Modified = new DateTime(2017, 1, 1),
Created = new DateTime(2017, 1, 1),
CreatedBy = "Tester 1",
ModifiedBy = "Tester 2"
},
new Result()
{
ID = 2,
Name = "Result 2",
Modified = new DateTime(2017, 1, 2),
Created = new DateTime(2017, 1, 2),
CreatedBy = "Tester 1",
ModifiedBy = "Tester 2"
},
};
var mockUnitOfWork = new Mock<IUnitOfWork>();
var mockResultRepository = new Mock<IGenericRepository<Result>>();
mockResultRepository.Setup(x => x.Get(null, null, ""))
.Returns(results);
mockResultRepository.Setup(x => x.GetById(It.IsAny<int>()))
.Returns((int id) => GetById(results, id));
mockUnitOfWork.Setup(x => x.ResultRepository)
.Returns(mockResultRepository.Object);
return mockUnitOfWork;
}
private Result GetById(List<Result> results, int id)
{
return results.FirstOrDefault(r => r.ID == id);
}
In this case my TestMethods testing GetById both throw an exception with message: Object of type 'System.Object[]' cannot be converted to type 'System.Int32'.
When I change the mocking code to this:
mockResultRepository.Setup(x => x.Get(null, null, ""))
.Returns(results);
mockUnitOfWork.Setup(x => x.ResultRepository)
.Returns(mockResultRepository.Object);
mockUnitOfWork.Setup(x => x.ResultRepository.GetById(It.IsAny<int>()))
.Returns((int id) => GetById(results, id));
The GetById tests don't throw an exception but GetResultReturnsAResult doesn't return a result so it always fails.
Can anyone shed a light on this behaviour?
As suggested by Eugene Podskal in the comments, I was creating an MCVE (download here) and ran into the solution. He was in fact right that the solution was to be found in code that was not shared first.
The code that returned the
Object of type 'System.Object[]' cannot be converted to type 'System.Int32'
exception was correct in throwing this exception since
GetById
takes a
params object[]
as first parameter.