Questions tagged [moq]
Moq is a strongly typed and minimalistic mocking framework for .NET.
5,749
questions
0
votes
1
answer
42
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
20
views
With Moq in C#, how would you automate writing a MakeSut(out ...) method from any constructor?
Given any constructor of a class I want to test, such as:
public MyService(IFooStore store, IBarService service, IModeratelyLongDependencyName dependency3, ...)
{
...
}
Can you think of a good ...
1
vote
2
answers
32
views
Using a single Moq Setup to return multiple argument values
I have a Moq object and I need to return values for 4 different arguments. I can do it in 4 different statements but is there a way to achieve the same in a single Setup statement?
var parametersMock =...
0
votes
1
answer
74
views
Advice on Integration Testing for Azure CI/CD [closed]
API Project built using .Net 6
Currently writing unit tests for our API project.
I have just implemented Moq framework and used the Setup() function to test for exceptions
My question is, we will be ...
0
votes
0
answers
34
views
How to mock 'IsSuccessStatusCode' of HttpResponseMessage in C# [closed]
I have the following function for which I am trying to write unit test case:
public async Task<ActionResult<string>> GetHealthCheck()
{
var isApiSuccessStatusCode = false;
...
1
vote
1
answer
49
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....
0
votes
0
answers
42
views
How to mock static extension methods in Unit Test (c#) [duplicate]
I'm currently working on unit testing a .NET 6 project and facing a challenge with mocking static extension methods because I'm not allowed to refactor the code. I have a scenario where I need to mock ...
1
vote
1
answer
25
views
.net Mock a method that has a generic return type
I'm trying to Mock a method that has a generic return type that is implemented in an abstract class.
Abstract class code:
public abstract class AbstractRepository<T> where T : class
{
...
0
votes
0
answers
49
views
Why doesn't [FromQuery] work when unit testing a Razor page?
I have this property in a PageModel:
[FromQuery(Name = "paypalPlanId")] public string? paypalPlanId { get; set; }
It works when calling the page within the application - the property is set ...
1
vote
1
answer
42
views
How to mock a task from a dependency called from an external consumer
I'm a newbie in mocking and was asked to build some unit tests for a method, what I understood so far is that one dependency of this class (where the method to be tested is located) waits for a ...
0
votes
1
answer
35
views
Unit of Work has null repository property in Unit Test
I cannot run a unit test from the BLL/Service layer. The test mocks the Unit of Work because its a unit test for a service method. Thus, the uow mock has a null repository property which fails the ...
2
votes
1
answer
49
views
Controller ViewResult returns empty Model collection while doing Unit test using xUnit and Mock
When i debugging the controller index method it returns an empty model where I do mistake?
I am using Moq by Daniel Cazzulino and xUnit
Following is my controller code:
TeacherController:
public class ...
2
votes
1
answer
45
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
45
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)
{
...
0
votes
1
answer
29
views
How to mock a Sequence with a GUID Parameter using moq C#
I have the following concrete code:
var allBookedPos = await _dataService.GetAllBookingsForVendorInAwitingApproval(purchaseOrder.VendorCode);
foreach (var booking in allBookedPos)
{
// get ...
0
votes
0
answers
70
views
System.ArgumentException : Invalid callback. Setup on method with return type 'Task<Response>' cannot invoke callback with return type 'Task'
I want to implement a unit test for my method called GetFileContentAsync that get a content of file from an Azure Storage.
This is my class :
using Azure.Storage.Blobs;
using Azure.Storage.Blobs....
0
votes
1
answer
50
views
When mocking HttpContext, SignOutAsync fails
I'm using SignOutAsync from Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.
In my unit tests, I get an ArgumentNullException somewhere within that extension method, which says
...
1
vote
2
answers
70
views
Mock Request and Response of Web service method with Moq Framework
Summary: I want to be able to mock the request and the response of a SOAP web method which makes calls to a remote server. I want to be able to test the entire request and response functionality of ...
0
votes
1
answer
81
views
Handler 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 ...
0
votes
2
answers
102
views
Mocking and unit testing graphql-dotnet
I'm using graphql-dotnet library to query some GraphQL APIs from my C# code. Is there a way to easily mock the GraphQLHttpClient in unit tests?
0
votes
0
answers
51
views
How do I mock HostingEnvironment properly when unit testing?
I am trying to test a code block that says.
if (!HostingEnvironment.IsHosted)
{
throw new Exception();
}
else
{
doWork();
}
I've been trying to create a new instance like this
var hostEnv =...
0
votes
0
answers
25
views
Validating the value of a ref argument using moq [duplicate]
I'm struggling to figure out how I can verify that a method call was invoked with a ref argument of a particular value. The issue is I need to interact with a COM interface, so I am mocking out the ...
1
vote
1
answer
29
views
Setting lambdas for KeyVaultSecret on ReturnsAsync
I'm using Moq 4.18.4 and I'm having trouble when setting the ReturnsAsync, it is showing to me the following error
ISetup<SecretClient, Task<Response>>' does not contain a definition for '...
1
vote
1
answer
49
views
How to mock a method returning OneOf<IServiceA, IServiceB>? Using Moq
In my project, a common method of service resolver class is written. In which a public method returns OneOf<IServiceA, IServiceB, IServiceC>. I am not able to mock this class behavior.
private ...
0
votes
0
answers
33
views
Why Moq dependency uprev is not working as expected?
Moq has a dependency hierarchy as follows
Moq 4.18.4
System.Threading.Tasks.Extensions >= 4.5.4
System.Runtime.CompilerServices.Unsafe >= 4.5.3
In my application I must use
System.Runtime....
0
votes
0
answers
28
views
How do i mock httpresponse.clear() with MOQ framework for unit test?
I cannot find any good answer for this and if it exists, remove this question.
I wanna mock for httpresponse.clear() with moq framework but do not know how to do?
This is the package:
https://learn....
1
vote
2
answers
46
views
Unit testing whether or not method used in System.Threading.Timer constructor (TimerCallback) has been called using Moq
I am looking to make sure a callback passed into a System.Threading.Timer with TimerCallback in the signature:
public Timer (System.Threading.TimerCallback callback, object? state, TimeSpan dueTime, ...
1
vote
1
answer
55
views
Is there a good way of injecting mocked repositories using .NET DI framework?
I have the following generic repository:
public interface IRepository<T> where T : BaseEntity
{
IMongoQueryable Entities { get; }
Task<T> AddAsync(T entity, InsertOneOptions? ...
1
vote
2
answers
68
views
How can I Mock HttpResponseMessage SendAsync in VB.NET?
I have found literally a hundred posts on how to do this in C#, but not a one on how to do it in VB.Net. Every attempt to translate these methods into VB.NET has failed. It seems to boil down to the ...
0
votes
2
answers
41
views
Does not contain a definition for 'ReturnsAsync' and the best extension method overload 'ReturnsExtension'
Not able to call this function Validate()
getting error cs1929 Isetup<IserviceTemplateblService, Task>'does not contain defination for 'ReturnsAsync'and best extension method overload
The ...
1
vote
2
answers
49
views
C#, Moq, Unit-Testing: How to create an object that inherits from another class?
My classes/interfaces are set up like this:
Room.cs
//import statements
namespace namespace1
{
internal class Room: Apartment
{
// constructor
public Room(Furniture furniture) : ...
2
votes
1
answer
61
views
how to mock response from httpclient in c#, Azure functions, how to test
I have a static azure function that has an httpclient inside of a service.
public static void MyAzureFunction ()
{
...........
// inside run
var service = new Service(...)
var result ...
-1
votes
1
answer
89
views
Test for SQL Exception
I have a code for catching SqlException. I wrote a test to handle SQLException based on answer listed here: How to throw a SqlException when needed for mocking and unit testing?
[TestMethod]
public ...
0
votes
0
answers
19
views
How to use CallBase method on mocked Fluentvalidation Validator using Moq
The goal is to verify wether the validation was invoked using the right ruleset whilst still invoking the actual validation (base method).
The current implementation gives a DynamicProxy2 exception ...
0
votes
1
answer
70
views
How to mock a call to external service
I'm using ASP.NET Core 7.0 and I have a Web API.
I have a simple controller that looks like this:
[ApiController]
[Route("api/payment")]
public class PaymentController : ControllerBase
{
...
1
vote
1
answer
44
views
How can I get the original type of a Mock after the Mock has been cast to an object
I have a ServiceCollection, and I want to make a method where I can pass in a set of parameters, and have the ServiceCollection return those services when the matching type is requested. I am using ...
0
votes
1
answer
52
views
.net Mocking ToListAsync() in repository is not working
So I am trying to mock GetQueryable().ToListAsync() but I keep getting this error
"System.NotSupportedException : Unsupported expression ... Extension methods (here: ...
1
vote
1
answer
32
views
Mocked methods with Moq not getting called within code in Unity Play Mode Tests
If I mock a method, do I have to explicitly call that method to run my mocked implementation?
I'm trying to get mocking to work inside a Unity project. I'm basically starting a scene and within a ...
1
vote
1
answer
59
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....
1
vote
0
answers
90
views
How can I mock the Azure Blob storage blob.WithVersion(versionId) function?
I am having issues mocking one particular function from Azure.Storage.Blobs; I would like to be able to mock blob.WithVersion(versionId) but can't figure out how to.
When I don't mock the function, I ...
-1
votes
1
answer
22
views
How to create Moq for "Update a property of concrete class in a method using injected interface method"
I have this concrete class which implements an interface
internal interface ITableAdapter
{
int CustomFill(Dataset dataset, ...);
}
internal interface IEntityRetriever
{
IEntity RetriveEntity();
}...
1
vote
1
answer
49
views
What is the correct syntax for mock.Verify for a protected setup?
I have the following unit test:
[TestMethod]
public async Task ShouldGetExperimentalValuePost()
{
//arrange
var avd = ActualVesselData.Parser.ParseJson(File.ReadAllText(".\\TestFiles\\...
-1
votes
2
answers
53
views
Moq not running correctly and always gives wrong result
I created a small test project in VS 2022 -> .Net framework 4.7.2 to check the usage of moq.
Interface and the implementation are provided below.
public interface IDataMaintainer
{
bool AddData(...
0
votes
0
answers
26
views
C# Moq Mocking a method that expects a Func<TResult> delegate [duplicate]
I need to setup a method with Moq so that I can control what it returns. The setup I'm trying to do looks like this:
Setup(x => x.DoSomething<TResult>(It.IsAny<string>(), It.IsAny<...
0
votes
1
answer
82
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 ...
1
vote
1
answer
26
views
How to create and pass IConfiguration using MSTest
I have a concrete service that is declared in the form:
public class ApiDataService:IApiDataService
{
private IConfiguration configuration;
public ApiDataService(IConfiguration _configuration)
...
0
votes
0
answers
46
views
Mocking a constructor called from the sut
I have a service I'm trying to test which has this code in it:
public async Task ExecuteAsync()
{
IEnumerable<Dto> dtos = await _injectedDtoBuilder.CreateAsync(_injectedParameters);
...
1
vote
1
answer
47
views
how to fix system.NotsupportedException moq use, trying to moq an object
I am trying to mock an object
_logger = new Mock<ILogger>();
_sender = new Mock<ServiceBusMessageSender>();
the error is thrown in this line:
_sender.Setup(x => x.SendMessageToQueue(It....
0
votes
0
answers
55
views
How to mock Func<Task<generic type>> in c#
I have make a generic class like "GenericProxy : IProxy" and method like this :
public async Task<T> SomeMethod<T>(Func<Task<T>> action, bool ignore) {
if (...
0
votes
1
answer
120
views
Mocking Blobclient.DownloadContentAsync() using Moq
am I mocking the method below correctly coz, when called its not returning the result:
var blobContent = new BinaryData("this is test data");
var downloadResult = BlobsModelFactory....