I wrote a unit test thats failing:
[Test]
public async Task GetLogsPaged_Account_ExpectsSuccess()
{
//Arrange
var request = new Mock<HttpRequest>();
request.Setup(x => x.Scheme).Returns("https");
request.Setup(x => x.Host).Returns(HostString.FromUriComponent("https://localhost:5001"));
request.Setup(x => x.PathBase).Returns(PathString.FromUriComponent("/v1/customersupport-manager/logs/account/D4C88E3C-2848-400F-AB66-0DC3FAFFD24A?PageNumber=1&PageSize=5&DateFrom=2021-09-30%2012%3A30%3A13.413&DateTo=2021-09-30%2012%3A33%3A05.317"));
List<LogEntry> logEntries = new List<LogEntry>() { new LogEntry { Id = 1 }, new LogEntry { Id = 2 } };
PaginationFilter paginationFilter = new PaginationFilter { };
LogEntryListFilter logEntryListFilter = new LogEntryListFilter { };
var accountId = Guid.NewGuid();
LogEntryPageResult logs = new LogEntryPageResult() { PagedRecords = logEntries };
A.CallTo(() => logRepo.GetLogs(A<Guid>._, A<PaginationFilter>._, A<LogEntryListFilter>._)).Returns(logs);
//Act
var result = await svc.GetLogs(accountId, request.Object, paginationFilter, logEntryListFilter);
//Assert
result.ApplicationEvents[0].Code.Should().Be(ApplicationResponseCodes.System.OperationSucceed);
}
When I debug the test I get a exception that says - {"Object reference not set to an instance of an object."} System.Exception {System.NullReferenceException}.
Which can only be var request because it's mocked. I'm not sure why I'm getting this exception when I've seen HttpRequest being mocked in other tests. Any assistance is appreciated.
Edit: I'm including the the line that fails in my code
var uri = new Uri(request.GetDisplayUrl()); <- System.NullReference
But I have the url specified in my tests :
request.Setup(x => x.Scheme).Returns("https");
request.Setup(x => x.Host).Returns(HostString.FromUriComponent("https://localhost:5001"));
request.Setup(x => x.PathBase).Returns(PathString.FromUriComponent("/v1/customersupport-manager/logs/account/D4C88E3C-2848-400F-AB66-0DC3FAFFD24A?PageNumber=1&PageSize=5"));
I have the test below and am using standard mocking on a DbSet/Context. When the test runs it fails as it states that "The source IQueryable doesn't implement IAsyncEnumerable Team. Only sources that implement IAsyncEnumerable can be used for Entity Framework asynchronous operations".
public async Task Get_team_name_with_valid_search_term_returns_team_names()
{
// Arrange
var data = new List<Team>
{
new Team {Name = "Leeds"},
new Team {Name = "Glasgow"}
}.AsQueryable();
var mockSet = new Mock<DbSet<Team>>();
mockSet.As<IQueryable<Team>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<Team>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<Team>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<Team>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
var mockContext = new Mock<RadContext>();
mockContext.Setup(c => c.Team).Returns(mockSet.Object);
var service = new ITeamSearchService(mockContext.Object);
// Act
var result = await service.GetTeamName("Gla");
// Assert
}
The service itself is quite simple
public async Task<List<SearchTeamResponse>> GetTeamName(string searchTerm)
{
if (searchTerm == null)
{
throw new ArgumentNullException(nameof(searchTerm));
}
var query = await _radContext.Team.Where(x => x.Name.StartsWith(searchTerm))
.OrderBy(x => x.Name)
.ToListAsync();
var json = JsonConvert.SerializeObject(query);
var result = JsonConvert.DeserializeObject<List<SearchTeamResponse>>(json);
return result;
}
In the following code. The Assert.Equal(...) of the Callback() is never called?
var test = "Test";
var command = new MyCommand { V = test };
var mock = new Mock<IRepository>(); // IRepository has the method of Save()
var p = new P(test);
mock.Setup(x => x.Save(p))
.Callback<P>(x => Assert.Equal(x.Value, test)); // break point on Assert.Equal not hit
var sut = new C(mock.Object);
var result = await sut.M(command);
You have:
.Setup(x => x.Save(p))
but are you sure the P used in your SUT is "equal to" just that p? Instead you could do:
.Setup(x => x.Save(It.IsAny<P>()))
and in that case the set-up (and call-back) would apply to any argument.
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.
I am mocking a function in c# using Moq.
public void Mapper_GetProductMappingTest()
{
//Arrange:
Mapping mapping= new Mapping()
{
code = "AB"
};
Mapper mapper = new Mapper(new MongoStore());
CaseProduct caseProduct = new CaseProduct()
{
ProductID = "ABC",
};
Mock<Mapper> mock = new Mock<Mapper>(new MongoStore());
mock.Setup(x => x.GetMapping(caseProduct)).Returns(mapping);
// why does it return the caseproduct not the mapping?!
var mapped = mock.Object.GetMapping(caseProduct);
Assert.IsTrue(mapped.code == "AB");
This Assert.IsTrue is failed and the mock.Object.GetMapping(caseProduct) returns ABC insteadof AB.
Can somebody help me with that?