3,324 questions
0
votes
0
answers
24
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 ...
0
votes
1
answer
24
views
EF Core In-Memory Database Test Is Flaky: Data Not Persisting Consistently Between Queries
I’m using EF Core’s in-memory database for unit testing a job that processes event queues and updates existing events in the database. The problem is that my test sometimes passes but often fails, ...
0
votes
0
answers
34
views
Problem with ToListAsync() and NSubstitute for UnitTest
I'm trying to do a test for a unit that is supposed to get all the entities from the database and delete them all.
I'm using .NET 8 and CQRS pattern.
This is the Command Handler to remove all the ...
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 ...
0
votes
0
answers
16
views
EF Core with XUnit "The requested operation cannot be completed because the connection has been broken."
When I run multiple unit tests that use the same API, I am randomly getting this error:
The requested operation cannot be completed because the connection has been broken.
Here are the exception ...
0
votes
0
answers
20
views
Exception at mappermock.verify
Below is my service method
public async Task<ServiceResponse<AnnotationMasterResponse>> CreateAnnotation(AnnotationMasterRequest annotationMasterRequest)
{
return await ...
0
votes
0
answers
33
views
Unit Test Case running individually but failing together
I have a test case which is failing when running all together and working fine individually. I have tried adding Thread.Sleep() and also tried updating the method call to synchronous but didn't help ...
0
votes
0
answers
14
views
handle exception thrown by inner function in Unit test using xUnit
XML Parsing function is as follows:
public async void ParseXML(XMLReader reader)
{
if(await reader.ReadAsync() && reader.Name == "Node1")
{
while(await reader.ReadAsync())
...
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
0
answers
31
views
Unit testing a class that uses encryption
I am working on a relatively young ASP.NET Zero project, in which I am trying to implement unit testing.
I make use of NUnit and SQLite, in order to be able to integration test repositories, ...
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
31
views
Testcontainers.net Container to SQL Server container communication
I have two containers being managed by Testcontainers.net.
_dockerImage = new ImageFromDockerfileBuilder()
.WithDockerfileDirectory(CommonDirectoryPath.GetSolutionDirectory(), String.Empty)
....
1
vote
0
answers
29
views
Automatically add a parameter `ITestOutputHelper` to all Test class constructors
We have a set of 15000+ xunit integration test classes in my application. We identified that the logs generated by the tests could not be correlated to the test itself unless we start using ...
0
votes
0
answers
44
views
IServiceProvider is immediately disposed after creation and i don't understand why
This is my test class(well, part that contains the problem)
public class FiltrationServiceTests:
IClassFixture<IntegrationTestWebAppFactory>,
IAsyncLifetime
{
private readonly ...
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:...
2
votes
1
answer
29
views
Avalonia WriteableBitmap Memory Corruption in XUnit/NUnit Tests, But Not in Running Application
I'm encountering memory corruption issues when running tests using XUnit (and experiencing the same behavior with NUnit), even with seemingly straightforward code. There's no multithreading or complex ...
0
votes
0
answers
57
views
Unexpected TaskCanceledException in xUnit test that runs SQL Server Express LocalDB health check
I have an ASP.NET Core 8.0 REST API with a collection of xUnit unit, integration, and functional tests.
The REST API has some health checks registered with the IServiceProvider at application startup:
...
0
votes
1
answer
33
views
XUnit - TestCaseOrderer - Break if fail
I use the PriorityOrderer describe here :
https://learn.microsoft.com/en-us/dotnet/core/testing/order-unit-tests?pivots=xunit
It works fine, but i would like to break if a test fail.
Something which ...
0
votes
1
answer
101
views
How to create unit tests for MAUI hybrid app?
I am working on a MAUI Hybrid app, and I want to add unit tests for it. At first it was a regular MAUI app. I was able to create a xUnit test project for it. The csproj looked like this:
<Project ...
0
votes
0
answers
15
views
How to forcibly run a skipped xUnit test locally?
I sometimes find xUnit convenient for developing quick test harnesses, these are only intended for me to run locally and should not be run in any formal testing.
From
How do I skip specific tests in ...
0
votes
1
answer
53
views
Xunit TestContainers single server per class with fresh database per test
I'm trying to initiate a single TestContainer instance that creates sql server per test class. Then before every test a fresh database is created and migrated and after every test database is deleted.
...
0
votes
1
answer
35
views
How to handle transactions from Service level for multiple repositories
I have project in which I need to create a transaction from the service level and use it across multiple repository classes . Some of the repos calls their sub repos from within.
There is a main ...
0
votes
1
answer
37
views
Program.cs file after ASP.NET Core 6
I wrote a simple token generating API with ASP.NET Core 6. I need to do an integration test. When I write the integration test, it needs to reference the Program class, but I get an error
The ‘...
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 ...
0
votes
2
answers
46
views
LINQ Expressions in xUnit test
How can I simulate this part of my code in xUnit
var updateCost =
await _costOfConsomption.DeferredWhere(x => x.Id == model.CostOfConsomptionId).FirstOrDefaultAsync() ??
...
0
votes
0
answers
46
views
Failed Unit Tests Troubleshooting
What is proper way to troubleshoot failed Unit Test (or End2End Test) when very complex logic is under the test ? It is common advise in to inject NullLogger to the tested class for unit testing.
...
1
vote
2
answers
93
views
C# Unit Test: Concurrent Requests with MemoryCache and SemaphoreSlim
I'm unit testing a service that fetches data from an API and caches it using IMemoryCache and SemaphoreSlim to handle concurrency. I want to simulate a scenario with multiple concurrent requests where:...
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
...
0
votes
0
answers
24
views
Two different xUnit integration tests with the same IClassFixture writes to the same database despite different connection strings
I have a strange problem with some unit tests in a project I'm working on. I'll try to describe the problem as well as I can, but I'm pretty confused as to what's actually happening here.
The project ...
0
votes
1
answer
67
views
Can I change a connection string in xUnit class fixtures?
I've implemented a DatabaseFixture similar to the example in the xUnit docs, which looks like this:
public class DatabaseFixture : IDisposable
{
public DatabaseFixture()
{
Db = new ...
0
votes
1
answer
111
views
Stop xunit from generating global usings
I'm testing with xunit on multiple frameworks (.Net 8 & .Net Core 3.1). The problem is that it keeps auto-generating this GlobalUsings file in my obj folder:
// <auto-generated/>
global ...
0
votes
1
answer
79
views
Testing a library with a #if NET_STANDARD_2_1 directive
I have a library that targets multiple frameworks, one of which is .Net 8 and one of which is .Net Standard 2.1. Some functions aren't included in the older framework, so I write my own version for it....
0
votes
0
answers
28
views
Specflow second scenario always return 500 internal server error
I have a feature file with two similar scenarios:
Feature: MachineLearningFeature
@api
Scenario: Successfully retrieve default machine learning settings
Given User is authorized as 'Admin'
...
1
vote
0
answers
132
views
How to speed up "Run until failure" function in Visual Studio Tests Explorer?
I have test that failed one time and I want to catch this failure once again. When I start test mannualy I have to wait until test to run will be determined and other ctivities, so one test run takes ...
0
votes
1
answer
49
views
How to write xUnit test for Validate of IValidatableObject? [duplicate]
I have IValidatableObject with Validate method. How to write unit test for this object and this method? (I use xUnit). How to mock context? Code of the object below.
Note: that object have an enum ...
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 ...
1
vote
1
answer
57
views
can I combine Trait and Fact in xunit?
I really want to categorise some xunit tests as integration tests - but this:
[Fact]
[Trait("integration", "whatever")]
It is not ok with me. What I want to say is
[...
0
votes
0
answers
22
views
Visual Studio - Debug tests - `Aborted: Exit code is -42`
I have an old project I try to update. It is based on ASP.NET Zero 6.5.0.
The Tests are based on Xunit. Since an unknown time, when I run a test in Debug, Visual Studo tells me Aborted: Exit code is -...
0
votes
0
answers
92
views
How to run tests on a .dll file using the DotNetCoreCLI@2 command?
I'm facing an annoying issue with running tests in my YAML pipeline. The setup is as follows:
I have an Azure Functions project, for example, Users, which also has an xUnit test project, :Users.Tests. ...
0
votes
1
answer
82
views
Passing the unit-test C#
We have a unit-test to pass.
[TestCase("P2W12P1937A", "W", "12", "1937", "A")]
[TestCase("P02K13P8732D", "K", "13", &...
0
votes
0
answers
53
views
Xunit Serialize/Deserialize Custom Type
I'm trying to serialize / deserialize a unique type as part of an xunit c# test.
The type is
List<GraphicTestCase<TPage>> _testCases = new();
GraphicTestCase looks like the following:
...
1
vote
0
answers
33
views
Selenium XPath Not Contains () Not working correctly [duplicate]
I'm trying to check that a filter works by ensuring that every row of a table contains the correct value in one of it's cells. The xPath I have is the following:
var tableBody = testDriver....
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 ...
1
vote
2
answers
245
views
How to unit test MAUI app segment that uses the MainThread class
I am using xUnit to unit test my MAUI app.
I am testing my ViewModel class. The issue that I have is that a segment of code uses:
if (MainThread.IsMainThread)
{
DoSomething();
}
else
{
...
0
votes
2
answers
127
views
Troubleshooting Async Method Issues in Unit Tests: Resolving FirstOrDefaultAsync() Failures
Problem with Testing FirstOrDefaultAsync() in My Example Code
I have the method below where I'm fetching the user ID by username, and I've written tests for it. However, the tests are not working when ...
0
votes
0
answers
46
views
How to exclude certain projects from being tested in a .NET project using XUnit and Coverlet
So I have a API project, and a Services project in a Visual Studio Solution. I also have separate api.tests.csproj and services.tests.csproj projects. I have a command like dotnet test ... /p:...
0
votes
0
answers
51
views
C# xunit tests - How can i get output from exe file in tests
In my xunit test im using a powershell SDK to run my powershell function and that function should run an exe file then parse the output and return it.
This is the powershell function:
function Get-...
0
votes
2
answers
114
views
Generated Aspire Test Throws SSL Exception During Azure DevOps Tests
I have created a default Aspire starter solution which has the following test:
public sealed class WebTests
{
[Fact]
public async Task GetWebResourceRootReturnsOkStatusCode()
{
// ...
0
votes
1
answer
67
views
System.IO.FileNotFOundException for assembly that lives in the folder for my unit test project?
I am building a project for Revit and now want to build unit tests for my C# code. The issue I am running into is that whenever I actually build the project and reference my project I get an error ...