All Questions
527 questions
0
votes
0
answers
25
views
Moq verify property init
How do i verify an init-call with Moq? I have the following property defined in an interface:
public string Text { init; }
I want to verify that init was called with a specific parameter. Is that ...
1
vote
0
answers
15
views
Is there a way to flag which class-level Moq setups are never called?
We've been using xUnit and Moq for our (C#) unit tests for nearly 10 years. Over that time, as you can imagine, our code has changed an awful lot, and one of the results is that we now have a whole ...
2
votes
1
answer
46
views
Execution of interface-defined programs in C# test code
I am writing test code with xUnit and mock(moq) on C#.
However, the program through the interface cannot be executed.
The test code is as follows.
// test code
public void test1(string id, EntityA ...
2
votes
1
answer
46
views
Test case fails
When executing test case I'm getting this error:
Message: Moq.MockException:
Expected invocation on the mock once, but was 0 times: m => m.Map(AnnotationMasterRequest)
Performed invocations:...
0
votes
2
answers
28
views
Initializing internal variables with Moq in a unit test
I am trying to create a unit test for a controller that returns a status code based on a call from a service. Since the test doesn't actually call the service the control flow throws a null reference ...
0
votes
0
answers
20
views
Changing response of Moq ReturnsAsync [duplicate]
I'm trying to mock a singleton which will reuse an HttpClient in each test, due to the static nature of it's internal values.
In each xUnit test, I am attempting to reset the response value, like this:...
3
votes
1
answer
93
views
How can I simulate asynchronous LINQ queries with conditional logic in xUnit?
I'm writing unit tests for a service, and I need to simulate a more complex LINQ query that includes conditional logic and asynchronous methods, such as FirstOrDefaultAsync().
The query involves ...
1
vote
1
answer
71
views
Expected invocation on the mock once, but was 0 times: With Moq
I am getting an error
Moq.MockException :
Expected invocation on the mock once, but was 0 times: m => m.Position = Vector
Performed invocations:
Mock<IMove:1> (m):
IMove.Position
...
1
vote
2
answers
78
views
Error when testing xUnit inserting a user into the database
I'm new to writing unit testing
I'm trying to write a unit test for inserting a user into a database but I'm getting an error
Error: System.NotSupportedException : Type to mock (SqlConnection) must be ...
0
votes
1
answer
33
views
Xunit Snaphooter tests return different values when running and debuging
I am using .NET 8.0 for my test project with Xunit, Snaphooter and Moq NuGet packages.
I have noticed that then running my tests the pass but when I start them via Debug I get a failed result.
How can ...
0
votes
0
answers
31
views
Refernce to RouteValueDictionary claims it is defined in System.Web but could not be found
I am currently learning to unit test in ASP.NET MVC, and I have encountered an issue while working on my Controller Test class. The error message states, "Reference to RouteValueDictionary claims ...
1
vote
1
answer
93
views
xUnit test throws TypeInitializationException
I have an xUnit test project within a net8.0 Maui solution. All projects in the solution are targeting the same Windows versions (Mac and Android excluded)
I have set up the following test to check ...
1
vote
1
answer
30
views
Xunit verify is not working in a mocked logger
I have the following code,
namespace MarketData.Service.Diagnostics
{
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Extensions.Logging;
public ...
0
votes
0
answers
92
views
How to mock an object created inside a function
I would like to create unit test for my C# application. There are the functions which create objects inside and perform some checks on the created object. Since I want it to be unit test, functions ...
1
vote
1
answer
77
views
PnP.Core - Mock of IFolderCollection failing
I need to mock a sharepoint document library returning a list of 6 files. This is the logic I am using to create a mock system.
public class SharePointDocLibraryUtilsTestFactory
{
private Mock<...
0
votes
1
answer
46
views
How to mock a configfile
I need to test a function which uses CSVHelper
{
private readonly CsvConfiguration _csvConfig;
public CsvWriterService(CsvConfiguration csvConfig)
{
_csvConfig = csvConfig;
...
2
votes
2
answers
60
views
xunit and mock returns null instead of string
I'm having an xUnit.net and Moq test problem, I have mocked my dependencies for my controller and setup the mock to return a Task<string> but my response.Value is null here. Can someone help ...
0
votes
0
answers
61
views
How to mock a Generics<T> class that actually used to fetch data from database
I have a Base class where i can find different generic methods like
public class EntityRepositoryBase<T> : IDisposable, IEntityRepository<T> where T : class
{
//Context is application ...
1
vote
1
answer
478
views
AutoFixture is unable to create an instance of a class that has a property of type RestSharp.RestResponse
I am attempting to use AutoFixture to create instances of a class with dummy values for use in my unit-tests. One class in particular is giving me trouble, and it is a class that has a property of the ...
0
votes
1
answer
113
views
Xunit testing restsharp with Moq
I'm trying to test my class (se below) in xunit that is supposed to connect to an API and get all customers , the response I paginated. I don't have access to the API how can I mock this in Xunit, I'm ...
0
votes
0
answers
73
views
How can I test function with prism event aggregator subscripe inside?
I use Xunit and Moq to test my application.
I am new at this topic...
Is it possible to test the method DBConnector(...) ?
And if yes, how?
I try it with mock... but the following line causes problems:...
0
votes
1
answer
122
views
C# Asp.Net MVC Core - Unit testing ErrorController using RouteData() in XUnit (&Moq) [closed]
I have an ErrorController:
public class ErrorController : Controller
{
private readonly ILogger<ErrorController> _logger;
public ErrorController(ILogger<ErrorController> logger)
{
...
0
votes
1
answer
89
views
How to test this method using XUnit and Moq?
[HttpPost("GetRefusalPdf")]
public async Task<IActionResult> GetRefusalPdf([FromBody] DispatchRefusal? refusal)
{
if (refusal == null) return StatusCode(StatusCodes....
0
votes
1
answer
427
views
Mocking EF extension method using mockablequery.moq - Does not work
I have the following unit test that needs to mock the EF extension method .ToListAsync with moq. Since moq can't mock static methods and since extension methods are static methods I resorted to use ...
0
votes
1
answer
589
views
Mocking internal class without interface
I am trying to mock internal class for unit tests, due to some circular dependency I will not be able to use interface of this class to mock it, I also added unit test assembly name (made sure I am ...
0
votes
1
answer
101
views
Unable to mock Queue object (in C#)
I am trying to mock a Queue Object (using MOQ framework) but getting the following error,
System.NotSupportedException: 'Unsupported expression: x => x.Enqueue(It.IsAny())
Non-overridable members (...
1
vote
1
answer
96
views
KeyNotFoundException when trying to access mocked object in dictionary
My mock test is throwing a KeyNotFoundException:
[Fact]
public void MockAssembly_GetTypes_ReturnsMockedTypes()
{
var mockAssembly = new Mock<Assembly>();
mockAssembly.Setup(a => a....
2
votes
1
answer
892
views
How to do Unit Testing for a controller structured upon Clean Architecture and CQRS?
I have a Product API for which I mean to do Unit Testing via xUnit.net and Moq. I'm totally new to Unit Testing btw. I've seen a couple of videos on Unit Testing for controllers via Repository pattern,...
1
vote
1
answer
297
views
How to Unit Test Delete operation using moq and xUnit?
I'm trying to Unit Test CRUD operations for an API in my WEB API project. I have a hard time figuring out how to do that for DELETE. Below is my service;
public async Task DeleteCompany(int id)
{
...
1
vote
1
answer
2k
views
Mock of `HttpMessageHandler` did not return a response message in xunit
I am using Moq package for writing unit test for my service.
I am mocking HttpMessageHandler for mock HttpClient
but I got this runt time error message
System.InvalidOperationException : Handler did ...
1
vote
1
answer
234
views
How to use a Mock in xunit passing a mapped entity
I'm trying to create an unit test using moq on xunit, but the test is failing, I guest is because of the mapper, when the _sut.Create is called it's thrown an exception, if I remove MockBehavior....
0
votes
1
answer
172
views
How can I mock IotHubServiceClient for testing purposes? (v2)
I have a class IotHubService that depends on the C# IoTHub SDK's IotHubServiceClient (v2 version of the SDK, currently in preview) to perform various queries on an IoTHub. I'm trying to improve the ...
0
votes
0
answers
82
views
How to mock a static Sitecore method?
we have a static Sitecore method which is called when we fire the test we need to mock the method result, means when its called it should return our mocked result and shouldn't enter into that method.
...
1
vote
1
answer
59
views
Testing a function without a parameter and using moq and xunit
I'm trying to write a unit test for a function:
public async Task<IEnumerable<Person>> GetPerson()
{
var query = "SELECT * FROM Person";
using (var connection = _context....
0
votes
1
answer
34
views
Xunit For Attach in EF causing null reference exception
I am trying to write xUnit for my update service, but I get a null reference exception
public bool Update(string Id, CreateUpdateUserDto InP)
{
var user = new UserDetails
{
...
0
votes
0
answers
117
views
How to Mock Command Handler to return the success Response Code in Xunit Moq?
I am unit testing in Xunit, using Moq for mocking
I am following CQRS pattern, The class being tested looks like this
{
public class command : IRequest<VehicleListingResponse>, IReqTransaction
{
...
2
votes
1
answer
240
views
Mocking Method Which Returns Guid With .Moq
I am using clean architecture and creating tests for my Application layer. My problem is that the test case fails because of _movieRepository.CreateAsync() returns an empty Guid which is "...
1
vote
0
answers
271
views
Unit testing with Moq - Manipulate Ref Parameter
I'm writing Unit Tests in the xUnit Framework and have the scenario that i like to handle and manipulate a ref Parameter.
My code so far:
public interface IBar
{
public void ManipulateRefParam(ref ...
1
vote
1
answer
71
views
Getting an invocation error while unit testing the method
I have the handler method below where I am testing for invalid name exception.
....
namespace SchemaModeler.Host.Modules;
........
public class CreateWorkspaceHandler : IRequestHandler<...
0
votes
0
answers
146
views
Not able to grab value for a key when using Moq on IMemoryCache
This is the Service that i am mocking so i am looking to test GetTaskModel where if i create an entry into the mocked memory cache using CreateEntry. That entry can be found by GetTaskModel which is ...
0
votes
1
answer
793
views
Entity Framework with Moq: DbSet.Add not working in Unit Test
I'm new to EF and I've run into a hurdle. I'm currently testing a method using Moq and Xunit that adds an object to the database. The method works when I try it with the regular database, but with the ...
0
votes
0
answers
104
views
Xunit and MOQ: How to moq a generic function which returns a list
I'm using .net 3.1 core, MOQ and Xunit. Working with uow and repository.
I have a function in a generic repository(see below). How can i moq Getitems to return a List?
Method in generic Repo:
public ...
0
votes
1
answer
761
views
Testing a repository pattern using xUnit and Moq returning: System.NullReferenceException : Object reference not set to an instance of an object
I'm learning how to unit test ASP.NET Core web applications by reading the docs and tutorials, but not progressing too much because the docs looks kinda silly to me. I'm following the right path?
I ...
1
vote
0
answers
323
views
Unit Test for Handler Method
Details:
I Have tried a few different solutions, i don't use an interface as it is unnecessary for the service, I also have a few other methods for creating and retrieving/ updating. The error im ...
0
votes
2
answers
281
views
How to unit test a method that returns class and input as object with linq using moq/autofixture
I want to unit test GetFooInfo method of a Foo service class that returns FooDto object and takes input FooInput object using Xunit/Moq/AutoFixture. I'm using C#, EF core with DB First approach.
...
1
vote
0
answers
78
views
Xunit: Moq Setup doesn't return expected value
I've implemented a service that sends sms to some devices by means of AWS SNS Service.
The service checks for each device if it exists in a whitelist table. If the device isn't found, the sms is sent ...
0
votes
1
answer
281
views
Returning value that was passed into a ReturnsAsync method
I need method CreateAsync to return what it receives (the same List<enteties>)
Task<IEnumerable<Entity>> CreateAsync(IEnumerable<Entity> entities, CancellationToken? token = ...
0
votes
0
answers
261
views
How to mock MySqlConnection related method and add test case using Moq
How to mock MySqlConnection related method and add test case using Moq.
Here is my code block, When i am trying to mock MySqlConnection it is showing error.
public class MySQLServerConnection
{
...
1
vote
1
answer
200
views
Moq Raise event of Func<T1, Task>
I have a third-party class MqttClient which has an event inside it (Func<T1, Task>). I want to listen for this event inside the MyClient class and when it gets invoked, I update the property ...
0
votes
0
answers
26
views
Unable to pass mock verify
I trying to test this end point:
[HttpPost("Register")]
public async Task<ActionResult<UserDto>> RegisterUser([FromBody] RegisterDto registerDto)
{
_logger.Info($"...