title,body,link,tags,view_count,is_answered,score,answer_count
Microsoft.Azure.Functions.Worker.Middleware.IFunctionsWorkerMiddleware Unit Testing,"<p>Looking for some examples on how to setup unit testing around IFunctionsWorkerMiddleware.  All the examples I've found are for MVC and not function apps.</p>
<p>Example for MVC, but looking for .net 6 using function apps</p>
<pre><code>using var host = await new HostBuilder() .ConfigureWebHost(webBuilder =&gt; { webBuilder .UseTestServer() .ConfigureServices(services =&gt; { services.AddMyServices(); }) .Configure(app =&gt; { app.UseMiddleware&lt;MyMiddleware&gt;(); }); }) .StartAsync(); var response = await host.GetTestClient().GetAsync(&quot;/&quot;)
</code></pre>
<p>Thanks in advance.</p>
<p>In order to test the middleware we need to spin up a host using HostBuilder; as part of configuring host builder we can stipulate it needs to use the test server (an in-memory webserver).  This is what we will make request against an what should be executing the middleware. Every single example I've found and tried are all for MVC  and nothing for function apps.  and every attempt pretty much results in a gRPC issue (gRPC is spun uo by the function app process by default, I cannot find where/how to not set it up).</p>
",https://stackoverflow.com/questions/75236439/microsoft-azure-functions-worker-middleware-ifunctionsworkermiddleware-unit-test,['asp.net-core-middleware'],144,False,1,0
Reactor unit testing,"<p>I am new to the reactive world. I am working on a piece of code to be reactive from non-reactive. And while fixing the unit tests I have a scenario, I am unsure how to properly replace the logic. Below is an example of current mocking</p>
<pre><code>MyClass2 mockResult = mock(MyClass.class);

doNothing().when(mockResult).api1(&quot;testing&quot;);
when(input.api2(any())).thenReturn(mockResult);

verify(input).api2(any());
verify(mockResult).api1(&quot;testing&quot;);
</code></pre>
<p>api2 became reactive now, and the return type is Mono</p>
<p>I simply made changes below</p>
<pre><code>MyClass1 input = mock(MyClass1.class);
Mono&lt;MyClass2&gt; mockResult = Mono.just(mock(MyClass.class));

doNothing().when(mockResult).api1(&quot;testing&quot;); //  not sure how to test it
when(input.api2(any())).thenReturn(mockResult);

verify(input).api2(any());
verify(mockResult).api1(&quot;testing&quot;); //  not sure how to test it. I get Actually, there were zero interactions with this mock. Wanted but not invoked: error on trying with block(), which is not right anyway
</code></pre>
<p>Any suggestions, please</p>
",https://stackoverflow.com/questions/75933171/reactor-unit-testing,"['unit-testing', 'project-reactor']",55,True,0,1
angular detectChanges() unit testing,"<p>Hello developers I have a login component and I want to test it in the routing module and I'm using detectChanges() method my code looks like this:</p>
<pre><code>describe('TEST: RoutingModule', () =&gt; {
let appComponent: AppComponent;
let loginComponent: LoginComponent;


let appComponentFixture: ComponentFixture&lt;AppComponent&gt;
let loginComponentFixture : ComponentFixture&lt;LoginComponent&gt;;


let router: Router;
let location: Location;

beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
        declarations: [AppComponent,LoginComponent],
        providers: [MockProvider(CookieService), MockProvider(Store), MockProvider(Router)],
        imports: [RouterTestingModule.withRoutes(AppRoutes.getStatics())]
    }).compileComponents(); 
});

beforeEach(() =&gt; {
    router = TestBed.inject(Router);
    location = TestBed.inject(Location);
    
    loginComponentFixture = TestBed.createComponent(LoginComponent);
    loginComponent = loginComponentFixture.componentInstance;
    loginComponentFixture.detectChanges(); // here I get error
    
    appComponentFixture = TestBed.createComponent(AppComponent);
    appComponent = appComponentFixture.componentInstance;
    router.initialNavigation();
});
</code></pre>
<p>then I get this error:</p>
<pre><code>  TypeError: Cannot read properties of undefined (reading 'subscribe')

  43 |      public ngOnInit(): void {
  44 |              this.fromUrl();
&gt; 45 |              const router$ = this.router.events.subscribe(event =&gt; {
     |                                                 ^
  46 |                      if (event instanceof NavigationEnd) {
  47 |                              this.fromUrl();
  48 |                      }
</code></pre>
",https://stackoverflow.com/questions/75257828/angular-detectchanges-unit-testing,"['angular', 'unit-testing', 'events', 'jestjs']",23,False,-1,1
Unit testing Athena ETL?,"<p>We currently have a lambda function with Athena insert statement completing our ETL. I'm seeking guidance on how to unit test. What I have included is code snippet, there are a number of other columns and additional &quot;transformations/manipulations&quot;.</p>
<p>Code:</p>
<pre><code>import boto3

client = boto3.client(&quot;athena&quot;)

query_string = f&quot;&quot;&quot;INSERT INTO ind_actuarial_claims.term_claims
        SELECT 
            id,
            product,
            sex,
            iss_dt,
            year, month, day           
            from 
            (
            select
            id,
            product_line as product,
            case when gender = 'M' then 'Male'
                    else 'Female'
                    end as sex, 
            cast(date_parse(begin_date, '%Y%m%d') as date) as iss_dt, 
            year,
            month,
            day
            from database.table1
            where year = '{year}' and month = '{month}' and day = '{day}')
            &quot;&quot;&quot;

response = client.start_query_execution(
    QueryString=query_string,
    QueryExecutionContext={'Database': 'databasename'},
    ResultConfiguration={'OutputLocation': 's3://'}
)
</code></pre>
<p>Where would I begin trying to write a unit test?</p>
<p>For reference, this is our currently workflow:
python script with lambda_handler() &gt; deployed via Github action to AWS</p>
<p>Much appreciated.</p>
",https://stackoverflow.com/questions/75690176/unit-testing-athena-etl,"['amazon-web-services', 'unit-testing', 'validation', 'amazon-athena']",30,False,0,0
Unit testing Rx Catch,"<p>I'm unit testing the following service and the issue is that I'm able to test only the happy path but not the unhappy path. So how do I test them? TestScheduler? <a href=""http://introtorx.com/Content/v1.0.10621.0/16_TestingRx.html"" rel=""nofollow noreferrer"">http://introtorx.com/Content/v1.0.10621.0/16_TestingRx.html</a></p>
<p>These lines are left untested:</p>
<pre class=""lang-cs prettyprint-override""><code>.Catch&lt;string, TimeoutExceptiocn&gt;(_ =&gt; Observable.Return(&quot;Timeout&quot;))
.Catch&lt;string, Exception&gt;(ex =&gt; Observable.Return(ex.Message))
</code></pre>
<p><a href=""https://i.stack.imgur.com/Y1EEy.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Y1EEy.png"" alt=""enter image description here"" /></a></p>
<pre class=""lang-cs prettyprint-override""><code>public interface IProductService
{
    Task&lt;string&gt; GetAsync();
}

public sealed class ProductService : IProductService
{
    private readonly HttpClient _httpClient;

    public ProductService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public Task&lt;string&gt; GetAsync()
    {
        return Observable
            .FromAsync(() =&gt; _httpClient.GetAsync(&quot;http://www.mocky.io/v2/5e307edf3200005d00858b49&quot;))
            .SubscribeOn(TaskPoolScheduler.Default)
            .Retry(5)
            .Timeout(TimeSpan.FromSeconds(5))
            .Do(x =&gt; Console.WriteLine($&quot;Is message successful? {x.IsSuccessStatusCode}&quot;))
            .SelectMany(async responseMessage =&gt;
            {
                var response = await responseMessage.Content.ReadAsStringAsync();
                return response;
            })
            .Catch&lt;string, TimeoutException&gt;(_ =&gt; Observable.Return(&quot;Timeout&quot;))
            .Catch&lt;string, Exception&gt;(ex =&gt; Observable.Return(ex.Message))
            .ToTask();
    }
}
</code></pre>
<pre class=""lang-cs prettyprint-override""><code>public class ProductServiceTests
{
    [Fact]
    public async Task GetAsync_ShouldReturnText_WhenRequestIsSent()
    {
        // Arrange
        var messageHandler = new MockHttpMessageHandler(&quot;Stuff I want to return&quot;, HttpStatusCode.OK);
        var httpClient = new HttpClient(messageHandler);
        var sut = new ProductService(httpClient);

        // Act
        var result = await sut.GetAsync();

        // Assert
        result.Should().Be(&quot;Stuff I want to return&quot;);
    }

    // TODO: Unhappy path
}
</code></pre>
",https://stackoverflow.com/questions/75178879/unit-testing-rx-catch,"['c#', '.net', 'unit-testing', 'system.reactive']",51,False,0,0
Angular unit testing directive,"<p>I am trying to unit test my directive that looks like this</p>
<p><strong>show-password.directive.ts</strong></p>
<pre><code>/* eslint-disable @typescript-eslint/no-explicit-any */
import { DOCUMENT } from '@angular/common';
import { Directive, ElementRef, Inject, OnInit } from '@angular/core';

@Directive({
    selector: '[securityPassword]'
})
export class ShowPasswordDirective implements OnInit {
    private _shown = false;
    private showIcon =
        // eslint-disable-next-line max-len
        '&lt;img alt=&quot;&quot; src=&quot;data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTUiIGhlaWdodD0iMTUiIHZpZXdCb3g9IjAgMCAxNSAxNSIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4NCjxwYXRoIGQ9Ik03LjQ5OTA4IDMuNTYzMkM1LjE0NzU2IDMuNTIzNTQgMi43MTU1NCA1LjE2Njg2IDEuMTg2NTYgNi44NDk4NEMxLjAyNjA3IDcuMDI4MDIgMC45MzcyNTYgNy4yNTkzMiAwLjkzNzI1NiA3LjQ5OTEyQzAuOTM3MjU2IDcuNzM4OTIgMS4wMjYwNyA3Ljk3MDIyIDEuMTg2NTYgOC4xNDg0QzIuNjgyMjkgOS43OTU4IDUuMTA3MzEgMTEuNDc3IDcuNDk5MDggMTEuNDM2OEM5Ljg5MDg1IDExLjQ3NyAxMi4zMTY1IDkuNzk1OCAxMy44MTM0IDguMTQ4NEMxMy45NzM4IDcuOTcwMjIgMTQuMDYyNyA3LjczODkyIDE0LjA2MjcgNy40OTkxMkMxNC4wNjI3IDcuMjU5MzIgMTMuOTczOCA3LjAyODAyIDEzLjgxMzQgNi44NDk4NEMxMi4yODI2IDUuMTY2ODYgOS44NTA2IDMuNTIzNTQgNy40OTkwOCAzLjU2MzJaIiBzdHJva2U9IiMxRDFGMkEiIHN0cm9rZS13aWR0aD0iMS4yIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz4NCjxwYXRoIGQ9Ik05LjY4NjcxIDcuNTAwNjhDOS42ODY2IDcuOTMzMzIgOS41NTgyIDguMzU2MjEgOS4zMTc3NSA4LjcxNTg4QzkuMDc3MzEgOS4wNzU1NSA4LjczNTYxIDkuMzU1ODUgOC4zMzU4NyA5LjUyMTMzQzcuOTM2MTMgOS42ODY4MiA3LjQ5NjMgOS43MzAwNiA3LjA3MTk4IDkuNjQ1NThDNi42NDc2NyA5LjU2MTExIDYuMjU3OTMgOS4zNTI3MSA1Ljk1MjA1IDkuMDQ2NzVDNS42NDYxNyA4Ljc0MDc5IDUuNDM3ODggOC4zNTA5OSA1LjM1MzUyIDcuOTI2NjZDNS4yNjkxNSA3LjUwMjMyIDUuMzEyNTEgNy4wNjI1IDUuNDc4MSA2LjY2MjhDNS42NDM2OSA2LjI2MzExIDUuOTI0MDggNS45MjE0OSA2LjI4MzgyIDUuNjgxMTRDNi42NDM1NSA1LjQ0MDc5IDcuMDY2NDggNS4zMTI1IDcuNDk5MTIgNS4zMTI1QzcuNzg2NDcgNS4zMTI0MiA4LjA3MTAyIDUuMzY4OTcgOC4zMzY1IDUuNDc4OTJDOC42MDE5OCA1LjU4ODg3IDguODQzMiA1Ljc1MDA1IDkuMDQ2MzYgNS45NTMyN0M5LjI0OTUyIDYuMTU2NDggOS40MTA2NCA2LjM5Nzc0IDkuNTIwNTEgNi42NjMyNUM5LjYzMDM5IDYuOTI4NzYgOS42ODY4NyA3LjIxMzMzIDkuNjg2NzEgNy41MDA2OFoiIHN0cm9rZT0iIzFEMUYyQSIgc3Ryb2tlLXdpZHRoPSIxLjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPg0KPC9zdmc+DQo=&quot; /&gt;';
    private hideIcon = this.showIcon;
    private toWrap: any;
    private span: any;

    constructor(
        private el: ElementRef,
        @Inject(DOCUMENT) private document: Document
    ) {}

    ngOnInit(): void {
        this.toWrap = this.el.nativeElement;
        this.span = this.document.createElement('span');
        this.span.id = 't-toggle-type';
        this.span.innerHTML = this.showIcon;
        this.span.addEventListener('click', () =&gt; {
            this.toggle(this.span);
        });
        this.toWrap.parentNode.appendChild(this.span);
    }

    toggle(span: HTMLElement): void {
        this._shown = !this._shown;
        if (this._shown) {
            this.el.nativeElement.setAttribute('type', 'text');
            span.innerHTML = this.hideIcon;
        } else {
            this.el.nativeElement.setAttribute('type', 'password');
            span.innerHTML = this.showIcon;
        }
    }
}
</code></pre>
<p>Then my
<strong>show-password.directive.spec.ts</strong></p>
<pre><code>import { DOCUMENT } from '@angular/common';
import {
    Component,
    CUSTOM_ELEMENTS_SCHEMA,
    DebugElement,
    ElementRef,
    NO_ERRORS_SCHEMA,
    Renderer2
} from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ShowPasswordDirective } from './show-password.directive';
import { MockElementRef, testingModule } from './utils/mocks';

@Component({
    template: `&lt;input securityShowPassword type=&quot;password&quot; id=&quot;t-password&quot; /&gt;`
})
class TestSecurityShowPasswordDirectiveComponent {}

describe('TestSecurityShowPasswordDirectiveComponent ', () =&gt; {
    let fixture: ComponentFixture&lt;TestSecurityShowPasswordDirectiveComponent&gt;;
    let component: TestSecurityShowPasswordDirectiveComponent;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars-experimental
    let de: DebugElement;

    beforeEach(() =&gt; {
        const imports = testingModule.imports();
        TestBed.configureTestingModule({
            imports: [imports],
            declarations: [
                TestSecurityShowPasswordDirectiveComponent,
                ShowPasswordDirective
            ],
            providers: [
                { provide: DOCUMENT, useValue: document },
                Renderer2,
                {
                    provide: ElementRef,
                    useClass: MockElementRef
                }
            ],
            schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA]
        }).compileComponents();
    });

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(
            TestSecurityShowPasswordDirectiveComponent
        );
        component = fixture.componentInstance;
        de = fixture.debugElement;
    });

    it('should create', () =&gt; {
        expect(component).toBeTruthy();
    });

    it('should toggle type ', () =&gt; {
        // GIVEN
        const input = fixture.debugElement.query(By.css('#t-password'));
        const span = fixture.debugElement.query(By.css('#t-toggle-type'));
        const htmlElement: HTMLElement =
            fixture.nativeElement.querySelector('span');
        // WHEN
        span.nativeElement.click();
        // THEN
        expect(input).toBeTruthy();
    });
});
</code></pre>
<p>But my test got error</p>
<p><strong>TypeError: Cannot read properties of null (reading 'nativeElement')</strong></p>
<p>It look like element span is not created, but in real testing all is working perfect, any info why span is not yet created??</p>
",https://stackoverflow.com/questions/75243403/angular-unit-testing-directive,"['angular', 'typescript', 'unit-testing', 'jasmine']",33,False,0,1
Unit testing coroutine StateFlow,"<p>I am trying to test this StateFlow which lives in a ViewModel and receives data from a UseCase.</p>
<pre><code>val data: StateFlow&lt;Data&gt; = getDataUseCase.execute(Unit).stateIn(viewModelScope, Lazily, Data())
</code></pre>
<p>I have written this test using Mockk and Turbine</p>
<pre><code>@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun `test data updates value`() = runTest {

    val expectedId = 2

    coEvery { getDataUseCase.execute(Unit) } returns flowOf(Data(id = expectedId))

    viewModel.data.test {
        assertEquals(expectedId, expectMostRecentItem().id)
    }

}
</code></pre>
<p>I am always receiving a Data object with all its fields to null so all my assertions are failing (even if I throw an Exception).</p>
<p>Any ideas? thanks!</p>
",https://stackoverflow.com/questions/75926823/unit-testing-coroutine-stateflow,"['android', 'unit-testing', 'kotlin-coroutines', 'kotlin-flow', 'turbine']",87,False,0,1
Unit Testing for dynamodb-onetable,"<p>I am new to Unit Testing and wanted to stub dynamodb-onetable library. I was trying to stub getData() from getDetails.ts file but it shows that &quot;<strong>OneTableArgError: Missing Name Property</strong>&quot;. Because this getProjectDetails() contain new Table() class.
How to stub dynamodb-onetable so that I can get data in dataDetails variable. I was doing something like this in getEmp.spec.ts</p>
<p>dataDetailsStub = sinon.stub(DataService , &quot;getData&quot;);</p>
<pre><code>------lambda.ts
     import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
     import Dynamo from 'dynamodb-onetable/Dynamo';
     export const client = new Dynamo({
                            client: new DynamoDBClient({
                            region: REGION,   }),
                           });

-------DataService.ts
import { client } from '../lambda';
const workspaceTable = new Table({
  client,
  name: TableName,
  schema,
  logger: true,
  partial: false,
});
const projectDetail = workspaceTable.getModel('empDetail');

export default class **DataService** {
  static getData = async (empId: string, type: string) =&gt; {
    const params = {
      projectId,
      type
    };
    const response = await empDetail.find(params);
    logger.trace('response', { response });
    return response;   };
 }


------getDetails.ts
    const dataDetails= await DataService.getData(
      empId,
      'EMPLOYEE-SAVEDATA'
    );
</code></pre>
<p>I was trying to stub the DataService.getData() but getting error saying &quot;OneTableArgError: Missing &quot;name&quot; property&quot;. I want to get data in dataDetailsStub whatever i am sending while mocking the getData()</p>
<pre><code>const dataDetailsStub = sinon.stub(DataService , &quot;getData&quot;).return({emp object});
</code></pre>
<p>Can anyone help me out on this. I'm really got stuck in this. Thanks in advance</p>
",https://stackoverflow.com/questions/75385216/unit-testing-for-dynamodb-onetable,"['javascript', 'typescript', 'amazon-dynamodb']",109,False,1,0
Unit testing S3 PreSigned API,"<p>Im using s3's <code>GetObjectRequest</code> API to get the <code>Request</code> and use it to call Presign API.</p>
<pre><code>type S3Client struct {
    client s3iface.S3API
}

type S3API interface {
    PutObject(input *s3.PutObjectInput) (*s3.PutObjectOutput, error)
    GetObjectRequest(*s3.GetObjectInput) (*request.Request, *s3.GetObjectOutput)
}

type Request interface {
    Presign(expire time.Duration) (string, error)
}

func NewS3Client() S3Client {
    awsConfig := awstools.AWS{Config: &amp;aws.Config{Region: aws.String(&quot;us-west-2&quot;)}}
    awsSession, _ := awsConfig.Get()
    return S3Client{
        client: s3.New(awsSession),
    }
}

func (s *S3Client) GetPreSignedUrl(bucket string, objectKey string) (string, error) {

    req, _ := s.client.GetObjectRequest(&amp;s3.GetObjectInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(objectKey),
    })

    urlStr, err := req.Presign(30 * 24 * time.Hour)
    if err != nil {
        return &quot;&quot;, err
    }

    return urlStr, nil
}
</code></pre>
<p>Wondering how I can write unit tests for this snippet. So far I have the following but its not working. Would appreciate some help with this.</p>
<pre><code>type MockRequestImpl struct {
    request.Request
}

func (m *MockRequestImpl) Presign(input time.Duration) (string, error) {
    return preSignFunc(input)
}

type MockS3Client struct {
    s3iface.S3API
}

func init() {
    s = S3Client{
        client: &amp;MockS3Client{},
    }
}

func (m *MockS3Client) GetObjectRequest(input *s3.GetObjectInput) (*request.Request, *s3.GetObjectOutput) {
    return getObjectFunc(input)
}

func TestS3Service_GetPreSignedUrl(t *testing.T) {
    t.Run(&quot;should not throw error&quot;, func(t *testing.T) {
        getObjectFunc = func(input *s3.GetObjectInput) (*request.Request, *s3.GetObjectOutput) {
            m := MockRequestImpl{}.Request
            return &amp;m, &amp;s3.GetObjectOutput{}
        }
        preSignFunc = func(expire time.Duration) (string, error) {
            return &quot;preSigned&quot;, nil
        }

        url, err := s.GetPreSignedUrl(&quot;bucket&quot;, &quot;objectKey&quot;)
        assert.Equal(t, &quot;preSigned&quot;, url)
        assert.NoError(t, err)
    })
}

</code></pre>
<p>Getting the following error :
<code>=== RUN   TestS3Service_GetPreSignedUrl === RUN   TestS3Service_GetPreSignedUrl/should_not_throw_error --- FAIL: TestS3Service_GetPreSignedUrl (0.00s)     --- FAIL: TestS3Service_GetPreSignedUrl/should_not_throw_error (0.00s) panic: runtime error: invalid memory address or nil pointer dereference [recovered]    panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=0x102ca1eb4]</code>
For line <code>  urlStr, err := req.Presign(30 * 24 * time.Hour)</code>. Guessing req is returned as nil</p>
",https://stackoverflow.com/questions/75574755/unit-testing-s3-presigned-api,"['go', 'amazon-s3', 'mocking', 'gomock']",70,True,1,1
Unit testing spatial database repository,"<p>Normally I wrap my persistence layer using a repository pattern, which I then unit-test using SQLite.</p>
<p>Now I am processing spatial data using NetTopologySuite. The repository method <em>GetUsersInPerimeterAsync(requestorLoc, perimeter)</em> should return all users closeby.</p>
<p>So I have GPS (WGS84, SRID 4326) coordinates I want to compute distance from.
Using Haversine formula, this is not a problem, but of course this should be done on the database side.</p>
<p>Now, as SRID 4326 is using degrees as units, NTS's .Distance method also returns degrees which is completely meaningless.</p>
<p>I've read that using data type &quot;geography&quot; instead of &quot;geometry&quot; would return metres on Postgres and MSSQL, but is not available on SQLite.</p>
<p>So now, I am projecting to a cartesian system before persisting. Like 4839 (Germany).
Like this, database-side distance resolving works, but I am now completely bound to a specific spatial reference.</p>
<p>On the other side, using a generic reference like pseude web-mercator will give me huge errors again...</p>
<p>Is there a way around this? Do I have to choose between locking to a specific database or locking to a specific spatial reference?</p>
<p>Why does haversine work &quot;good enough&quot; all over the world whereas SRID projections differ greatly?</p>
",https://stackoverflow.com/questions/75696191/unit-testing-spatial-database-repository,"['c#', 'mapping', 'geospatial', 'nettopologysuite', 'srid']",36,False,0,0
Unit testing @run_on_executor decorated functions?,"<p>I'm trying to find a less brittle way to test functions employing the run_on_executor decorator. My problem is that a unit test will typically run the decorated function, return and then carry out the assert statement before the decorated function itself has had a chance to execute/complete. Here's an example decorated function, where the member variable has been initialised to be False:</p>
<pre><code>@run_on_executor(executor='thread_executor')
def read_environs(self):
    &quot;&quot;&quot;Read environmental sensors.&quot;&quot;&quot;
    self.environs_in_progress = True
</code></pre>
<p>And the unit test code, which will fail (saying the member variable is False) unless I uncomment the sleep statement:</p>
<pre><code>def test_read_environs_working_ok(self):
    &quot;&quot;&quot;Test the read_environs function works.&quot;&quot;&quot;
    with patch('some.class'):
        result = await self.test_hardware.hardware.read_environs()
        # time.sleep(0.1)
        assert self.test_hardware.hardware.environs_in_progress is True
</code></pre>
<p>Obviously, relying upon an arbitrary hardcoded delay is a bit brittle. I've had a look online, on SO and the Tornado documentation but cannot figure this out. I'm aware there is the run_in_executor or going whole hog to rely upon the async part of Tornado. However, it feels wrong to rewrite my source code to suit my unit tests. Also, I prefer the clean implementation of run_on_executor. Am I doomed to rely upon brittle sleep statements to make this work?</p>
",https://stackoverflow.com/questions/75284189/unit-testing-run-on-executor-decorated-functions,"['python', 'tornado']",28,False,0,0
Unit Testing in Python:: Failure :::,"<p>I am running unit testing in python. Here is the code for test script.</p>
<pre><code>import json


def test_create_flat(client):
    data = {
        &quot;title&quot;: &quot;SDE super&quot;,
        &quot;company&quot;: &quot;doogle&quot;,
        &quot;company_url&quot;: &quot;www.doogle.com&quot;,
        &quot;location&quot;: &quot;USA,NY&quot;,
        &quot;description&quot;: &quot;python&quot;,
        &quot;date_posted&quot;: &quot;2022-03-20&quot;
        }
    response = client.post(&quot;/flats/create-flat/&quot;,json.dumps(data))
    assert response.status_code == 200 
    assert response.json()[&quot;company&quot;] == &quot;doogle&quot;
    assert response.json()[&quot;description&quot;] == &quot;python&quot;

def test_read_flat(client):     #new test
    data = {
        &quot;title&quot;: &quot;SDE super&quot;,
        &quot;company&quot;: &quot;doogle&quot;,
        &quot;company_url&quot;: &quot;www.doogle.com&quot;,
        &quot;location&quot;: &quot;USA,NY&quot;,
        &quot;description&quot;: &quot;python&quot;,
        &quot;date_posted&quot;: &quot;2022-03-20&quot;
        }
    response = client.post(&quot;/flats/create-flat/&quot;,json.dumps(data))

    response = client.get(&quot;/flats/get/1/&quot;)
    assert response.status_code == 200
    assert response.json()['title'] == &quot;SDE super&quot;
</code></pre>
<p>Here is the result. I couldn't find the reason for the failure on test_read_flat function.</p>
<p>Terminal
-&gt; pytest</p>
<pre><code>================================================ test session starts ================================================
platform darwin -- Python 3.8.8, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: /Users/ok/Desktop/javasc/backend
plugins: mock-1.13.0, anyio-3.6.2, cov-3.0.0
collected 3 items                                                                                                   

tests/test_routes/test_flats.py .F                                                                            [ 66%]
tests/test_routes/test_users.py .                                                                             [100%]

===================================================== FAILURES ======================================================
__________________________________________________ test_read_flat ___________________________________________________

client = &lt;starlette.testclient.TestClient object at 0x7f89f8f0c8e0&gt;

    def test_read_flat(client):     #new test
        data = {
            &quot;title&quot;: &quot;SDE super&quot;,
            &quot;company&quot;: &quot;doogle&quot;,
            &quot;company_url&quot;: &quot;www.doogle.com&quot;,
            &quot;location&quot;: &quot;USA,NY&quot;,
            &quot;description&quot;: &quot;python&quot;,
            &quot;date_posted&quot;: &quot;2022-03-20&quot;
            }
        response = client.post(&quot;/flats/create-flat/&quot;,json.dumps(data))
    
        response = client.get(&quot;/flats/get/1/&quot;)
&gt;       assert response.status_code == 200
E       assert 404 == 200
E        +  where 404 = &lt;Response [404]&gt;.status_code

tests/test_routes/test_flats.py:30: AssertionError
============================================== short test summary info ==============================================
FAILED tests/test_routes/test_flats.py::test_read_flat - assert 404 == 200
============================================ 1 failed, 2 passed in 0.80s ============================================
(base) ok@Oks-MacBook-Air backend % 
</code></pre>
<p>All three test should have passed. I am new to unit testing I tried and checked all the lines one by one but couldn't see the problem</p>
",https://stackoverflow.com/questions/75406081/unit-testing-in-python-failure,"['python', 'unit-testing']",37,False,0,0
unit-testing boost interprocess client,"<p>I have to unit-test a client of a shared memory map constructed using the boost interprocess. It is really awkward to create shared memory blocks for unit-testing. Normally I would use some static memory to simulate shared memory behavior during unit-tests.</p>
<p>I do not see such a possibility in the boost interprocess. What is the established practice for unit-testing clients of the boos interprocess?</p>
",https://stackoverflow.com/questions/76316303/unit-testing-boost-interprocess-client,"['unit-testing', 'boost-interprocess']",5,False,0,0
Jasmine angular unit testing BehaviorSubject,"<p>i have some service like this</p>
<p><strong>calendar-domain.service.ts</strong></p>
<pre><code>@Injectable()
export class CalendarDomainService {
  private _calendarWeek = new BehaviorSubject&lt;CalendarWeekTo | null&gt;(null);
  get calendarWeek$(): Observable&lt;CalendarWeekTo | null&gt; {
    return this._calendarWeek.asObservable();
  }

  setCalendarWeek(calendarWeek: CalendarWeekTo): void {
    this._calendarWeek.next(calendarWeek);
  }
}
</code></pre>
<p>And unit test like this</p>
<p><strong>calendar-domain.service.spec.ts</strong></p>
<pre><code>import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { TestBed } from '@angular/core/testing';

import { CalendarDomainService } from './calendar-domain.service';

describe('CalendarDomainService', () =&gt; {
    let service: CalendarDomainService;

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            providers: [CalendarDomainService],
            schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
        });
        service = TestBed.inject(CalendarDomainService);
    });

    it('should be created', () =&gt; {
        expect(service).toBeTruthy();
    });
});
</code></pre>
<p>As you may see i didn't test those two function, because honest I don't know how even to start testing, any info about how to start, thanks</p>
",https://stackoverflow.com/questions/75181344/jasmine-angular-unit-testing-behaviorsubject,"['angular', 'typescript', 'jasmine']",98,True,0,1
mock Axios.Create() in unit testing,"<p>i want to create an unit testing for my service. In my service, i used axios.create function to help me configure some config. I am a little confused with the unit test.
I've done creating unit tests and mocks for axios but without using axios.create. Maybe you can help me to solve my problem. I have tried several solutions but have not been able to solve my problem</p>
<p>this is my api.js</p>
<pre><code>import axios from &quot;axios&quot;;

const BASE_URL = process.env.REACT_APP_BASE_URL;


const api = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
  headers: {
    Accept: &quot;application/json&quot;
  },
});

const apiService = {
  post: async (url: string, json = {}, reqConfig = {}) =&gt; {
    const token = localStorage.getItem(&quot;accessToken&quot;);
    if (token) {
      api.defaults.headers.Authorization = `Bearer ${token}`;
    }
    api.defaults.headers[&quot;Content-Type&quot;] = &quot;application/json&quot;;
    const data = json;
    try {
      const response = await api.post(url, data, {
        baseURL: BASE_URL,
        ...reqConfig
      });
      return response;
    } catch (err) {
      return err
    }
  }
}

export default apiService
</code></pre>
<p>and this is my unit test:</p>
<pre><code>import apiService from &quot;../api&quot;;
import axios from &quot;axios&quot;;

jest.mock(&quot;axios&quot;);
const mockedAxios = axios as jest.Mocked&lt;typeof axios&gt;;

describe(&quot;apiService&quot;, () =&gt; {
    beforeAll(() =&gt; {
        mockedAxios.create.mockReturnThis();
    });
    it(&quot;should call apiService.post&quot;, async () =&gt; {
        mockedAxios.post.mockImplementationOnce(() =&gt;
            Promise.resolve({
                data: {
                    task_id: &quot;123&quot;
                },
                status: 200
            })
        );
        const response: any = await apiService.post(&quot;&quot;, {
            requester: &quot;example@gmail.com&quot;,
            subject: &quot;test&quot;,
            description: &quot;test&quot;,
            attach: false
        });
        expect(response.data.task_id).toEqual(&quot;123&quot;);
        expect(response.status).toEqual(200);
    });
});
</code></pre>
<p>this is the error:</p>
<p><a href=""https://i.stack.imgur.com/6cijj.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/6cijj.png"" alt=""enter image description here"" /></a></p>
<p>I have tried to comment the api.defaults code, but i got this one:</p>
<p><a href=""https://i.stack.imgur.com/jkGyq.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/jkGyq.png"" alt=""enter image description here"" /></a></p>
<p>can someone help me to solve my problem? Thankyou.</p>
",https://stackoverflow.com/questions/76183702/mock-axios-create-in-unit-testing,"['javascript', 'reactjs', 'unit-testing', 'axios']",68,False,0,1
Unit testing notebooks in databricks,"<p>I have created test_example.py inside test1 folder  inside repo /Workspace/Repos/temp/test1/sample.py as follow:</p>
<pre><code>def test_addition():
    assert 1 + 2 == 3

def test_subtraction():
    assert 5 - 3 == 2
</code></pre>
<p>I have created sample.py inside test1 folder inside repo /Workspace/Repos/temp/test1/sample.py as follow:
import pytest</p>
<pre><code>test_file_path = '/Workspace/Repos/temp/test1/test_example.py'

# Run the test file with the specified arguments
retcode = pytest.main([test_file_path, '-v', '-p', 'no:cacheprovider'])

# Check the return code to see if the tests passed or failed
assert retcode ==0, 'the pytest invocation failed.see the log above for details.'

</code></pre>
<p>I would like to test all files from test1 folder which have all unit testing files:</p>
<p>but getting error :</p>
<p>OSError: [Errno 95] Operation not supported: '/Workspace/Repos/temp/test1/<strong>pycache</strong>'
=========================== short test summary info ============================
ERROR test_example.py - OSError: [Errno 95] Operation not supported: '/Worksp...
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
=============================== 1 error in 1.06s ===============================
Out[2]: &lt;ExitCode.INTERRUPTED: 2&gt;</p>
",https://stackoverflow.com/questions/75823688/unit-testing-notebooks-in-databricks,"['unit-testing', 'databricks']",29,False,0,0
Paging Android Unit Testing PagingData,"<p>Hello I am trying to unit test the Paging Data I receive from the flow of a Pager.I am using the paging-testing dependency as stated in Paging Testing Android guide. This dependency has a method to convert the PagedData to a list using asSnapshot() method. I have followed the same code as the guide suggested. But my test is completing before I receive the result. I debugged the lambda block which the asSnapshot() takes and it is unreachable.</p>
<p>I am sharing my test code below.</p>
<pre><code>    private val repo:ProfileRepository = mock()
    private val fakeRepo = EmployeeTestRepo()
    private val fakeModule = FakeEmployeeModule()
    private val fakeColl = fakeModule.getFakeCollection()
    private val fakeConfig = fakeModule.getFakePagingConfig()
    private val useCase:GetEmployeeRequestsUseCase = GetEmployeeRequestsUseCase(repo,fakeColl,
        fakeConfig)

    @Test
    fun `fetch employee requests from Firestore`() = runTest {
        whenever(repo.getUserRequests(fakeColl,fakeConfig))
            .thenReturn(fakeRepo.getUserRequests(fakeColl,fakeConfig))
        backgroundScope.launch(UnconfinedTestDispatcher(this.testScheduler)) {
            val flow =  useCase.invoke()
            val list = flow.asSnapshot(this@launch){
                appendScrollWhile {  item: User -&gt; item.name == &quot;5 employee request&quot; }
            }
            Assert.assertEquals(list, fakeRepo.getUserRequests(fakeColl, fakeConfig))

        }
    }
</code></pre>
",https://stackoverflow.com/questions/76015378/paging-android-unit-testing-pagingdata,"['android', 'firebase', 'android-paging-3']",52,False,0,0
Unit testing Spring controllers with CSRF,"<p>I have the version 5.6.10 in the following dependencies</p>
<ul>
<li><code>spring-security-test</code></li>
<li><code>spring-security-core</code></li>
<li><code>spring-security-web</code></li>
</ul>
<p>I have a controller with CSRF</p>
<pre><code>@GetMapping(value = &quot;/data&quot;)
public ResponseEntity&lt;DataResponse&gt; data(@RequestParam(required = false) Double param, CsrfToken token){
    ...
}
</code></pre>
<p>I have a JUnit test that was working before adding the <code>, CsrfToken token</code> to Repository.</p>
<pre><code>@WebMvcTest(controllers = Controller.class, excludeAutoConfiguration = {SecurityAutoConfiguration.class})
@ContextConfiguration(classes = {Controller.class, TestConfiguration.class})
class ControllerTest {

    @Autowired private MockMvc mockMvc;


    @Test
    void test() throws Exception {
    
        mockMvc.perform(get(&quot;/.../data?param=2.0&quot;)
                    .contextPath(&quot;/CONTEXT&quot;).servletPath(&quot;/.../data&quot;)
                    .contentType(MediaType.APPLICATION_JSON)
            )
            .andExpectAll(
                status().isOk(),
                ...
            )
            .andReturn();
    }
}
</code></pre>
<pre><code>
@WebAppConfiguration
@EnableWebMvc
public class TestConfiguration {

    @Bean
    ReactjsControllerExceptionHandler reactjsControllerExceptionHandler() {
        return new ControllerExceptionHandler(); // is a @ControllerAdvice that extends ResponseEntityExceptionHandler. I think it does not matter for this case.
    }
}

</code></pre>
<p>I am getting</p>
<blockquote>
<p>No primary or single unique constructor found for interface org.springframework.security.web.csrf.CsrfToken</p>
</blockquote>
<pre><code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: No primary or single unique constructor found for interface org.springframework.security.web.csrf.CsrfToken

    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:502)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:596)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:201)
Caused by: java.lang.IllegalStateException: No primary or single unique constructor found for interface org.springframework.security.web.csrf.CsrfToken
    at org.springframework.beans.BeanUtils.getResolvableConstructor(BeanUtils.java:268)
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:219)
    at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:85)
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:147)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:122)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:179)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:146)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1072)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:965)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    ... 87 more
</code></pre>
<p>I already tried these options:</p>
<ul>
<li><code>mockMvc.perform(get(...).with(csrf()))</code></li>
<li>Setting csfrToken as attribute:</li>
</ul>
<pre><code>.with(request -&gt; {
    request.setAttribute(CsrfToken.class.getName(), csrfToken);
    return request;
})
</code></pre>
<ul>
<li>Mocking with Mockito</li>
</ul>
<pre><code>CsrfToken csrfToken = Mockito.mock(CsrfToken.class);
Mockito.when(csrfToken.getToken()).thenReturn(&quot;myToken&quot;);
</code></pre>
<p>I am getting always the same error, what can I do?</p>
",https://stackoverflow.com/questions/76011945/unit-testing-spring-controllers-with-csrf,"['java', 'spring', 'spring-security', 'junit', 'spring-security-test']",176,True,3,1
Unit testing does not get attributes,"<p>I want to test (values that are definitely inside my database (I see these values when i am debugging))
I want to get get a list of strings from an linkedArrayList with a LinkedHashMap inside it (named names in code bellow).</p>
<p>I expect that this is wrong:</p>
<pre><code>List&lt;String&gt; names = body.stream().map(e-&gt; e.get(&quot;name&quot;)).collect(Collectors.toList());
</code></pre>
<p>Do you know how I can get my test passed by receiving a list of strings of of the attribute name?</p>
<p><a href=""https://i.stack.imgur.com/kKYrF.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/kKYrF.png"" alt=""DebugResults"" /></a></p>
<pre><code>public class FinanceRestControllerTests {
    private RestTemplate restTemplate;

    @Before
    public void setUp() {
        restTemplate = new RestTemplate();
    }
    
    @Test
    public void testGetContracts() {
        ResponseEntity&lt;List&gt; response = restTemplate.getForEntity(&quot;http://localhost:5050/finance/rest/contracts&quot;, List.class);
        List&lt;Map&lt;String,String&gt;&gt; body = response.getBody();
        System.out.println(body);
        MatcherAssert.assertThat(response.getStatusCodeValue(), Matchers.equalTo(200));
        List&lt;String&gt; names = body.stream().map(e-&gt; e.get(&quot;name&quot;)).collect(Collectors.toList());
        names.forEach((n) -&gt; System.out.println(n));
        MatcherAssert.assertThat(names, Matchers.containsInAnyOrder(&quot;Jen&quot;, &quot;Nakzo&quot;, &quot;Renes&quot;));
    }
}
</code></pre>
",https://stackoverflow.com/questions/75644225/unit-testing-does-not-get-attributes,"['java', 'spring', 'hibernate', 'junit']",30,True,2,1
Node.js unit testing using redis-mock,"<p>I am trying to connect to redis and set the data in redis using <a href=""https://www.npmjs.com/package/redis-mock"" rel=""nofollow noreferrer"">redis-mock</a> library in node-typescript but the test is failing</p>
<p>The redis connection code:</p>
<pre><code>let client: RedisClientType;

client = createClient({
    url: &quot;redis://localhost:6379&quot;,
});

beforeAll(() =&gt; {
    async () =&gt; {
        try {
            await client.connect();
        } catch (error) {
            console.error('Error connecting redis');
        }
    };
});
</code></pre>
<p>I have configured the redis-mock in jest.config.js file as per the <code>redis-mock</code> documentation but somehow it is not working</p>
<p>Here is the test case:</p>
<pre><code>describe('Redis', () =&gt; {
    it('should set user info in Redis', async () =&gt; {
        const userInfo = { id: 1, name: 'John Doe' };
        const token = 'some-token';

        await client.set(token, JSON.stringify(userInfo));
        const result = await client.get(token);

        expect(result).toEqual(JSON.stringify(userInfo));
    });
});
</code></pre>
<p>The return value of redis set method returns undefined</p>
",https://stackoverflow.com/questions/76182270/node-js-unit-testing-using-redis-mock,"['node.js', 'typescript', 'express', 'unit-testing']",61,False,0,1
Mapper.map returns null in unit testing,"<pre><code>public async Task Make_Sure_Getting_Active_Material_ReturnsActiveMaterials()
{
    var data = MaterialData.GetFakeMaterialList();
    var _logger = new Mock&lt;ILogger&lt;GetAllMaterialQueryHandler&gt;&gt;();
    var mockSet = FakeDbSetup.GetMockDbSet&lt;DataAccess.Domain.Materials.Material&gt;(data);
    var mockContext = FakeDbSetup.GetMockDbContext();

    mockSet.Setup(x =&gt; x.AsNoTracking()).Returns(mockSet.Object);
    mockSet.Setup(m =&gt; m.Include(It.IsAny&lt;String&gt;())).Returns(mockSet.Object);
    mockContext.Setup(c =&gt; c.Materials).Returns(mockSet.Object);
           
    GetAllMaterialQuery query = new GetAllMaterialQuery();
    GetAllMaterialQueryHandler handler = new GetAllMaterialQueryHandler(mockContext.Object, _mapper!.Object, _logger.Object);

    // Act
    var Materials = await handler.Handle(query, new System.Threading.CancellationToken());

    Assert.False(Materials[0].IsDeleted);
}

public async Task&lt;List&lt;MaterialViewModel&gt;&gt; Handle(GetAllMaterialQuery request, CancellationToken cancellationToken)
{
    try
    {
        // get only active materials.
        var materials = await _context.Materials
                                      .Where(m =&gt; !m.IsDeleted)
                                      .AsNoTracking()
                                      .Include(m =&gt; m.Well)
                                      .Include(m =&gt; m.Rig)
                                      .Include(m =&gt; m.Supplier)
                                      .Include(m =&gt; m.Chemical!.MaterialType)
                                      .Include(m =&gt; m.Chemical!.MaterialSubType)
                                      .Include(m =&gt; m.CisProMaterial)              
                                      .ToListAsync(cancellationToken);
            
    // on this line I'm getting null
    var materialViewModel = _mapper.Map&lt;List&lt;DataAccess.Domain.Materials.Material&gt;, List&lt;MaterialViewModel&gt;&gt;(materials);
    
    return materialViewModel.OrderByDescending(x =&gt; x.ReceivedOn)
                            .ThenBy(x =&gt; x.Name)
                            .ThenBy(x =&gt; x.SpecificGravity).ToList();
}
catch (Exception ex)
{
    _logger.LogError(ex, ex.Message);
    throw;
}

// returns null
var materialViewModel = _mapper.Map&lt;List&lt;DataAccess.Domain.Materials.Material&gt;, List&lt;MaterialViewModel&gt;&gt;(materials);
</code></pre>
<p>This works fine while running actual application, while it returns null in unit testing.I have added the necessary mappings as well</p>
",https://stackoverflow.com/questions/75299452/mapper-map-returns-null-in-unit-testing,"['c#', '.net', 'unit-testing', 'testing', 'mapper']",46,False,0,0
Angular Unit testing for Safe Pipe,"<p>I am trying to write a unit testing case without using fixtures. But it keep throwing me an error</p>
<p>I am getting an error of</p>
<pre><code>this.sanitizer.bypassSecurityTrustResourceUrl is not a function
</code></pre>
<pre><code>  constructor(private sanitizer: DomSanitizer) {}

  transform(value: string): SafeResourceUrl {
    return this.sanitizer.bypassSecurityTrustResourceUrl(value);
  }
</code></pre>
<pre><code>  it('should return safe url', () =&gt; {
    const pipe = new SafeUrlPipe(&lt;DomSanitizer&gt;{});
    pipe.transform('val');
    expect(pipe).toBeTruthy();
  });
</code></pre>
<p>I have try too make it undefined or match but it still haven't work</p>
",https://stackoverflow.com/questions/75010760/angular-unit-testing-for-safe-pipe,"['angular', 'karma-jasmine']",98,False,0,1
Unit testing method that returns bool,"<p>Let's consider a method <code>bool Validate(Request req)</code>. The specific implementation doesn't matter.</p>
<p>But the thing we know is that this method always return <code>true</code> or <code>false</code>. And now I see problem with unit testing method like this below.</p>
<p>We can test whether it returns <code>false</code> when validation fails for many cases, e.g. user is not adult, has not enough role to access some resource etc.</p>
<p>But we can't determine where the <code>false</code> is returned. So unit test can be successful but due to different reason than expected.</p>
<p>Currently, to check whether <code>false</code> is returned where I want to return it (and this is specified by concrete test method where it should be returned) I set breakpoint on this <code>return</code> statement and run concrete unit test method. If test stops on this breakpoint I'm sure unit test is not lying.</p>
<p>But this approach seems primitive to me. How shall I write unit tests for methods that returns <code>bool</code>?</p>
",https://stackoverflow.com/questions/76265752/unit-testing-method-that-returns-bool,"['c#', 'unit-testing']",65,True,0,2
Angular unit testing this.target.clear is undefined,"<p>spec.ts:
`it('should reset form :resetUploadFileFeild()', () =&gt; {</p>
<p>component.docUploadForm = formData;</p>
<p>component.target.clear();</p>
<p>component.Otherdocuments.push(component.setUploadedImage(1, 1));</p>
<p>component.documents.push(component.setUploadedImage(1, 1));</p>
<p>component.resetUploadFileFeild();
});`</p>
<p>component.ts:</p>
<p>`resetUploadFileFeild() {</p>
<p>this.target.clear();</p>
<p>.....
}<code> </code> TypeError: Cannot read properties of undefined (reading 'clear')`
how can i solve this error?</p>
",https://stackoverflow.com/questions/75106758/angular-unit-testing-this-target-clear-is-undefined,"['angular', 'unit-testing', 'karma-jasmine']",25,False,0,1
Unit testing in Vue2 with Jest,"<p>For a school project we must write some unit-tests in a Vue2 codebase. I have never used Vue2 nor Jest, but I am familiar with Javascript.</p>
<p>I wanted to start creating a very simple unit-test, just to see how it works. Jest automatically creates a HelloWorld unit-tests that passes message to a component, and checks if the message is rendered correctly;</p>
<pre><code>import { shallowMount } from &quot;@vue/test-utils&quot;;
import Login from &quot;@/components/authentication/Login.vue&quot;;

describe(&quot;Login.vue&quot;, () =&gt; {
    it(&quot;renders props.msg when passed&quot;, () =&gt; {
        const msg = &quot;new message&quot;;
        const wrapper = shallowMount(Login, {
        propsData: { msg }
        });
        expect(wrapper.text()).toMatch(msg);
    });
});
</code></pre>
<p>However, i get this error when running the test;</p>
<pre><code>Cannot read properties of undefined (reading 'dispatch')
TypeError: Cannot read properties of undefined (reading 'dispatch')
</code></pre>
<p>There seems to be something wrong with the ShallowMount, people with the same error had problems with vuex store, but that doesn't seem to be my problem.</p>
<p>Thank You!</p>
",https://stackoverflow.com/questions/76013088/unit-testing-in-vue2-with-jest,"['javascript', 'vue.js', 'vuejs2', 'jestjs', 'vuex']",34,True,0,1
Setup service provider on unit testing,"<p>I have a component the following:</p>
<p><strong>TS</strong></p>
<pre><code>export class CashFlowSalariesComponent implements OnInit, OnChanges {

...

constructor(
    public apiService: ApiService,
    private modalService: NgbModal,
    private toastr: ToastrService
  ) {}

  ngOnInit() {

  }
}
</code></pre>
<p>Now I want to create a unit testing for it so I try</p>
<p><strong>.spec.ts</strong></p>
<pre><code>describe('CashFlowSalariesComponent', () =&gt; {
    let component: CashFlowSalariesComponent;
    let fixture: ComponentFixture&lt;CashFlowSalariesComponent&gt;;
    let apiService: ApiService;


  
    beforeEach(async(() =&gt; {
      TestBed.configureTestingModule({
        schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
        imports: [
                            [RouterModule.forRoot([])],
                            RouterTestingModule,
                            FormsModule,
                            ReactiveFormsModule,
                            BrowserModule,
                            HttpClientTestingModule,
                        ],
        declarations: [ 
            CashFlowSalariesComponent,
        ],
        providers: [{provide: apiService}]

      })
      .compileComponents();
    }));
  
    beforeEach(() =&gt; {
      fixture = TestBed.createComponent(CashFlowSalariesComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    });
  
    it('should create', () =&gt; {
      expect(component).toBeTruthy();
    });
</code></pre>
<p>But this is throwing an error message:</p>
<blockquote>
<p>NullInjectorError:
StaticInjectorError(DynamicTestModule)[CashFlowSalariesComponent -&gt;
ApiService]:    StaticInjectorError(Platform:
core)[CashFlowSalariesComponent -&gt; ApiService]:
NullInjectorError: No provider for ApiService!</p>
</blockquote>
<p>As you can see, I tried to set the ApiService as a provider, but it did not work; what am I doing wrong?</p>
",https://stackoverflow.com/questions/75162774/setup-service-provider-on-unit-testing,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",38,True,0,2
Angular unit testing - test ng-content,"<p>I have an expansion panel component that wraps content dynamically:</p>
<pre><code>&lt;div class=&quot;expansion-panel&quot;&gt;
  &lt;ng-content&gt;&lt;/ng-content&gt;
&lt;/div&gt;
</code></pre>
<p>If you'd use this component it would be like this</p>
<pre><code>&lt;expansion-panel&gt;
  // any content
&lt;/expansion-panel&gt;
</code></pre>
<p>I want to write a unit test that checks whether the content renders correctly, but I can't find any way to insert some content (other than <code>fixture.nativeElement.innerHTML = 'content'</code>, but that's not the right way). How do I do this?</p>
",https://stackoverflow.com/questions/75788420/angular-unit-testing-test-ng-content,"['angular', 'unit-testing', 'karma-jasmine']",77,True,0,1
Exclude *.data.spec.ts file from unit testing,"<p>I'm struggling to find a simple answer on internet on how to exclude <code>*.data.spec.t</code>s from Jest tests.
I think this is happening in <code>jest.config.json</code> file and need to put something in <code>&quot;testPathIgnorePatterns&quot;: []</code>, but I didn't find the correct RegEx (if not wrong) to exclude those <code>*.data.spec.ts</code> files.</p>
<p>Any clue?</p>
<p>Here is the path to the file: <code>src/app/features/settings/settings.data.spec.ts</code>.</p>
<p>Thanks in advance for your help. :)</p>
",https://stackoverflow.com/questions/75112085/exclude-data-spec-ts-file-from-unit-testing,"['angular', 'typescript', 'unit-testing', 'ts-jest']",43,False,0,1
Unit Testing Thread Safe List in Swift,"<p>I have an AtomicList type:</p>
<pre><code>public struct AtomicList&lt;Element&gt; {
    public var values: [Element] = []
    private let queue = DispatchQueue(label: UUID().uuidString)
    
    public var last: Element? {
        self.queue.sync { return self.values.last }
    }
    
    public mutating func append(item: Element) {
        self.queue.sync {
            self.values.append(item)
        }
    }
}

</code></pre>
<p>And a flaky failing test that <em>should</em> validate that it's thread safe:</p>
<pre><code>class AtomicListTests: XCTestCase {
    func testReadingAndWritingOnDifferentThreads() {
        var arrayA = AtomicList&lt;Int&gt;()
        var arrayB = AtomicList&lt;Int&gt;()
        
        let expectation = expectation(description: &quot;thread safety test&quot;)
        expectation.expectedFulfillmentCount = 10000
        
        for i in 0..&lt;expectation.expectedFulfillmentCount {
            DispatchQueue.global().async {
                arrayA.append(item: i)
                if let last = arrayA.last {
                    arrayB.append(item: last)
                }
                expectation.fulfill()
            }
        }
        
        wait(for: [expectation], timeout: 5.0)
        XCTAssertEqual(arrayA.values.count, arrayB.values.count)
    }
}
</code></pre>
<p>I have 2 questions:</p>
<ol>
<li>Is this even a valid test to check whether this type is thread safe?</li>
<li>Why is the test occasionally failing with the error that 9999 is not equal to 10000 (i.e. the counts don't match)</li>
</ol>
<p>Note:
I noticed a couple solutions that fix this and make it pass the test such as:</p>
<ol>
<li>Changing AtomicList from a struct to a class</li>
<li>Changing var last to a mutating func</li>
<li>Synchronizing access to arrayA and arrayB in the test</li>
</ol>
<p>But I still don't fully understand why the existing code doesn't work, and why the first 2 solutions above make it pass.</p>
",https://stackoverflow.com/questions/75700337/unit-testing-thread-safe-list-in-swift,"['ios', 'swift', 'multithreading']",113,True,3,2
Using mocks in unit testing in Haskell?,"<p>Consider the following piece of code:</p>
<pre class=""lang-hs prettyprint-override""><code>data Slice = Slice
  { text :: String,
    color :: Color
  }

newtype Color = Color
  { string :: String
  }

mainList :: [FilePath] -&gt; [FilePath] -&gt; [String] -&gt; [[Slice]]
mainList somethingA somethingB codedLines = ...
</code></pre>
<p>The <code>Slice</code> record represents a result of decoding a string with ANSI escape codes.
Inside the <code>mainList</code> function I use some function, let's call it <code>categorize</code> that parses the <code>codedLines</code> (this represents a line of ANSI escape coded strings) parameter to <code>[[Slice]]</code>.</p>
<h3>First question:</h3>
<p>How would I write unit tests for the <code>mainList</code> function using the Quickcheck unit testing framework?
I am fairly new to Haskell. Now, if this had been some OOP language, I know what to do: have the class that has the <code>categorize</code> method passed as a parameter to the ctor of the class that has the <code>mainList</code> method and then mock my heart out of it using some mocking library or even write the mock manually. But what a man to do in Haskell, where there is no notion of classes?</p>
<h3>Second question:</h3>
<p>Maybe I can change the <code>mainList</code> function like follows:</p>
<pre class=""lang-hs prettyprint-override""><code>mainList :: [FilePath] -&gt; [FilePath] -&gt; ([String] -&gt; [[Slice]]) -&gt; [[Slice]]
</code></pre>
<p>But then, I would have to pass it a mock instead of the third parameter. Since Haskell is not an OOP language, is there even a notion of a mock? Is this idiomatic Haskell? Or maybe I'm mistakenly projecting OOP principles onto a functional language?</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/76086911/using-mocks-in-unit-testing-in-haskell,"['unit-testing', 'haskell', 'quickcheck', 'hunit']",92,True,2,1
Unit testing of destructive functions in lisp,"<p>The background here is that I have a non-destructive version of a function that I want to make destructive for performance reasons. However, writing unit tests gets challenging because lisp considers all quoted lists in the source code to be constants and changing those leads to undefined behaviour.</p>
<p>I'm using parachute as the unit testing framework</p>
<p>e.g.,</p>
<pre><code>(define-test suite-1
 (let ((start '((1 2) (3 4) (5 6)))
       (end '((7 1 2) (3 4) (5 6))))
  (is #'equal end (push 7 (car start))))
 (let ((start '((1 2) (3 4) (5 6)))
       (end '((8 1 2) (3 4) (5 6))))
  (is #'equal end (push 8 (car start)))))
</code></pre>
<p>This kinda fails because we end up pushing <code>8</code> onto the constant list <code>(1 2)</code> which eventually causes <code>(push 8 (car start))</code> to result in <code>(8 7 1 2)</code> instead of the expected <code>(8 1 2)</code></p>
<p>This isn't a problem with testing non-destructive functions because they don't modify constants. This is also not a problem outside of unit tests because I know that the original structure will no longer be needed.</p>
<p>I could replace the above with this ugly thing :-</p>
<pre><code>(let ((start (list (list 1 2) (list 3 4) (list 5 6))) ...
</code></pre>
<p>which then creates a proper non-constant list but it sure does make the code unreadable...</p>
<p>Any suggestions on how other people approach this?</p>
",https://stackoverflow.com/questions/75251279/unit-testing-of-destructive-functions-in-lisp,"['unit-testing', 'common-lisp', 'destructive-function', 'parachute']",111,True,2,2
Unit Testing in C scope pointer issue,"<p>I am trying to implement unit testing in C using Ceedling.</p>
<pre><code>struct Person *list;
/* TASK_FIND_BY */
void test_main_task_find_by_normal(void)
{
    char *string = (char *)malloc(sizeof(char));
    struct Person new_list_instance;
    struct Person *new_list = &amp;new_list_instance;
    ask_input_ExpectAndReturn(string);
    llist_find_by_ExpectAndReturn(list, string, new_list);
    llist_print_Expect(new_list);
    llist_remove_all_Expect(&amp;new_list);

    printf(&quot;\nOutside single: %p\n&quot;, new_list);
    printf(&quot;Outside double: %p\n&quot;, &amp;new_list);

    task_find_by(list);
}
</code></pre>
<pre><code>void task_find_by(struct Person *list)
{
    char *input = NULL;
    struct Person *new = NULL;

    printf(&quot;Input exact name/surname/email/phone: &quot;);
    input = ask_input();
    if (input == NULL) {
        printf(&quot;Error!&quot;);
        return;
    }
    new = llist_find_by(list, input);
    if (new != NULL)
        llist_print(new);
    else 
        printf(&quot;Address not found!\n&quot;);
    
    printf(&quot;\nInside single: %p\n&quot;, new);
    printf(&quot;Inside double: %p\n&quot;, &amp;new);
    
    free(input);
    llist_remove_all(&amp;new);
}

</code></pre>
<p>I expect the function inside <code>task_find_by</code> to be called with the same argument as here: <code>llist_remove_all_Expect(&amp;new_list)</code>.
But the actual function is called with the address of <code>new</code> pointer, where <code>new</code> holds the <code>new_list</code>. Since <code>new_list</code> and <code>new</code> are different pointers their addresses are different. Is there any way to test the called argument without changing the implementation of <code>task_find_by</code> function?</p>
<pre><code>  - &quot;Outside single: 0x7ffc2e3c03d0&quot;
  - &quot;Outside double: 0x7ffc2e3c03c0&quot;
  - &quot;Inside single: 0x7ffc2e3c03d0&quot;
  - &quot;Inside double: 0x7ffc2e3c0398&quot;
</code></pre>
",https://stackoverflow.com/questions/76208999/unit-testing-in-c-scope-pointer-issue,"['c', 'unit-testing', 'pointers', 'ceedling']",98,True,2,2
Unit testing streamed filed download with Jest,"<p>I have a function that takes an array of URLs to images, loops through them and downloads them to a local directory written in typescript. I am trying write a unit test for the function in Jest and running into issue with mocking some parts of it. In the code below, <code>filepath</code> is the location the file is being written to and <code>url</code> is the URL of the current image.</p>
<pre class=""lang-js prettyprint-override""><code>const finished = promisify(stream.finished);
const writer = fs.createWriteStream(filepath);

axios({
    method: 'get',
    url: url,
    responseType: 'stream'  // Make the response a stream
}).then(async (response) =&gt; {
    response.data.pipe(writer);  // Send the response stream to the writable file stream
    await finished(writer);  // Watch the stream for being finished/any errors
}).catch(error =&gt; {
    console.error('Image Download');
    console.error(error);
    process.exit(1);
});
</code></pre>
<p>How would you properly mock the axios stream, the fs.createWriteStream, and the stream.finished functions? I am already using <code>axios-mock-adapter</code> for mocking axios in other unit tests where the code is just getting a response from an API and not streaming a file.</p>
",https://stackoverflow.com/questions/75315448/unit-testing-streamed-filed-download-with-jest,"['typescript', 'unit-testing', 'jestjs', 'mocking', 'ts-jest']",65,False,1,0
Unit Testing of Published object in Swift,"<p>I'm struggling with unit testing of Published object.</p>
<p>I have a viewmodel class as below</p>
<pre><code>class MovieListViewModel {
    @Published public private(set) var arrayOfMovies: [Movie] = []
    @Published private var arraofFavoriteMoviesID: [FavouriteMovieID] = []

     init(request: NetworkServiceProtocol) {
        addSubscribers()
        callServicesInSequence()
    }

    func addSubscribers() {
        $arrayOfMovies.combineLatest($arraofFavoriteMoviesID)
            .debounce(for: 0.0, scheduler: DispatchQueue.main)
            .sink { [weak self] (_, _) in
                self?.fetchWachedMovies()
                self?.fetchTobeWatchedMovies()
                self?.fetchFavoriteMovies()
            }
            .store(in: &amp;subscriptions)
    }

    func callServicesInSequence() {/*..service request...*}
}
</code></pre>
<p>Here addSubscribers() listen for any changes happening in <code>arrayOfMovies</code> or <code>arraofFavoriteMoviesID</code> and works perfectly is the app.</p>
<p>But when I tried to mock and write unit test cases. Any chnages happening in <code>arrayOfMovies</code> or <code>arraofFavoriteMoviesID</code> does not make any effect (addSubscribers's body never get called).</p>
<p>Can any one please guide me what am I doing wrong while writing unit test cases for Combine/Published objects.</p>
<p>Please let me know if more clarification required.</p>
",https://stackoverflow.com/questions/75162546/unit-testing-of-published-object-in-swift,"['ios', 'swift', 'xcode', 'combine']",398,True,1,1
Unit-testing http request retry with httptest,"<p>I'm struggling to write a unit test for a component called <code>HttpRequest</code> that wraps HTTP requests and handles response unmarshalling. Recently, I added a feature to this component that allows it to retry an HTTP request if it encounters a &quot;connection refused&quot; error on the first attempt.</p>
<p>To use the HttpRequest component, I call it once like this: <code>user, err := HttpRequest[User](config)</code>. The config parameter contains all the necessary information to execute the request, such as the URL, method, timeout, retry count, and request body. It also unmarshals the response body to an instance of the specified type (<code>User</code> in this case)</p>
<p>The problem arises when I try to test the scenario where the initial request fails with a &quot;connection refused&quot; error, but the second attempt is successful. The retries happen internally within the component, so I only make a single call to the component.</p>
<p>I've found it challenging to create a unit test for this scenario because, in order for a request to fail with &quot;connection refused,&quot; there needs to be no listener on the port being called. The issue is that when using <code>httptest</code>, it always listens on a port when an instance is created, even with <code>httptest.NewUnstartedServer</code>. Consequently, after the <code>httptest</code> instance is created, I will never encounter a &quot;connection refused&quot; error in my client code.</p>
<p>However, before creating the <code>httptest</code> instance, I don't know which port it will be listening on. <code>httptest</code> always picks a random port, and there is no way to specify one programmatically. This means I can't make the HttpRequest call before creating the <code>httptest</code> instance.</p>
<p>Does anyone have any ideas on how to effectively unit test such a scenario?</p>
",https://stackoverflow.com/questions/76341798/unit-testing-http-request-retry-with-httptest,"['unit-testing', 'go']",35,True,1,1
Unit testing a Powershell Azure Function App?,"<p>I have an Azure Function written in Powershell:</p>
<pre><code>function Invoke {
    param($Request)
    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
        StatusCode = [HttpStatusCode]::OK
        Body       = &quot;Hello!&quot;
    })
}
</code></pre>
<p>I have a Pester unit test for this function:</p>
<pre><code>Describe &quot;Invoke&quot; {
    It &quot;Returns a 200 response&quot; {
        $Response = Invoke -Request [HttpRequestContext]@{}
        $Response.StatusCode | Should Be ([HttpStatusCode]::OK)
    }
}
</code></pre>
<p>Running this test yields:</p>
<pre><code>Describing Invoke
  [-] Returns a 200 response 4ms (3ms|1ms)
   RuntimeException: Unable to find type [HttpRequestContext].
</code></pre>
<p>Presumably the PowerShellWorker injects these types when it runs the script and so they are not available when Pester invokes the test. In falling order of desirability, how can I:</p>
<ol>
<li>Import these types in my test run? For example, is there a module I could import?</li>
<li>Inject mocks of these types? Pester has support for creating mocks of objects, but not inject types?</li>
<li>Ask the PowerShellWorker to invoke the function from my test? (I could probably invoke <code>func host start</code> and write integration tests instead, but I would really prefer to have unit tests if possible.)</li>
</ol>
<p>I'd appreciate any lead that can help me with this.</p>
<p>UPDATE: As pointed out in comments, I had deleted a <code>param()</code> when compacting my example. To clarify, the idea is to support type annotations in both test and production code.</p>
<p>UPDATE2: Corrected spelling as per mclayton's suggestion.</p>
",https://stackoverflow.com/questions/76338754/unit-testing-a-powershell-azure-function-app,"['powershell', 'unit-testing', 'azure-functions']",125,True,1,2
VSTO Outlook Addin Unit Testing with xUnit,"<p>I was having some trouble getting unit testing with xUnit to work in Visual Studio (2019) for my VSTO Outlook addin project.  I had reviewed the following SO questions and answers:</p>
<p><a href=""https://stackoverflow.com/questions/45121396/vsto-unit-testing-office-addin-in-c-sharp-net-via-requestcomaddinautomationserv?r=SearchResults"">VSTO Unit Testing Office AddIn in C# .NET via RequestComAddInAutomationService</a></p>
<p><a href=""https://stackoverflow.com/questions/50743180/unit-testing-excel-addin-using-vsto?r=SearchResults"">Unit testing Excel addin using VSTO</a></p>
<p><a href=""https://stackoverflow.com/questions/30906070/unit-testing-vsto-projects?r=SearchResults"">Unit Testing VSTO projects</a></p>
<p>However, in the end it turned out that I had simply not properly created the xUnit test project.</p>
<p><strong>Unlike the questions/solutions listed above, I did NOT need to use RequestComAddinAutomationService, nor have to setup any classes with COM Interop attributes or set &quot;Register for COM interop&quot; to get my tests running.</strong></p>
<p>My xUnit project is capable of both launching Outlook (just like debugging does), and accessing my classes and methods created inside of my addin project.   I'm not sure why I am able to get xUnit working with my Outlook VSTO addin without the COM interop stuff (see Note 2) -- but it works, so I thought I would share a step-by-step description of how I got it working in my Answer below.</p>
<p>Note 1:
I created a new question/answer for this, since none of the questions above involved an Outlook VSTO addin, but rather were for Excel and Powerpoint.</p>
<p>Note 2:
Perhaps the COM interop code is not needed because this is an Outlook addin versus Excel or Powerpoint as in the questions listed above?  Or perhaps because I am using xUnit, while I believe the testing framework in most of the questions above is MS Native Unit Testing?</p>
",https://stackoverflow.com/questions/75739113/vsto-outlook-addin-unit-testing-with-xunit,"['c#', 'unit-testing', 'outlook', 'vsto', 'xunit']",61,True,1,1
Unit testing NgRx effect as a function,"<p>I want to unit test functional effect as described here</p>
<pre><code>export const loadUsers = createEffect(
  (actions$ = inject(Actions), usersService = inject(UsersService)) =&gt; {
    return actions$.pipe(
      ofType(userActions.getUser),
      exhaustMap(() =&gt; {
        return usersService.getAll().pipe(
          map((users) =&gt; userActions.usersLoadedSuccess({ users })),
    
        );
      })
    );
  },
  { functional: true }
);
</code></pre>
<p><a href=""https://ngrx.io/api/effects/createEffect#functional-effects"" rel=""nofollow noreferrer"">https://ngrx.io/api/effects/createEffect#functional-effects</a></p>
<p>How one would unit test this functional effect.
Kindly note there is no injectable or class</p>
<p>I am expecting a way to test this functional effect.
I tried below approach but the effect is not getting triggered at all.</p>
<pre><code>import { HttpClientTestingModule } from '@angular/common/http/testing';
import { Observable, of } from 'rxjs';
import { TestBed } from '@angular/core/testing';
import { provideMockActions } from '@ngrx/effects/testing';
import { MockProvider } from 'ng-mocks';
import { Actions } from '@ngrx/effects';
import { userActions } from './user-store';
import { MockStore, provideMockStore } from '@ngrx/store/testing';
import { UsersService } from './users.service';
import { loadUsers } from './user.effects';

describe('Offer Effects', () =&gt; {
    let actions$: Observable&lt;unknown&gt;;
    let store: MockStore;
    let userService: UsersService;
    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [loadUsers, MockProvider(UsersService), provideMockStore(), provideMockActions(() =&gt; actions$)],
        });

        actions$ = TestBed.inject(Actions);
        store = TestBed.inject(MockStore);
        userService = TestBed.inject(UsersService);
    });

    it('should test load users effect', async () =&gt; {
        actions$ = of({
            type: userActions.getUser,
        });
        const users = { name: 'Test', surname: 'Data' };
        jest.spyOn(userService, 'getAll').mockReturnValue(of(users));
        const spy = jest.spyOn(userActions, 'usersLoadedSuccess');
        await loadUsers;
        expect(spy).toHaveBeenCalledWith({ users });
    });
});

</code></pre>
",https://stackoverflow.com/questions/75449942/unit-testing-ngrx-effect-as-a-function,"['angular', 'jestjs', 'jasmine', 'ngrx', 'ngrx-effects']",251,True,1,1
Importing a transpiled package for unit testing,"<p>I have a TypeScript package that is shipped transpiled to JS with rollup. The package uses <code>type: module</code> and rollup produces the following files:</p>
<pre><code>dist/cjs/index.cjs
dist/es6/index.mjs
dist/browser/index.js
dist/types.d.ts
</code></pre>
<p>My unit testing is also in TypeScript so that I can test the typings. I use mocha with all the special configuration:</p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;spec&quot;: &quot;test/*.test.@(cjs|mjs|ts)&quot;,
  &quot;require&quot;: [
    &quot;ts-node/register&quot;
  ],
  &quot;loader&quot;: &quot;ts-node/esm&quot;
}
</code></pre>
<p>The problem is that I cannot easily import this package from the unit testing. I cannot import <code>'..'</code> or use <code>tsconfig-paths</code> since <code>type: module</code> disallows directory imports. If I import <code>../dist/cjs/index.cjs</code> I lose the typings. Does anyone see any way I could import the compiled package with the typings?</p>
<p>Currently the only solution is to drop <code>type: module</code> and use <code>import from '..'</code> - which means I am going back 5 years.</p>
<p>The package is <a href=""https://github.com/mmomtchev/query-mvt"" rel=""nofollow noreferrer"">https://github.com/mmomtchev/query-mvt</a> if anyone is interested. I have currently dropped <code>type: module</code>.</p>
",https://stackoverflow.com/questions/75550544/importing-a-transpiled-package-for-unit-testing,['typescript'],25,False,0,0
Unit Testing with Mockito &amp; Firebase Kotlin,"<p>I am trying to write a unit tests to my kotlin class that writes and reads values from Firebase. I tried in different ways of writing the tests but always got errors with firebase.
This is my Repository Class:</p>
<pre><code>package mainPackage.model

import com.google.firebase.firestore.FirebaseFirestore
import android.util.Log
import com.google.firebase.firestore.FirebaseFirestoreException
import mainPackage.utils.Checks

const val TAG = &quot;FIRESTORE&quot;

class RepositoryMockup {

    //--------------------------------

//Firebase functions

fun writeNewUser(pass: String, email: String, isATeacher: Boolean?) {
    val database = FirebaseFirestore.getInstance()
    val myRef = database.collection(&quot;Users&quot;).document(email)

    val newUser = hashMapOf(
        &quot;is_a_teacher&quot; to isATeacher,
        &quot;pass&quot; to pass
    )

    myRef.set(newUser)
        .addOnSuccessListener { Log.d(TAG, &quot;User successfully added&quot;) }
        .addOnFailureListener { e -&gt; Log.w(TAG, &quot;Error writing user&quot;, e) }

}

//CHECKED AND FIXED

fun userLogin(user: User, callback: (Checks) -&gt; Unit) {
    val database = FirebaseFirestore.getInstance()
    val myRef = database.collection(&quot;Users&quot;).document(user.email.toString())
    myRef.get()
        .addOnSuccessListener { document -&gt;
            if (document != null &amp;&amp; document.exists()) {
                val pass = document.get(&quot;pass&quot;) as String
                if (pass == user.password) {
                    callback(Checks.PASSED)
                } else {
                    callback(Checks.FAILED_CHECK)
                }
                Log.d(TAG, &quot;Pass successfully checked&quot;)
            } else {
                callback(Checks.NEW_USER_CREATED)
                Log.d(TAG, &quot;Is empty&quot;)
                writeNewUser(user.password.toString(), user.email.toString(), user.isATeacher)
            }
        }
        .addOnFailureListener { exception -&gt;
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, &quot;Error getting document: &quot;, exception)
            }
            callback(Checks.FAILED_CHECK)
        }
}

fun userLoginTest(user: UserTest, callback: (Checks) -&gt; Unit) {
    val database = FirebaseFirestore.getInstance()
    val myRef = database.collection(&quot;Users&quot;).document(user.email.toString())
    myRef.get()
        .addOnSuccessListener { document -&gt;
            if (document != null &amp;&amp; document.exists()) {
                val pass = document.get(&quot;pass&quot;) as String
                if (pass == user.pass) {
                    callback(Checks.PASSED)
                } else {
                    callback(Checks.FAILED_CHECK)
                }
                Log.d(TAG, &quot;Pass successfully checked&quot;)
            } else {
                callback(Checks.NEW_USER_CREATED)
                Log.d(TAG, &quot;Is empty&quot;)
                writeNewUser(user.pass.toString(), user.email.toString(), user.isATeacher)
            }
        }
        .addOnFailureListener { exception -&gt;
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, &quot;Error getting document: &quot;, exception)
            }
            callback(Checks.FAILED_CHECK)
        }
}




//CHECKED AND FIXED

fun readNameSurnameByEmail(email: String, callback: (String) -&gt; Unit){
    val database = FirebaseFirestore.getInstance()
    val myRef = database.collection(&quot;Users&quot;).document(email)

    myRef.get()
        .addOnSuccessListener { document -&gt;
            if (document != null) {
                val fieldValue = document.get(&quot;name_surname&quot;) as String
                callback(fieldValue)
                Log.d(TAG, &quot;Name and surname successfully read&quot;)
            } else {
                Log.d(TAG, &quot;Is empty&quot;)
            }
        }
        .addOnFailureListener { exception -&gt;
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, &quot;Error getting document: &quot;, exception)
            }
        }
}

//CHECKED

fun readIsATeacherByEmail(email: String): Boolean {
    val database = FirebaseFirestore.getInstance()
    val myRef = database.collection(&quot;Users&quot;).document(email)
    var fieldValue = false


    myRef.get()
        .addOnSuccessListener { document -&gt;
            if (document != null) {
                fieldValue = document.get(&quot;is_a_teacher&quot;) as Boolean
                Log.d(TAG, &quot;Name and surname successfully read&quot;)
            } else {
                Log.d(TAG, &quot;Is empty&quot;)
            }
        }
        .addOnFailureListener { exception -&gt;
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, &quot;Error getting document: &quot;, exception)
            }
        }
    return fieldValue
}

//CHECKED

fun writeOfficeHoursInstance(email: String, timeFrom: String, timeTo: String) {
    val database = FirebaseFirestore.getInstance()
    var id = &quot;&quot;
    val myRef = database.collection(&quot;OfficeHoursInstance&quot;).document()
    id = myRef.id
    val newInstance = hashMapOf(
        &quot;email&quot; to email,
        &quot;time_from&quot; to timeFrom,
        &quot;time_to&quot; to timeTo,
        &quot;id&quot; to id
    )

    myRef.set(newInstance)
        .addOnSuccessListener { Log.d(TAG, &quot;Instance successfully added&quot;) }
        .addOnFailureListener { e -&gt; Log.w(TAG, &quot;Error writing Instance&quot;, e) }



}

//CHECKED AND FIXED

fun readOfficeHoursInstanceTeacher(email: String, callback: (MutableList&lt;OfficeHoursInstance&gt;) -&gt; Unit){
    var timeFrom = &quot;&quot;
    var timeTo = &quot;&quot;
    var userEmail = &quot;&quot;
    var code = &quot;&quot;
    var list = mutableListOf&lt;OfficeHoursInstance&gt;()
    val database = FirebaseFirestore.getInstance()
    val ref = database.collection(&quot;OfficeHoursInstance&quot;)
        .whereEqualTo(&quot;email&quot;, email)
    ref.get()
        .addOnSuccessListener { documents -&gt;
            for (document in documents) {
                timeFrom = document.get(&quot;time_from&quot;) as String
                timeTo = document.get(&quot;time_to&quot;) as String
                userEmail = document.get(&quot;email&quot;) as String
                code = document.get(&quot;id&quot;) as String
                list.add(OfficeHoursInstance(userEmail, timeFrom, timeTo, code))
                Log.d(TAG, &quot; Time instance successfully read&quot;)
            }
            callback(list)
        }
        .addOnFailureListener { exception -&gt;
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, &quot;Error getting document: &quot;, exception)
            }
        }
}

fun updateUserOfficeHoursList(email: String, code: String){
    val database = FirebaseFirestore.getInstance()
    val ref = database.collection(&quot;Users&quot;).document(email)
    var list = &quot;&quot;

    ref.get()
        .addOnSuccessListener { document -&gt;
            if (document != null) {
                list = document.get(&quot;office_hours_list&quot;) as String
                Log.d(TAG, &quot;office_hours_list successfully read&quot;)
            } else {
                Log.d(TAG, &quot;Is empty&quot;)
            }
        }
        .addOnFailureListener { exception -&gt;
            if (exception is FirebaseFirestoreException) {
                Log.e(TAG, &quot;Error getting document: &quot;, exception)
            }
        }
    if (list.isEmpty()){
        list = code
    }
    else {
        list + &quot;, &quot; + code
    }
    ref.update(&quot;office_hours_list&quot;, list)
}
</code></pre>
<p>}</p>
<p>Can you give me a clue how to write a unit test for my db methods?
Or show me the structure?</p>
<p>Here is what I have but it is not working:</p>
<pre><code>package mainPackage.tests

import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.FirebaseFirestoreException
import mainPackage.model.RepositoryMockup
import mainPackage.model.UserTest
import mainPackage.utils.Checks
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations

class RepositoryMockupTest {

    private lateinit var repositoryMockup: RepositoryMockup

    @Mock
    private lateinit var firebaseFirestore: FirebaseFirestore

    @Mock
    private lateinit var documentSnapshot: DocumentSnapshot

    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
        repositoryMockup = RepositoryMockup()
    }

    @Test
    fun testWriteNewUser() {
        repositoryMockup.writeNewUser(&quot;password&quot;, &quot;email&quot;, true)
        Mockito.verify(firebaseFirestore).collection(&quot;Users&quot;).document(&quot;email&quot;)
    }

    @Test
    fun testUserLogin_Passed() {
        val user = UserTest(&quot;man.man@pwr.edu.pl&quot;, &quot;password123&quot;, true)
        Mockito.`when`(firebaseFirestore.collection(&quot;Users&quot;).document(&quot;email&quot;).get())
            .thenReturn(documentSnapshot)
        Mockito.`when`(documentSnapshot.exists()).thenReturn(true)
        Mockito.`when`(documentSnapshot.get(&quot;pass&quot;)).thenReturn(&quot;password&quot;)
        var check = Checks.FAILED_CHECK
        repositoryMockup.userLoginTest(user) {
            check = it
        }
        assertEquals(Checks.PASSED, check)
    }

    @Test
    fun testUserLogin_FailedCheck() {
        val user = UserTest(&quot;man.man@pwr.edu.pl&quot;, &quot;wrong_password&quot;, true)
        Mockito.`when`(firebaseFirestore.collection(&quot;Users&quot;).document(&quot;user.email&quot;).get())
            .thenReturn(documentSnapshot)
        Mockito.`when`(documentSnapshot.exists()).thenReturn(true)
        Mockito.`when`(documentSnapshot.get(&quot;pass&quot;)).thenReturn(&quot;password&quot;)
        var check = Checks.PASSED
        repositoryMockup.userLoginTest(user) {
            check = it
        }
        assertEquals(Checks.FAILED_CHECK, check)
    }

//    @Test
//    fun testUserLogin_NewUserCreated() {
//        val user = UserTest(&quot;email&quot;, &quot;password&quot;, true)
//        Mockito.`when`(firebaseFirestore.collection(&quot;Users&quot;).document(&quot;user.email&quot;).get())
//            .thenReturn(documentSnapshot)
//        Mockito.`when`(documentSnapshot.exists()).thenReturn(false)
//        var check = Checks.PASSED
//        repositoryMockup.userLoginTest(user) {
//            check = it
//        }
//        assertEquals(Checks.NEW_USER_CREATED, check)
//    }
}

private fun Any.thenReturn(documentSnapshot: DocumentSnapshot) {

}
</code></pre>
",https://stackoverflow.com/questions/75259993/unit-testing-with-mockito-firebase-kotlin,"['android', 'firebase', 'kotlin']",215,False,0,0
"Angular Karma/jasmine Unit testing, InjectorToken , RxJs","<p>Im a Angular newbie and starting to write Unit Tests.
I have a simple Component, which loads data from RxJs - Subject.
Im not able to initialize the spec.ts file for testing does anyone now how to do
the correct implementation ?</p>
<h1>Thats my Component</h1>
<pre><code>import { Component, Inject, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { fluxDispatcherToken } from 'src/app/shared/helpers/flux.configuration';
import { FluxStore } from 'src/app/shared/services/flux-store';
import { Account } from 'src/app/shared/types/account';
import { FluxAction, FluxActionTypes } from 'src/app/shared/types/actions.type';
import { CsvTransactionFormComponent } from './csv-transaction-form/csv-transaction-form.component';
import { ManualTransactionFormComponent } from './manual-transaction-form/manual-transaction-form.component';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.scss']
})
export class AccountComponent implements OnInit, OnDestroy {
  @ViewChild('manualTransactionModal') manualTransactionModal!: ManualTransactionFormComponent
  @ViewChild('csvTransactionModal') csvTransactionModal!: CsvTransactionFormComponent
  @Input() activeAccounts: Account[] = []

  accounts: Account[] = []
  selectedAccount?: Account
  data : string = 'noentry'
  private subscription: Subscription[] = []

  constructor(@Inject(fluxDispatcherToken) private dispatcher: Subject&lt;FluxAction&gt;, public store: FluxStore){}

  ngOnInit() {
    this.dispatcher.next(new FluxAction(FluxActionTypes.Load))
    this.subscription.push(this.store.Accounts.subscribe((data) =&gt; {
      if (data.length &gt; 0) {
        this.data = 'data'
        this.accounts = data;
      }
      if (data.length === undefined) {
        this.data = 'isloading'
      }
      if (data.length === 0) {
        this.data = 'nodata'
        this.accounts = [];
      }
    }))
  }

  openManualTransactionModal(account: Account) {
    this.selectedAccount = account
    this.manualTransactionModal.manualtransactionform.nativeElement.classList.add('is-active')
  }

  openCsvTransactionModal(account: Account) {
    this.selectedAccount = account
    this.csvTransactionModal.modal.nativeElement.classList.add('is-active')
  }

  ngOnDestroy() {
    this.subscription.forEach((subscription) =&gt; {subscription.unsubscribe()})
  }
}
</code></pre>
<h1>And this is the Configuration for the  @Inject(fluxDispatcherToken)</h1>
<pre><code>import { InjectionToken } from '@angular/core'
import { Subject } from 'rxjs'
import { FluxAction } from '../types/actions.type'

export const fluxDispatcherToken = new InjectionToken('fluxActions')

export const fluxActionSubject = new Subject&lt;FluxAction&gt;()

export const FLUX_CONFIG = [
    { provide: fluxDispatcherToken, useValue: fluxActionSubject },
]
</code></pre>
<h1>Here is my test file spec.ts</h1>
<pre><code>import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from &quot;@angular/core/testing&quot;;
import { AccountComponent } from &quot;./account.component&quot;;
import { FluxStore } from 'src/app/shared/services/flux-store';
import { fluxDispatcherToken } from 'src/app/shared/helpers/flux.configuration';
import { FluxAction, FluxActionTypes } from 'src/app/shared/types/actions.type';
import { Subject } from 'rxjs';



describe(&quot;AccountComponent&quot;, () =&gt; {
  let component: AccountComponent;
  let fixture: ComponentFixture&lt;AccountComponent&gt;;
  let Store: FluxStore;
  let dispatcher: Subject&lt;FluxAction&gt;;

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: [AccountComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [
        { provide: FluxStore, useValue: {} },
        { provide: fluxDispatcherToken, useValue: new Subject&lt;FluxAction&gt;() },
      ],
      imports: []
    }).compileComponents();
  });

 

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(AccountComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    Store = TestBed.inject(FluxStore);


  });

  describe('method1', () =&gt; {
    it('should ...', () =&gt; {
      expect(component).toBeTruthy();
    });
  });


})
</code></pre>
<p>When I start to test there is a failure :
TypeError: Cannot read properties of undefined (reading 'subscribe')</p>
",https://stackoverflow.com/questions/75071540/angular-karma-jasmine-unit-testing-injectortoken-rxjs,"['angular', 'rxjs', 'karma-jasmine', 'flux', 'angular-unit-test']",40,False,0,0
iOS unit testing async function not called,"<p>How to test that an async function is not called in iOS unit testing?</p>
<p>I know how to test that an async function IS called: by using XCTestExpectation and expectation fulfill. But how to test that a function is not called?</p>
<p>Context: There are four potential async function within a launcher, and with the specific argument, one of these functions should be called and the other three shouldn't. I know how to write a unit test to make sure that the function that needs to be called is called, but don't know how to write a test to test if the other three functions are not touched. Thanks for helping!</p>
",https://stackoverflow.com/questions/75679458/ios-unit-testing-async-function-not-called,"['ios', 'swift']",42,True,0,1
Disable Authorization filter extending TypeFilterAttribute unit testing,"<p>for below code I want to do setup in ConfigureTestServices so that this particular attribute gets disabled while running the test.</p>
<pre><code>`public class AuthorizePermissionAttribute : TypeFilterAttribute
    {
        public AuthorizePermissionAttribute(Type type, params string[] permissions) : base(typeof(AuthorizePermissionPreferenceFilter&lt;&gt;).MakeGenericType(type))
        {
            Arguments = new object[] { permissions };
        }
    }
    public class AuthorizePermissionPreFilter&lt;T&gt; : AuthorizePermissionFilter, IAsyncAuthorizationFilter where T : IPrefScope
    {
        public AuthorizePermissionPrefFilter(
            IRequestContext context,
            IPermissionProvider permissionProvider,
            ILogger&lt;AuthorizePermissionPreFilter&lt;T&gt;&gt; logger,
            IOptionsSnapshot&lt;CoreAppConfiguration&gt; config,
            string[] permissions) : base(context, permissionProvider, logger, config, permissions)
        {

        }
        public new async Task OnAuthorizationAsync(AuthorizationFilterContext authContext)
        {

                await base.OnAuthorizationAsync(authContext);
            
        }
}`
</code></pre>
<p>This has been added through middleware          <code>app.UseEndpoints(endpoints =&gt; { endpoints.MapControllers(); });</code></p>
<p>I tried using MOQ, Moq.AutoMock with xunit but nothing helped</p>
",https://stackoverflow.com/questions/75463959/disable-authorization-filter-extending-typefilterattribute-unit-testing,"['asp.net', 'unit-testing', '.net-core', 'moq', 'automoq']",26,False,0,0
Unit testing service method in Spring Boot,"<p>I have been doing unit testing with JUnit 5 and Mockito for the following code that I am going to show you, but it is not working correctly. I want to evaluate the successful case.</p>
<pre><code>public Maybe &lt; MyResponse&gt; generate(String numberValue) {
  return Maybe.just(numberValue)
        .filter(number -&gt; number.length() == Constants.REQUEST_REQUIRED) //R_R = 16
        .flatMap(number -&gt; MyUtils.generate())
        .map(MyMapper::createResponse)
        .switchIfEmpty(Maybe.error(MyExceptioManager.throwException400(...)));
}
</code></pre>
<p>I tried converting the static methods to instance methods and then invoked them with @Mock, but it didn't work. How can I do this?</p>
<p>I did this:</p>
<pre><code>@Test
void generate() {
    String numberValue = &quot;1234567891234567&quot;;
    // when(myUtils.generate()).thenReturn(any()); 
    when(numberValue.length()).thenReturn(eq(16));
    when(myMapper.createResponse(anyString())).thenReturn(any(MyResponse.class));

    myService.generate(numberValue )
             .test()
             .assertNoErrors()
             .assertComplete()
             .assertValue(myResponse -&gt; myResponse.getCode().equals(&quot;1234&quot;));
}
</code></pre>
<p>error:</p>
<blockquote>
<p>org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);</p>
</blockquote>
",https://stackoverflow.com/questions/75857012/unit-testing-service-method-in-spring-boot,"['java', 'spring', 'mockito', 'rx-java', 'junit5']",70,False,0,1
Unit testing a lambda function in Java,"<p>I have a lambda function written like this:</p>
<pre><code>@Bean
    public Function&lt;Request, Audience&gt;
    fromAudienceDTOToAudienceMapper(
            final Function&lt;ExpressionDto, Expression&gt; fromExpressionDtoToExpression,
            final Function&lt;SchemaDto, Schema&gt; fromSchemaDtoToSchema,
            final Function&lt;PolicyDTO, Policy&gt;
                    fromDataGovernancePolicyDtoToDataGovernancePolicy
            )
            
</code></pre>
<p>As this is a bean and a lambda function, I am unable to come up with a way using Junit/Mockito to actually test this out. If I instantiate the function, it will have its own apply() and then the original code will not get called.
I'm inclining towards converting this to a class itself, but thought of finding a way to unit test this out directly. Any help is appreciated!</p>
",https://stackoverflow.com/questions/75475912/unit-testing-a-lambda-function-in-java,"['java', 'junit', 'mockito']",60,False,0,0
Unit testing module federated redux toolkit store,"<p>I created a module federated redux store and inside this store I have a useStore() function which I then call into my other application but when I to test the component using react-testing and jest that calls useStore() I get following error:</p>
<pre><code>TypeError: (0 , useStore) is not a function
</code></pre>
<p>Redux function:</p>
<pre><code>export function useStore() {
  const selectD = useAppSelector((state) =&gt; state.selectD);
  const selectT= useAppSelector((state) =&gt; state.t);
  const dispatch = useAppDispatch();
  return {
    selectD,
    selectT,
    ... more code  
  };
}
</code></pre>
<p>Inside other app I call it as so:</p>
<pre><code>import {  useStore } from &quot;store/store&quot;
function SimpleComponent() {
  // GRAB VARIABLES FROM MWTC-5 REDUX STORE
  const {selectDrawer: {isOpen}, selectTrack} = useStore();
  ... other code 
}
</code></pre>
<p>The app works great when I run npm run start but the problem is testing the SimpleComponent component that calls useStore();</p>
<p>How would I be able to pass this test?
Thank you in advance!</p>
",https://stackoverflow.com/questions/76048176/unit-testing-module-federated-redux-toolkit-store,"['reactjs', 'jestjs', 'webpack-module-federation']",42,False,0,1
DynamicTestModule throws error on angular unit testing,"<p>I'm currently creating a unit testing with Karma and Jasmine as:</p>
<pre><code>describe('ProfileListComponent', () =&gt;  {
let component: ProfileListComponent;

beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
        imports: [
            [RouterModule.forRoot([])],
            FormsModule
        ],
        declarations: [
            ProfileListComponent,
            ProfilesFiltersComponent,
            DatatableComponent,
            ProfileImagePopoverComponent,
            NgbHighlight,
            NgbRating,
            PaginationFooterComponent
        ],
        providers: []
    }).compileComponents();

    TestBed.configureTestingModule({
        declarations: [ ProfileListComponent ]
    })
    .createComponent(ProfileListComponent);
}));


it('should be 4', async(() =&gt; {
    expect(component.add(2,2)).toEqual(4);
}))

});
</code></pre>
<p>The profile list component has many childs, which is why I imported them on <code>declarations</code>. The <code>ProfilesFiltersComponent</code> uses angular Forms as:</p>
<p><strong>HTML:</strong></p>


<p><strong>TS</strong></p>
<pre><code>export class ProfilesFiltersComponent implements OnInit {
 filterForm: FormGroup;
}
</code></pre>
<p>So, the testing asking me for the form group as:</p>
<blockquote>
<p>Can't bind to 'formGroup' since it isn't a known property of 'form'</p>
</blockquote>
<p>So I added it to <code>declarations</code> on the testing as:</p>
<pre><code> declarations: [
    ...
    FormGroup
    ]
</code></pre>
<p>But now it is throwing a new error:</p>
<blockquote>
<p>Failed: Unexpected value 'FormGroup' declared by the module
'DynamicTestModule'. Please add a @Pipe/@Directive/@Component
annotation.</p>
</blockquote>
<p>That I have no idea how to solve; what am I doing wrong?</p>
",https://stackoverflow.com/questions/75154122/dynamictestmodule-throws-error-on-angular-unit-testing,"['angular', 'typescript', 'jasmine', 'karma-jasmine']",53,False,0,1
Capture input parameters for Java Unit Testing,"<p>I am working with two components, say A and B. Java development takes place in component B. I managed to modify the relevant Java code, generated JAR using Maven, and deployed it to the run-time instance. All is good.</p>
<p>Component A will invoke classes and methods in B. One method, named say, <code>processNode()</code> in B takes the input of type <code>org.w3c.dom.Node</code>. The input is generated in the run-time instance in A. For example, the code in A will invoke the code in B as follows:</p>
<pre><code>... This is the code of A
... display form
... accept input
... convert the input to an object of type org.w3c.dom.Node
... org.w3c.dom.Node inp = ....
   B.Solution sol = new B.Solution();
   sol.processNode(inp);
...
...
</code></pre>
<p>My objective is to build a unit test and hard-code the value of the variable <code>inp</code> in the unit test to make the development cycle more efficient. This will help me avoid the cycle to code, build, copy the jar to the instance, restart the instance, start the application, provide the input, and check the log ... it is too long.</p>
<p>If I can somehow intercept the value of the input <code>inp</code> in component B and save it in text format for example, then I can hard-code it in the unit test, and convert it to the type <code>org.w3c.dom.Node</code> before invoking <code>B.solution.processNode()</code></p>
<p>I can see the value of <code>inp</code> in the logs generated by the component <code>A</code> as follows:</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;TskDta&gt;
    &lt;fileNamePath&gt;\path\to\file\filename.json&lt;/fileNamePath&gt;
    &lt;fileData&gt;{&amp;#xd;
    &quot;TranNumber&quot;: 12345,&amp;#xd;
    &quot;PropNumber&quot;: 12345,&amp;#xd;
    &quot;DateSigned&quot;: &quot;2020-04-28T16:31:51.8937987Z&quot;,&amp;#xd;
    &quot;ValuatType&quot;: &quot;002&quot;,&amp;#xd;
    &quot;BondAmt&quot;: 150000.0,&amp;#xd;
    &quot;TtlDNumber&quot;: &quot;B2005-rexsd&quot;,&amp;#xd;
    &quot;PolNumber&quot;: &quot;Policy123&quot;,&amp;#xd;
    &quot;MandOffName&quot;: &quot;ManOffName123&quot;,&amp;#xd;
    &quot;AuthSigName&quot;: &quot;Sig123&quot;,&amp;#xd;
    &quot;ConveName&quot;: &quot;John123&quot;,&amp;#xd;
    &quot;CollatId&quot;: &quot;Col351&quot;,&amp;#xd;
    &quot;AccNumber&quot;: &quot;LoanAccontNumber123&quot;,&amp;#xd;
    &quot;Curr&quot;: &quot; CurrencyType&quot;,&amp;#xd;
    &quot;TypOBond&quot;: &quot;BondType&quot;,&amp;#xd;
    &quot;ProcGrp&quot;: &quot;ProcessingGroup23&quot;,&amp;#xd;
    &quot;DeeOff&quot;: &quot;6&quot;,&amp;#xd;
    &quot;BchUnt&quot;: &quot;BrhUnit123&quot;&amp;#xd;
}&lt;/fileData&gt;
    &lt;archAlw&gt;Y&lt;/archAlw&gt;
    &lt;ArchFPath&gt;path\to\arch\folder&lt;/ArchFPath&gt;
    &lt;archiveFilePrefix&gt;CollatLink&lt;/archiveFilePrefix&gt;
    &lt;maxRet&gt;3&lt;/maxRet&gt;
    &lt;retryInter&gt;2&lt;/retryInter&gt;
    &lt;IBSerH&gt;host.name.com&lt;/IBSerH&gt;
    &lt;IBSerUName&gt;UName&lt;/IBSerUName&gt;
    &lt;IBSerP&gt;asdcfre345&lt;/IBSerP&gt;
    &lt;SSLOk&gt;Y&lt;/SSLOk&gt;
    &lt;httpConnectTimeout&gt;1000&lt;/httpConnectTimeout&gt;
    &lt;httpReadTimeout&gt;2000&lt;/httpReadTimeout&gt;
    &lt;endPointBaseURL&gt;https://end.point.host&lt;/endPointBaseURL&gt;
    &lt;authPartURL&gt;/auht/part/url&lt;/authPartURL&gt;
    &lt;busFuncPart&gt;/func/part/url&lt;/busFuncPart&gt;
    &lt;id_client&gt;asdqwe&lt;/id_client&gt;
    &lt;sec_client&gt;dfsdfsdf&lt;/sec_client&gt;
    &lt;grtype&gt;cl_cred&lt;/grtype&gt;
    &lt;scope&gt;adasd&lt;/scope&gt;
&lt;/TskDta&gt;
</code></pre>
<p>I am guessing that I can convert the above XML into an object of type <code>org.w3c.dom.Node</code> which I will base my research on.</p>
<p>I am checking if there is a better way, possibly serializing the variable <code>inp</code> in B and saving it, hard-code the value in the unit test, and then deserializing it to convert it back to the original object type while running the unit test classes.</p>
<p>Is that possible?</p>
",https://stackoverflow.com/questions/75479318/capture-input-parameters-for-java-unit-testing,"['java', 'unit-testing', 'serialization', 'deserialization', 'xmlnode']",46,False,0,1
LiveData not captured when unit testing Either.fold(),"<p>I'm trying to add unit tests to a project that we've inherited from another company, but I can't manage to make them work since I'm not very experienced with testing and I never used the Arrow-kt library.</p>
<p>The function <code>GetAEQueries.Params.forAEQueryRequest(queryRequest)</code> returns an <code>Either&lt;Failure, List&lt;AEQuery&gt;&gt;</code></p>
<p>They use the following architecture for Viewmodels:</p>
<pre><code>    private var _queryList = MutableLiveData&lt;Result&lt;List&lt;AEQuery&gt;&gt;&gt;()
    val queryList: LiveData&lt;Result&lt;List&lt;AEQuery&gt;&gt;&gt; get() = _queryList    

    fun foo(queryRequest: AEQueryRequest, consultationType: ConsultationType) {
        _lastFilter.postValue(queryRequest)
        _queryList.postValue(Result.Loading())
        launch {
            getAEQueries(GetAEQueries.Params.forAEQueryRequest(queryRequest)).fold(
                {
                    // Failure
                    _queryList.postValue(Result.Error(it))
             
                },
                { queries -&gt;
                    // Success
                    _queryList.postValue(Result.Success(queries))
                }
            )
        }
    }
</code></pre>
<p>And this is the test I'm trying to run</p>
<pre><code>    @get:Rule
    val instantRule = InstantTaskExecutorRule()

    private val testDispatcher = TestCoroutineDispatcher()

    @Before
    fun setUp() {
        Dispatchers.setMain(testDispatcher)

        viewModel = ConsultationsListViewModel(
            testDispatcher,
            appNavigator,
            transactionsNavigator,
            dialogNavigator,
            getAEQueries,
            getAEServices,
            getAEDownload
        )
    }

    @After
    fun tearDown() {
        Dispatchers.resetMain()
        testDispatcher.cleanupTestCoroutines()
    }

    @Test
    fun `requestToGetAEQueries OK should update queryList with the result`() = runTest {
        // Given
        val queryRequest = // Mocked request
        val consultationType = // Mocked consultation type
        val expectedQueries = // Mocked return
        val expectedResult: Either&lt;Failure, List&lt;AEQuery&gt;&gt; = expectedQueries.right()

        coEvery { getAEQueries(GetAEQueries.Params.forAEQueryRequest(queryRequest)) } returns expectedResult

        // When
        viewModel.requestToGetAEQueries(queryRequest, consultationType)

        // Then
        viewModel.lastFilter.observeOnce {
            assert(it == queryRequest)
        }
        viewModel.queryList.observeOnce {
            if(it is Result.Loading) {
                assert(it == Result.Loading(null))
            } else if (it is Result.Success) {
                assert(it == Result.Success(expectedQueries))
            }
        }
    }
</code></pre>
<p>The problem that I've got here is that the test captures the <code>lastFilter</code> LiveData correctly, but doesn't capture anything inside the viewmodel's <code>.fold()</code> function so it never reaches the Result.Success condition.</p>
<p>What am I missing here? Thanks in advance</p>
",https://stackoverflow.com/questions/75921274/livedata-not-captured-when-unit-testing-either-fold,"['android', 'kotlin', 'unit-testing', 'mockk', 'arrow-kt']",74,False,0,0
Unit Testing retryWhen using rxjs marbles + Jest,"<p>I have this RxJS function, which first calls <code>foo.methodOne()</code>, which returns an <code>Observable&lt;string&gt;</code>, and then calls <code>bar.methodTwo()</code>, which also returns an <code>Observable&lt;string&gt;</code>. <code>bar.methodTwo()</code> can fail every so often, so I needed to add retry logic to it using <code>retryWhen</code>. So this is what I've written.</p>
<pre><code>public myMethod(arg: string): Observable&lt;string&gt; {
    return this.foo.methodOne(arg)
      .pipe(
        switchMap((response) =&gt; {
          return this.bar.methodTwo(response).pipe(
            map((barResponse) =&gt; barResponse),
          );
        }),
        retryWhen((errors) =&gt; errors.pipe(
          tap((err) =&gt; console.log('error: ', err)),
          delay(500),
          take(3)),
        ),
      );
  }
</code></pre>
<p>I'm very new to RxJS marbles, and wrote the following test:</p>
<pre><code>    it('should retry if bar fails', () =&gt; {
      const arg = 'burak-crush-hyperion-cantos';
      const fooResponse = 'burak-crush-technocore';
      const barResponse = 'burak-crush-the-shrike';
      const error = {
        errorMessage: 'shrike-impale-rachel-weintraub-on-tree-of-thorns',
      };
      fooMock.methodOneSpy.mockReturnValue(
        cold('-a', { a: { uid: fooResponse } }),
      );
      barMock.methodTwoSpy
        .mockReturnValueOnce(hot('--#', null, { error }))
        .mockReturnValueOnce(hot('--c', { c: barResponse }));

      expect(
        dataService.myMethod(arg),
      ).toBeObservable(cold('--d', { d: barResponse }));
      expect(fooMock.methodOneSpy).toHaveBeenCalled();
      expect(barMock.methodTwoSpy).toHaveBeenCalledTimes(2);
    });
</code></pre>
<p>However, what I found is that bar.methodTwo fails as expected, and the <code>retryWhen</code> block gets executed (I can see the console log I've added to the <code>tap</code> therein). But then, bar.methodTwo is not called a second time, and I get an empty <code>Array[]</code> as a response.</p>
<p>What am I doing wrong here with the testing? Thanks so much in advance.</p>
<p>P.S.: Apologies for the Dan Simmons inspired test data :)</p>
",https://stackoverflow.com/questions/75322951/unit-testing-retrywhen-using-rxjs-marbles-jest,"['typescript', 'jestjs', 'rxjs', 'ts-jest', 'rxjs-marbles']",56,False,0,0
how to fix unit testing error UNHANDLED_REJECTION,"<p>its failing getting error</p>
<p>[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().</p>
",https://stackoverflow.com/questions/76286500/how-to-fix-unit-testing-error-unhandled-rejection,"['html', 'reactjs']",20,False,0,0
Too few invocations unit testing with Spock,"<p>First time user of Spock (with limited knowledge of Groovy to boot) and I suspect I am hitting the <a href=""https://stackoverflow.com/a/53281900/336752"">&quot;one giant gotcha&quot;</a> with Spock:</p>
<blockquote>
<p>Mocking and stubbing of the same method call has to happen in the same interaction.</p>
</blockquote>
<p>But I can't quite see how my example matches other questions (<a href=""https://stackoverflow.com/questions/53267791/spock-mocked-classs-method-is-not-being-matched"">1</a>, <a href=""https://stackoverflow.com/questions/41841668/spock-mock-returns-wrong-value"">2</a>, <a href=""https://stackoverflow.com/questions/54489759/spock-testing-too-few-invocation"">3</a> as examples) – all those involve methods which return a value, where the method in question is mocked in the <code>given</code> code then verified in the <code>then</code>. My code is verifying <code>void</code> methods.</p>
<p>This is the code I am trying to test:</p>
<pre><code>package com.company

import app.cash.licensee.LicenseeExtension
import app.cash.licensee.LicenseePlugin
import org.gradle.api.Plugin
import org.gradle.api.Project

class ThirdPartyLicensesCheckPlugin implements Plugin&lt;Project&gt; {

    @Override
    void apply(final Project project) {
        project.pluginManager.apply(LicenseePlugin)

        def licenseeExtension = project.extensions.findByType(LicenseeExtension)
        project.pluginManager.withPlugin(&quot;app.cash.licensee&quot;) {
            licenseeExtension.ignoreDependencies(&quot;com.company&quot;, &quot;common-utils&quot;) {
                because &quot;internal project&quot;
            }
        }
    }
}

</code></pre>
<p>I want to verify that the Licensee plugin is applied and configured correctly.</p>
<p>This is my test code:</p>
<pre><code>package com.company

import app.cash.licensee.LicenseeExtension
import app.cash.licensee.LicenseePlugin
import org.gradle.api.Project
import org.gradle.api.plugins.ExtensionContainer
import org.gradle.api.plugins.PluginManager
import spock.lang.Specification

class ThirdPartyLicensesCheckPluginTest extends Specification {

    private ThirdPartyLicensesCheckPlugin plugin

    // Class dependencies

    // Mocks for tests
    private Project project
    private PluginManager pluginManager
    private LicenseeExtension licenseeExtension

    def setup() {
        plugin = new ThirdPartyLicensesCheckPlugin()
        project = Mock(Project)
        pluginManager = Mock(PluginManager)
        project.pluginManager &gt;&gt; pluginManager

        licenseeExtension = Mock(LicenseeExtension)
        project.extensions &gt;&gt; Mock(ExtensionContainer) {
            findByType(LicenseeExtension) &gt;&gt; licenseeExtension
        }
    }

    def &quot;the cashapp/licensee plugin is applied to the project&quot;() {
        given: &quot;a Gradle project&quot;

        when: &quot;this plugin is applied&quot;
        plugin.apply(project)

        then: &quot;the cashapp/licensee plugin is applied&quot;
        1 * pluginManager.apply(LicenseePlugin)
        1 * pluginManager.withPlugin(&quot;app.cash.licensee&quot;, _)
        1 * licenseeExtension.ignoreDependencies(&quot;com.company&quot;, &quot;common-utils&quot;) { because(&quot;internal project&quot;)}
    }
}

</code></pre>
<p>The failure I am getting is:</p>
<pre><code>Too few invocations for:

1 * licenseeExtension.ignoreDependencies(&quot;com.company&quot;, &quot;common-utils&quot;) { because(&quot;internal project&quot;)}   (0 invocations)

Unmatched invocations (ordered by similarity):

None
</code></pre>
<p>I tried to verify the action parameter at the same time as the <code>withPlugin</code> check, as so:</p>
<pre><code>package com.company

import app.cash.licensee.LicenseeExtension
import app.cash.licensee.LicenseePlugin
import org.gradle.api.Project
import org.gradle.api.plugins.ExtensionContainer
import org.gradle.api.plugins.PluginManager
import spock.lang.Specification

class ThirdPartyLicensesCheckPluginTest extends Specification {

    private ThirdPartyLicensesCheckPlugin plugin

    // Class dependencies

    // Mocks for tests
    private Project project
    private PluginManager pluginManager
    private LicenseeExtension licenseeExtension

    def setup() {
        plugin = new ThirdPartyLicensesCheckPlugin()
        project = Mock(Project)
        pluginManager = Mock(PluginManager)
        project.pluginManager &gt;&gt; pluginManager

        licenseeExtension = Mock(LicenseeExtension)
        project.extensions &gt;&gt; Mock(ExtensionContainer) {
            findByType(LicenseeExtension) &gt;&gt; licenseeExtension
        }
    }

    def &quot;the cashapp/licensee plugin is applied to the project&quot;() {
        given: &quot;a Gradle project&quot;

        when: &quot;this plugin is applied&quot;
        plugin.apply(project)

        then: &quot;the cashapp/licensee plugin is applied&quot;
        1 * pluginManager.apply(LicenseePlugin)
        1 * pluginManager.withPlugin(&quot;app.cash.licensee&quot;) {
            licenseeExtension.ignoreDependencies(&quot;wrong.group&quot;, &quot;incorrect-project&quot;) { because(&quot;the wrong reason&quot;)}
        }
    }
}

</code></pre>
<p>But this always passed, even though the verification is wrong.</p>
",https://stackoverflow.com/questions/75928691/too-few-invocations-unit-testing-with-spock,"['unit-testing', 'gradle', 'groovy', 'mocking', 'spock']",50,False,0,1
Unit Testing VueRouter with the :to Attribute,"<p>I have a simple test case (Vue 2, Vuetify 2, vue-router, jest, vue-test-utils) where a Vuetify v-btn component is clicked and goes to a new route</p>
<pre><code>&lt;v-btn id=&quot;create-plan-btn&quot; :to=&quot;{ 'name': 'newPlan', query: { dept: 216001 }}&quot;&gt;Create plan&lt;/v-btn&gt;
</code></pre>
<p>However, I am unable to figure out how to register a click method that captures the <strong>:to</strong> property's action.</p>
<pre><code>describe('when &quot;Create Plan button is clicked', () =&gt; {
  const localVue = createLocalVue()
  let vuetify

  beforeEach(() =&gt; {
    vuetify = new Vuetify()
  })

  const $route = { path: '/student/index', name: 'studentLanding' }

  const mockRouter = {
    to: jest.fn(),
    push: jest.fn()
  }
  const wrapper = shallowMount(StudentLanding, {
    localVue,
    stubs: {'router-link': RouterLinkStub},
    mocks: {
      $route: $route,
      $router: mockRouter
    }
  })

  it('triggers Vue router call to the new plan page', async () =&gt; {
    const button = wrapper.find('#create-plan-btn')
    expect(button.exists()).toBe(true)
    expect(mockRouter.push).toHaveBeenCalledTimes(0)
    button.vm.$emit('click') // Vuetify buttons need &quot;vm.$emit&quot; to be triggered, not &quot;trigger()&quot; like a normal HTML button would
    await wrapper.vm.$nextTick()
    expect(mockRouter.push).toHaveBeenCalledTimes(1)
    expect(mockRouter.push).toHaveBeenCalledWith({ name: 'newPlan', query: { dept: 216001 }})
  })
})
</code></pre>
<blockquote>
<p>● when &quot;Create Plan button is clicked › triggers Vue router call to
the new plan page</p>
<pre><code>expect(jest.fn()).toHaveBeenCalledTimes(expected)

Expected number of calls: 1
Received number of calls: 0
</code></pre>
</blockquote>
<p>Note that changing <strong>push</strong> to <strong>to</strong> doesn't make any difference in the above code either.</p>
<p>The test <strong>does</strong> succeed, however, if I change my  to use a @click callback instead:</p>
<pre><code>// Test succeeds with this code
&lt;v-btn id=&quot;create-plan-btn&quot; @click=&quot;redirect&quot;&gt;Create plan&lt;/v-btn&gt;

redirect () {
   this.$router.push({ name: 'newPlan', query: { dept: 216001 }});
}
</code></pre>
<p>Is there a way to modify this test that allows the :to prop to be captured on the  click? I've tried to at least make sure the content of the :to prop is visible in the test, but I only ever get <strong>[object Object]</strong> sent back to me:</p>
<pre><code>expect(button.attributes('to').toString()).toEqual({ name: 'newPlan', query: { dept: 216001 }})
</code></pre>
<blockquote>
<p>Expected: {&quot;name&quot;: &quot;newPlan&quot;, &quot;query&quot;: {&quot;dept&quot;: 216001}}
Received: &quot;[object Object]&quot;</p>
</blockquote>
",https://stackoverflow.com/questions/75365825/unit-testing-vuerouter-with-the-to-attribute,"['jestjs', 'vue-router', 'vue-test-utils']",59,True,0,1
Flutter Unit Testing with Mockito multiple stubs,"<p>I'm quite new to unit testing and I want to test a method of a service that calls conditionally a second method. The problem I'm facing now is that I'm getting a missing MissingStubError even I have created the missing stub.</p>
<p>mockito: 5.3.2</p>
<p>Error Message:
MissingStubError: 'createCashbookItem'
No stub was found which matches the arguments of this method call:
createCashbookItem(Instance of 'CashbookItem')</p>
<p>Test:</p>
<pre><code>@GenerateMocks([CashbookRepository, ReceiptRepository, CashbookItemRepository])
void main() {
  late BookingService bookingService;
  late MockCashbookRepository mockCashbookRepository;
  late MockCashbookItemRepository mockCashbookItemRepository;
  late MockReceiptRepository mockReceiptRepository;

  setUp(() {
    mockCashbookRepository = MockCashbookRepository();
    mockCashbookItemRepository = MockCashbookItemRepository();
    mockReceiptRepository = MockReceiptRepository();
    bookingService = BookingServiceImpl(
      receiptRepository: mockReceiptRepository,
      cashbookItemRepository: mockCashbookItemRepository,
      cashbookRepository: mockCashbookRepository,
    );
  });

  group(&quot;bookings&quot;, () {
    var t_OldReceipt = Receipt.empty();
    var t_NewReceipt = Receipt.empty();

    test(&quot;create booking&quot;, () async {
      t_OldReceipt = t_OldReceipt.copyWith(
          amount: 10,
          totalAmount: 10,
          taking: true,
          category: &quot;test&quot;,
          taxRate: 0,
          paymentType: kPaymentTypeBar,
          documentNumber: &quot;1&quot;,
          taxAmount: 0,
          receiptDate: DateTime.now(),
          year: &quot;2023&quot;,
          yearMonth: &quot;20232&quot;,
          yearMonthDay: &quot;2023210&quot;,
          contact: Contact.empty());
      // arrange

      var cashbookItem = CashbookItem.fromReceipt(t_OldReceipt);

      when(mockReceiptRepository.createReceipt(t_OldReceipt)).thenAnswer((realInvocation) async =&gt; const Right(unit));
    
when(mockCashbookItemRepository.createCashbookItem(cashbookItem)).thenAnswer((realInvocation) async =&gt; const Right(unit));
      // act
      final result = await bookingService.createBooking(t_OldReceipt);
      // assert
      expect(result, const Right(unit));
    });
  });
}
</code></pre>
<p>Method that I want to test:</p>
<pre><code>  Future&lt;Either&lt;ReceiptFailure, Unit&gt;&gt; createBooking(Receipt receipt) async {
    Either&lt;ReceiptFailure, Unit&gt;? receiptFailureOrSuccess;
    Either&lt;cashbook_failures.CashbookFailure, Unit&gt;? cashbookFailureOrSuccess;

    receiptFailureOrSuccess = await receiptRepository.createReceipt(receipt);

    if (receiptFailureOrSuccess.isLeft()) {
      return receiptFailureOrSuccess;
    }

    if (receipt.paymentType == kPaymentTypeBar) {
      cashbookFailureOrSuccess = await cashbookItemRepository.createCashbookItem(CashbookItem.fromReceipt(receipt));
      if(cashbookFailureOrSuccess.isLeft()){
        receiptRepository.deleteReceipt(receipt.id.value);
        return left(CreateCashbookItemFromReceiptFailure());
      } else {
        return right(unit);
      }
    }
    return receiptFailureOrSuccess;
  }
</code></pre>
<p>I have added a stub for the error and my assumption was that it is possible to have two stubs in one test. I want to test if the method createCashbookItem inside createBooking is called.</p>
",https://stackoverflow.com/questions/75419547/flutter-unit-testing-with-mockito-multiple-stubs,"['flutter', 'dart', 'unit-testing', 'mockito']",139,False,0,0
"Unit testing CompletableFutures, Junit, Mockito, @RunWith(SpringRunner.class)","<p>I need help testing this CF's.</p>
<pre><code>public class RateHandler {    
public Response firstMethod(RateRequest, Context context) {
        CompletableFuture&lt;Response&gt; rateRespCf = CompletableFuture.supplyAsync(() -&gt; {
                try {
                    return firstHandler.handle(rateRequest, context);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }, executorService);
// same here as well rateRespCf is not taking the stubbed value from the test 
//hence resulting null

         CompletableFuture&lt;Double&gt; avgRateCf = 
                CompletableFuture.supplyAsync(() -&gt; 
                                            secondHandler.handle(rateRequest, context), executorService);

//avgRateCf is coming with 0.0 value though I'm stubbing it with 1.2 from the test. 
//I looked inside the mockInterceptor in debug mode I see 1.2 under stubbed section 
//but by the time it completes executing the line it gives me 0.0


    CompletableFuture&lt;Response&gt; result = rateRespCf //'rateRespCf' this is NULL as well
            .thenCompose(rateResp -&gt; CompletableFuture.supplyAsync(() -&gt;
                secondMethod(rateResp, avgRateCf), executorService));

        return result.get(); //getting NPE here when running the test
    }


    private RateResponse secondMethod(RateResponse rateResponse, CompletableFuture&lt;Double&gt; avgRateCf) {
        // some business logic
     for(Rate: rateResponse.getRates()) { //getting NPE at this line also when running the test since rateResponse is null
        rate.setValue(avgRateCf.get())
     }
     return rateResponse;
    }
}
</code></pre>
<p>I added my test case like this but I'm getting <code>NPE</code> by the time the control reached <code>result.get</code> not sure why result is coming as <code>NULL</code> as you can see in the test from this line <code>when(rateHandler.handler(getRateLookupRequest(),context)).thenReturn(rateLookupResponse);</code> it should return the value in <code>thenReturn</code>. In fact none of the <code>thenReturn</code> are working everything is coming as null. Please help.</p>
<p>//MyTest</p>
<pre><code>    @Mock
    FirstHandler firstHandler;
    @Mock
    SecondHandler secondHandler;   
    @InjectMocks
    RateHandler rateHandler;  

    @Test
      public void testRateHandler()
          throws BusinessException, IOException, ExecutionException, InterruptedException {
       when(firstHandler.handle(rateRequest(), context)).thenReturn(rateResponse);
       when(secondHandler.handle(rateRequest(), context))).thenReturn(1.2); 
        
    when(rateHandler.handler(getRateLookupRequest(),context)).thenReturn(rateLookupResponse);
        }
</code></pre>
<p>I even tried this approach still no luck</p>
<pre><code>    @Test
  public void testRateHandler1()
      throws BusinessException, IOException, ExecutionException, InterruptedException {
    CompletableFuture&lt;RateLookupResponse&gt; rateLookupResponseCf = CompletableFuture.completedFuture(rateLookupResponse);
    CompletableFuture&lt;Double&gt; doubleCf = CompletableFuture.completedFuture(1.2);

    doReturn(rateLookupResponseCf)
        .when(firstHandler)
        .handle(getRateLookupRequest(), context);

    doReturn(doubleCf)
        .when(secondHandler)
        .handle(getRateLookupRequest(), context);

    RateLookupResponse response = rateHandler.handler(getRateLookupRequest(), context);
    assertNotNull(response);
  }
</code></pre>
<p>PS: <code>firstHandler.handle(rateRequest(), context)</code> //returns and POJO
<code>secondHandler.handle(rateRequest(), context)</code> // returns primitive <code>double</code>
<code>rateHandler.handle(rateRequest(), context)</code> //returns POJO</p>
",https://stackoverflow.com/questions/75478642/unit-testing-completablefutures-junit-mockito-runwithspringrunner-class,"['spring-boot', 'java-8', 'mockito', 'completable-future']",178,False,0,0
Django fixing migrations order for unit testing,"<p>I'm working on a codebase which has a lot of migrations. We also have SQL views which are defined in the migrations and later updated in the migrations (whenever changes to the SQL views were required). We have a challenge where when running unit tests the migrations are not applied in the same appear as they currently appear in the <code>django_migrations</code> table. This causes unit tests to fail.</p>
<p>My thought is, I could probably write a script to the dependencies of all the migrations files to follow the same order of <code>django_migrations</code> thus ensuring that migrations are run in the correct order. Then I can look into squashing migrations.</p>
<p>But this is a lengthy process and I'm not sure if this will actually work.</p>
<p>Has anyone come across this issue before? If so, how did you overcome it?</p>
",https://stackoverflow.com/questions/75082614/django-fixing-migrations-order-for-unit-testing,"['python', 'python-3.x', 'django', 'django-migrations']",25,False,0,0
Exposing for unit testing in objective c,"<p>Let's say I have a class:</p>
<pre><code>@interface MyClass
@end

@implementation MyClass {
 myType *_myIvar;
}
@end
</code></pre>
<p>And I'd like to expose it for testing. I see two ways to do this:</p>
<ol>
<li>expose the ivar as a property:</li>
</ol>
<pre><code>@interface MyClass
  // Pragma mark - Expose for testing
  @property myIvar; 
@end
    
@implementation MyClass
@end
</code></pre>
<ol start=""2"">
<li>Use key value coding:</li>
</ol>
<pre><code>-(void)myTest {
  myType *myIvar = [myClass valueForKey:@&quot;_myIvar&quot;];
}
</code></pre>
<p>Which method is preferred?</p>
",https://stackoverflow.com/questions/75415673/exposing-for-unit-testing-in-objective-c,"['ios', 'objective-c', 'testing', 'key-value-coding']",29,True,0,1
Unit testing localStorage with Jasmine &amp; JS,"<p>I'm trying to get my head around unit testing <code>window.localStorage</code> and I believe I'm almost there, I just can't seem to access the actual key/value pairs when testing my final helper method.</p>
<p>I have the following methods:</p>
<pre class=""lang-js prettyprint-override""><code>export function testSet() {
  window.localStorage.setItem('testSet', '1234');
}

export function testDeletePrefix() {
  let deleted = false;
  Object.entries(window.localStorage).forEach(([key, value]) =&gt; {
  console.log(key);
  // This logs out getItem setItem removeItem clear
  if (key.startsWith(&quot;test&quot;) &amp;&amp; key !== &quot;test&quot;) {
    window.localStorage.removeItem(key);
    console.log(`Item with key '${key}' deleted from local storage.`);
    deleted = true;
  }
});
  if (!deleted) {
    console.log(`No key starting with 'test' found in local storage.`);
  }
}
</code></pre>
<p>Unit test:</p>
<pre class=""lang-js prettyprint-override""><code>setItemSpy = spyOn(window.localStorage, &quot;setItem&quot;).and.callFake(
    (key, value) =&gt; {
      store[key] = value.toString();
    }
  );

testSet();
expect(setItemSpy).toHaveBeenCalledWith(&quot;testSet&quot;, &quot;1234&quot;);
testDeletePrefix();
</code></pre>
<p>Whenever I run this test I get the output <code>No key starting with 'test' found in local storage.</code></p>
<p>So the <code>spyOn</code> has confirmed the key/value pair has been set, so why can't I access them when looping over <code>window.localStorage</code>?</p>
",https://stackoverflow.com/questions/76154244/unit-testing-localstorage-with-jasmine-js,"['javascript', 'jasmine', 'local-storage']",48,False,0,2
Unit testing useLoaderData() react-router v6 loader functions,"<p>A project uses react-router v6 and in some components I call <code>useLoaderData()</code>. For instance:</p>
<pre class=""lang-js prettyprint-override""><code>const routes = [
    { path: &quot;widgets&quot;, 
      loader: () =&gt; fetchAndGetJSON(&quot;/api/widgets&quot;), 
      element: &lt;ListWidgets/&gt; }
];

function ListWidgets() {
    const widgets = useLoaderData();
    return &lt;&gt;
        &lt;p&gt;Here is a list of {widgets.length} widgets:
        &lt;...&gt;
    &lt;/&gt;;
}
</code></pre>
<p>When testing I do not want to execute the <code>fetch</code>, I want to supply the list of widgets in the test.</p>
<p>How can I create a unit test for <code>ListWidgets</code> that uses data that I supply in the test?</p>
",https://stackoverflow.com/questions/75296685/unit-testing-useloaderdata-react-router-v6-loader-functions,"['reactjs', 'unit-testing', 'react-router']",451,True,3,1
Unit testing lambdas which call dynamodb in python,"<p>I am having lambdas which use <code>boto3.client()</code> to connect to a dynamoDB.</p>
<p>I tried to test it like this</p>
<pre class=""lang-py prettyprint-override""><code>    @mock.patch(&quot;boto3.client&quot;)
    def test(self, mock_client, test):

        handler(event, context)

        print(mock_client.call_count) # 1
        print(mock_client.put_item.call_count) # 0
</code></pre>
<p>However, the mock_client.call_count is 1, but not the put_item_call_count.</p>
<p>My handler looks like this:</p>
<pre class=""lang-py prettyprint-override""><code>def handler(event, context):
      dynamodb = boto3.client('dynamodb')

         response = dynamodb.put_item(// same attributed) 
</code></pre>
<p>Any suggestion, how to test if the correct item gots putted in the database without using moto?</p>
",https://stackoverflow.com/questions/75124572/unit-testing-lambdas-which-call-dynamodb-in-python,"['python', 'amazon-web-services', 'boto3', 'python-unittest']",61,True,2,1
Unit testing method that uses already tested method,"<p>Assume we have class <code>Handler</code> and class <code>Validator</code>. The <code>Handler</code> uses <code>Validator</code> to validate incoming requests.</p>
<p>The <code>Validator</code> class is unit tested, whether returns appropriate error etc.</p>
<p>Later, we want to create unit tests for <code>Handler</code>. The <code>Validator</code> has already unit tests, so how would the test for <code>Handler</code> look?</p>
<p>Will we write the same tests as for <code>Validator</code> whether <code>Handler</code> returns the appropriate error (retrieved from <code>Validator</code> class)? It doesn't make sense to me.</p>
<p>So how would the unit test for <code>Handler</code> class look in this case?</p>
",https://stackoverflow.com/questions/76247001/unit-testing-method-that-uses-already-tested-method,['unit-testing'],39,True,2,2
Golang Issue with Unit Testing for simple error,"<p>I am having trouble trying to test this function with an error inside. The following is my ResponseJson function which does not return an error but sends a response json.</p>
<pre class=""lang-golang prettyprint-override""><code>func ResponseJson(w http.ResponseWriter, Code int, Message string) {
    jsonStatus := struct {
        Code int `json:&quot;code&quot;`
        Message string `json:&quot;message&quot;`
    }{
        Message: Message,
        Code: Code,
    }

    bs, err := json.Marshal(jsonStatus);

    if err != nil {
        log.Println(&quot;Error in Marshal JSON in ResponseJson: &quot;, err)
        str := &quot;Internal Server Error. Please contact the System Administrator.&quot;
        io.WriteString(w, str);
        return 
    } else {
        io.WriteString(w, string(bs));
        return
    }
    
}
</code></pre>
<p>The following is my unit testing code which creates a mock ResponseWriter and it is able to successfully test the writer response json for cases with no errors. Since I am not returning an error type in ResponseJson() function, how do I test it inside the Test_ResponseJson function as shown below?</p>
<pre class=""lang-golang prettyprint-override""><code>func Test_ResponseJson(t *testing.T) {
    responseJsonTests := []struct {
        testName string
        code int
        message string
        expectedJsonResponse string
    } {
        {&quot;Successful Login&quot;, http.StatusOK, &quot;Successfully Logged In!&quot;, `{&quot;code&quot;:200,&quot;message&quot;:&quot;Successfully Logged In!&quot;}`},
        {&quot;Existing username&quot;, http.StatusBadRequest, &quot;Username already exists. Please try again.&quot;, `{&quot;code&quot;:400,&quot;message&quot;:&quot;Username already exists. Please try again.&quot;}`},
    }

    for _, e := range responseJsonTests {
        // Creating a mock ResponseWriter
        w := httptest.NewRecorder()

        ResponseJson(w, e.code, e.message)

        // Read the response body as a string
        body, _ := io.ReadAll(w.Result().Body)
        actual := string(body)

        expected := e.expectedJsonResponse
        if actual != expected {
            t.Errorf(&quot;%s: expected %s but got %s&quot;, e.testName, e.expectedJsonResponse, actual)
        }
    }
}
</code></pre>
<p>Also, I have created a function which generates an actual log output for log.Println() built-in function. I am aware that the log.Println() function is a built-in function and it is highly unlikely to fail. However, I want to achieve 100% coverage in my unit testing. Please help! Thank you :)</p>
<pre class=""lang-golang prettyprint-override""><code>func GenerateLogOutput(message string, errorMessage string) string {
    // Create a new bytes.Buffer to capture the log output
    var buf bytes.Buffer

    // Redirect log output to a different destination set as a buffer
    // By default, log message are written to the standard error stream os.Stderr
    log.SetOutput(&amp;buf)

    // Generate an error
    err := errors.New(errorMessage)

    w := httptest.NewRecorder()

    // Calling the function
    InternalServerError(w, message, err)
    actualOutput := buf.String()

    return actualOutput
}
</code></pre>
",https://stackoverflow.com/questions/75710686/golang-issue-with-unit-testing-for-simple-error,"['unit-testing', 'go']",330,True,1,1
Unit testing IndexModel OnGet method with mocked User.Identity.Name,"<p>I am new to Testing and trying to unit test the function onGet()</p>
<pre><code>public class IndexModel : PageModel
    {
     private readonly ILogger&lt;IndexModel&gt; _logger;
       
     public IndexModel(ILogger&lt;IndexModel&gt; logger)
    {
     _logger = logger;
    }
       
     public IActionResult OnGet()
     {            
     var loggedInUser = User.Identity?.Name;
     /*sets the cookie and redirects*/
     }
    }
</code></pre>
<p>Below is my unit test:</p>
<pre><code>public void OnGet_Test()
    {
      var mock = new Mock&lt;ILogger&lt;IndexModel&gt;&gt;();
      ILogger&lt;IndexModel&gt; logger = mock.Object;

      var test = new IndexModel(logger);
      IActionResult result = test.OnGet();
      Assert.IsInstanceOfType(result,typeof(RedirectToPageResult));

     }
</code></pre>
<p>This gives null reference exception as there is not value of User.Identity?.Name</p>
<p>I have tried many things including to mock it</p>
<pre><code>var user_mock = new Mock&lt;ControllerContext&gt;();            
   user_mock.SetupGet(p =&gt; p.HttpContext.User.Identity.Name).Returns(“Test User”);
</code></pre>
<p>but how to set it up in the current context of the Test? as it keeps giving errors
error -Property or indexer 'PageModel.User' cannot be assigned to -- it is read only
error - Property or indexer 'PageModel.HttpContext' cannot be assigned to -- it is read only</p>
<p>If I mock HttpContext then also it’s the same problem how to set to in my class object?</p>
",https://stackoverflow.com/questions/76333443/unit-testing-indexmodel-onget-method-with-mocked-user-identity-name,['unit-testing'],25,False,1,0
MediatR is returning null while unit testing controller,"<p>I am trying to unit test my controller but I am using MediatR. I have mocked it but somehow result is null. I tried to search other people questions but non of them helped.</p>
<p>My controller:</p>
<pre><code>[HttpGet(&quot;{authorId}&quot;)]
    [ProducesResponseType(200, Type = typeof(Author))]
    [ProducesResponseType(400)]
    public async Task&lt;IActionResult&gt; GetAuthor(int authorId)
    {
        var query = new GetAuthorQuery(authorId);
        var result = await _mediator.Send(query); 
        return result != null ? (IActionResult)Ok(result) : NotFound();
    }
</code></pre>
<p>Unit Test constructor:</p>
<pre><code>private Mock&lt;IMediator&gt; _mediator;
 public BookStoreAuthorControllerTests()
    {
        _mediator= new Mock&lt;IMediator&gt;();
        _authorRepository= new Mock&lt;IAuthorRepository&gt;();
        fixture= new Fixture();

        fixture.Behaviors.OfType&lt;ThrowingRecursionBehavior&gt;().ToList()
        .ForEach(b =&gt; fixture.Behaviors.Remove(b));
        fixture.Behaviors.Add(new OmitOnRecursionBehavior());

        var mapperConfig = new MapperConfiguration(c =&gt;
        {
            c.AddProfile&lt;Helpers.MappingProfiles&gt;();
        });
        _mapper = mapperConfig.CreateMapper();

    }
</code></pre>
<p>GetAuthor Test :</p>
<pre><code> [Test]
    public async Task GetAuthor_Returns_Ok()
    {
        var author = fixture.Build&lt;Author&gt;().Create();
        var mappedAuthor= _mapper.Map&lt;AuthorDto&gt;(author);

        var controller = new AuthorController(_mediator.Object);
        var query = new GetAuthorQuery(author.Id);

        _authorRepository.Setup(r=&gt;r.GetAuthor(author.Id)).ReturnsAsync(author);
        _mediator.Setup(x =&gt; x.Send(query, It.IsAny&lt;CancellationToken&gt;())).ReturnsAsync(mappedAuthor);

        var result = await controller.GetAuthor(author.Id);
        var obj = result as ObjectResult;

        Assert.AreEqual(200, obj.StatusCode);
    }
</code></pre>
",https://stackoverflow.com/questions/75959076/mediatr-is-returning-null-while-unit-testing-controller,"['c#', 'unit-testing', 'asp.net-web-api', 'nunit', 'mediatr']",47,True,1,1
Unit testing onSuccess for a react query call,"<p>I have a component that looks like this:</p>
<pre><code>&lt;TestComponent refetch={fn} /&gt;
</code></pre>
<p>Within <code>TestComponent</code>, I have a save button that fires off a mutation:</p>
<pre><code>    const handleSaveClick = () =&gt; {
        const reqBody: AddHotelRoomDescription = {...}

        addHotelRoomDescriptionMutation(reqBody, {
            onSuccess: () =&gt; {
                closeDrawer();
                handleRefetch();
            }
        })
    }
</code></pre>
<p>Within my test file for this component, I am trying to ensure <code>handleRefetch</code> gets called:</p>
<pre><code>it('successfully submits and calls the onSuccess method', async () =&gt; {
        const mockId = '1234'

        nock(API_URL)
            .post(`/admin/${mockId}`)
            .reply(200);

        const user = userEvent.setup();
        const editorEl = screen.getByTestId('editor-input');

        await act( async () =&gt; { await user.type(editorEl, 'Updating description'); });
        expect(await screen.findByText(/Updating description/)).toBeInTheDocument();

        const saveButton = screen.getByText('SAVE');
        await act( async () =&gt; { await user.click(saveButton) });

        expect(mockedMutate).toBeCalledTimes(1);

        await waitFor(() =&gt; {
            expect(mockedHandleRefetch).toBeCalledTimes(1); &lt;-- fails here
        })
    })
</code></pre>
<p>I am not sure how to proceed here. I know I can test useQuery calls by doing:</p>
<pre><code>const { result } = renderHook(() =&gt; useAddHotelRoomDescription(), { wrapper }
</code></pre>
<p>But I think this is for a different situation.</p>
<p>Appreciate the guidance!</p>
",https://stackoverflow.com/questions/75376783/unit-testing-onsuccess-for-a-react-query-call,"['reactjs', 'jestjs', 'react-query']",382,True,1,1
Python generate the ClientRequestException object for unit testing,"<p>For my <code>Python</code> application unit test, I need to generated the <code>ClientRequestException</code>  object, to test the failure condition. using the below code to generate the exception object, but getting the error message.</p>
<p><strong>Code:</strong></p>
<pre><code>    from office365.runtime.client_request_exception import ClientRequestException
    from requests import Response
    e = Response()
    e.args = []
    e.response=&quot;hello&quot;
    e.status_code = 404
    e.headers['Content-Type'] = 'application/json'
    err = ClientRequestException(*e.args, response=e.response)
    print(err)
</code></pre>
<p><strong>Error:</strong></p>
<pre><code>self = ClientRequestException(), args = (), kwargs = {'response': 'hello'}

    def __init__(self, *args, **kwargs):
        super(ClientRequestException, self).__init__(*args, **kwargs)
&gt;       content_type = self.response.headers.get('Content-Type', '').lower().split(';')[0]
E       AttributeError: 'str' object has no attribute 'headers'

..\..\venv\lib\site-packages\office365\runtime\client_request_exception.py:7: AttributeError
</code></pre>
<p>May I know the correct way to generate <code>ClientRequestException</code> object?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/76318819/python-generate-the-clientrequestexception-object-for-unit-testing,"['python', 'python-3.x', 'pytest']",19,True,1,1
Angular Unit - Testing how to subscribe event emitter,"<p>In my unit test I want to call <code>openDialog</code>, <code>openPdf</code>, <code>getPath</code> with these three eventemitter that are in the <code>ngOnDestroy</code> method. How can I call them?</p>
<p><code>component.ts</code>:</p>
<pre class=""lang-js prettyprint-override""><code>pdfPath: string = ''; // will be edited later

@Output() openDialog = new EventEmitter();
@Output() openPdf = new EventEmitter();
@Output() getPath: EventEmitter&lt;string&gt; = new EventEmitter();
 
getData() {
  // ...
  this.openDialog.emit(true);
}

showData() {
  // ...
  this.openPdf.emit();
}

fetchData() {
  // ...
  this.getPath.emit(this.pdfPath);
}


ngOnDestroy(): void {
    this.openDialog.unsubscribe();
    this.openPdf.unsubscribe();
    this.getPath.unsubscribe();
}

</code></pre>
<p>I've tried calling them like this in the <code>beforeEach</code> and use   spyOn(component.openDialog, 'subscribe');
, but this isn't working:</p>
<pre><code>const emitter = new EventEmitter();
component.openDialog = emitter;
component.openPdf = emitter;
component.getPath = emitter;
emitter.emit(true);
</code></pre>
",https://stackoverflow.com/questions/75155122/angular-unit-testing-how-to-subscribe-event-emitter,"['angular', 'unit-testing', 'karma-jasmine', 'angular11']",183,False,1,1
Python unit testing with consistent random.seed using multiprocessing?,"<p>I have a function in my code that calls a <code>multiprocessing.Pool</code>, and each worker process calls a function <code>generate_sensor</code> that uses <code>random.randint</code> and <code>random.choice</code> a number of times.  <code>generate_sensor</code> is in the file <code>seed.py</code>, which imports <code>random</code>.</p>
<p>I want to set a consistent random seed to ensure reproducible unit tests, and I'm having trouble, I <em>think</em> because of the use of multiprocessing, which means the order random is called isn't consistent.  Or maybe I just am trying to set the seed incorrectly.</p>
<hr />
<p>The code in question, <code>my_module.py</code> in <code>main</code> contains something like this:</p>
<pre class=""lang-py prettyprint-override""><code>num_processes = multiprocessing.cpu_count() -1
pool = multiprocessing.Pool(num_processes)
tasks: list[tuple[seed.Seed, str, int, int]] = []
sensors: dict[str, sensor.Sensor] = {}

for i in range(num_processes):
    tasks.extend([(s, self.recSeq, seedSensPerProcess, i) for s in seeds])

for t in tasks:
    pool.apply_async(
        generate_sensor, t, callback=lambda result: sensors.update(
            [(r.seq, r) for r in result]
        ),
    )
pool.close()
pool.join()
return sensors
</code></pre>
<hr />
<p>I'm trying to set a consistent seed in pytest for unit testing, to ensure a consistent result.</p>
<p>So far, I tried both of the following, to no success:</p>
<p><strong>Failed Approach 1:</strong></p>
<pre class=""lang-py prettyprint-override""><code>def test_my_function() -&gt; None:
    random.seed(0)
    out_sensors = my_module.main()
    print(out_sensors)
    assert False # so pytest will show print no matter what
</code></pre>
<p>This shows a different output every time, so the random imported by seed.py is not affected.</p>
<p><strong>Failed Approach 2:</strong></p>
<pre class=""lang-py prettyprint-override""><code>def test_my_function() -&gt; None:
    with patch(&quot;my_package.seed.random&quot;) as mock_random:
        mock_random = random.Random(0)

        out_sensors = my_module.main()
        print(out_sensors)
        assert False # so pytest will show print no matter what
</code></pre>
<p>This fails silently, and doesn't generate any output-- I'm guessing seed's imported random is no longer working.</p>
<hr />
<p>Any idea on how to properly pass a random seed to the submodule?</p>
",https://stackoverflow.com/questions/75871558/python-unit-testing-with-consistent-random-seed-using-multiprocessing,"['python', 'random', 'mocking', 'multiprocessing', 'pytest']",73,False,1,1
Swift Async/Await with Combine Publisher unit testing,"<p>I have a codebase where we have a mixture of Async/Await and combine, while running it seems to work fine, however testing is another matter entirely. Publishers are easy enough to get deterministic output on as you can wait for the expectation or even inject a different thread for them to run making them execute immediately. Async/Await however does not give you this control. I have tried running <code>try await Task.sleep(nanoseconds: duration)</code> with some limited success but it is a tad flakey and does not always work.</p>
<p>Here is the code im currently trying to pass on tests</p>
<pre><code>lazy var searchTests: AnyPublisher&lt;Result&lt;LabTestResultPage, Error&gt;, Never&gt; = searchSub
      .compactMap { $0 }
      .debounce(for: .seconds(1), scheduler: DispatchQueue.main)
      .map { [unowned self] in search(searchParams: $0) }
      .switchToLatest()
      .share()
      .eraseToAnyPublisher()
</code></pre>
<p>and the Async/Await method that is being called is here</p>
<pre><code>private func search(searchParams: SearchTestsParams) -&gt; AnyPublisher&lt;Result&lt;LabTestResultPage, Error&gt;, Never&gt; {
        Deferred { [searchTestsUseCase] in
          Future { promise in
            Task {
              do {
                promise(.success(.success(try await searchTestsUseCase.execute(with: searchParams))))
              } catch {
                promise(.success(.failure(error)))
              }
            }
          }
        }
        .eraseToAnyPublisher()
      }
</code></pre>
<p>Has anyone got these to work nicely together when testing?</p>
",https://stackoverflow.com/questions/75542266/swift-async-await-with-combine-publisher-unit-testing,"['swift', 'async-await', 'combine']",280,False,0,0
Ways to mock C functions for unit-testing?,"<p>I've tried multiple sources for solutions to this problem. They all either require modifying the source code, and architecture specific exploit such as writing in a jmp instruction to detour the function, or using a macro and including the c file. The first one is extremely annoying to deal with, the second is usually not possible due to page protections, and the third introduces a lot of problems with linking multiple files containing different mocks and unit test for the same source file. Is there any better method of doing this?</p>
",https://stackoverflow.com/questions/75028506/ways-to-mock-c-functions-for-unit-testing,"['c', 'unit-testing', 'mocking', 'stub']",122,True,0,1
Docker Environment Variables missing for PhpStorm Unit Testing,"<p>I am currently trying to set up a development environment with Docker. The goal is have a single Docker Compose file to start all necessary containers and develop and test code within the containers.</p>
<p>I now ran into a problem with my environment variables not being available when running tests using PhpStorm's built-in Docker support. All my tests are succeeding when running <code>docker compose exec api-internal-php vendor/bin/phpunit</code> but not when running my tests in PhpStorm. To clarify: In both cases I am executing my tests in the running container. The reason for my tests failing is that the environment variables I defined in my Docker Compose file, and that are necessary for connecting to my database, are not available when running PHPUnit in PhpStorm. My Docker image is based on php:8.2-fpm-alpine.</p>
<p>My system configuration (up-to-date at the time of writing):</p>
<ul>
<li>macOS 13.1</li>
<li>Docker Desktop 4.15.0</li>
<li>PhpStorm 2022.3.1</li>
</ul>
<p>Of course I ensured that I am actually running the tests using Docker. I am using a Docker network and connect to the database by using the service's name. I can confirm that the scope of my environment variables is the issue, because when replacing the environment variables in my code by their actual value, the tests are succeeding even in PhpStorm. That also means that the test is able to connect to the database using the service's name and the Docker network.</p>
<p>I installed Xdebug in my image and debugging is working fine. By adding a breakpoint at the beginning of my test I can confirm that my variables are missing in the <code>$_ENV</code> array.</p>
<p>I tried different things and was searching for a solution for hours but did not succeed yet. I tried adding an fpm config file with my environment variables like <a href=""https://stackoverflow.com/a/45011630/21026760"">this post</a> suggested, which did not help. Otherwise, I did not find any question with the exact same problem.</p>
<p>Relevant excerpt of my Docker Compose file:</p>
<pre class=""lang-yaml prettyprint-override""><code>api-internal-php:
  build:
    context: .
    dockerfile: dockerfiles/php.dockerfile
    args:
      APP_ENV: dev
      SYMFONY_DIRECTORY: backend-api-internal
  restart: unless-stopped
  volumes:
    - ./backend-api-internal:/var/www/html:ro
    - ./backend-api-internal/var:/var/www/html/var
    - ./backend-api-internal/vendor:/var/www/html/vendor
    - ./backend-api-internal/.phpunit.result.cache:/var/www/html/.phpunit.result.cache
  environment:
    DB_ANSWERS_URL: mysqli://root:local@mariadb/
    DB_DEV_NAME: dev_env_db
    DB_TEST_NAME: test_env_db
  depends_on:
    - mariadb
    - model
</code></pre>
<p>One interesting side note: My application/working directory in the container is (obviously) <code>/var/www/html</code>. Somehow, PhpStorm uses <code>/opt/project</code> as the path mapping. As I said, when replacing the environment variables in the code by their actual value, the tests run just fine, so I do not think that this is the problem.</p>
",https://stackoverflow.com/questions/75145831/docker-environment-variables-missing-for-phpstorm-unit-testing,"['php', 'docker', 'phpunit', 'phpstorm']",316,True,0,1
Simulating apache ignite node failure for unit testing,"<p>For unit testing, I'm running multiple Ignite nodes in the same JVM (as discussed in the answer <a href=""https://stackoverflow.com/questions/57353239/how-to-run-multiple-apache-ignite-nodes-on-same-jvm"">here</a> ).</p>
<p>In my unit tests I want to simulate what happens when an Ignite node unexpectedly dies, e.g. to simulate a sudden hardware failure and the effects of it on the cluster as a whole. I can't just call Ignite.close() because this does an <strong>orderly</strong> shutdown, and I want a sudden <strong>disorderly</strong> shutdown, with all the problems it could bring.</p>
<p>I can think of two potential ways to do this:</p>
<ol>
<li><p>When I start a new ignite node in my JVM, somehow keep track of all the threads it spawns and then use (the deprecated) method thread.stop to kill all its threads abruptly when I want to simulate it dying. I can't see a way of reliably distinguishing between threads launched by one Ignite in the JVM from threads spawned by another though, unless I assume Ignite starts all its threads at startup only.</p>
</li>
<li><p>Launch a separate process using the Java process API (see first answer <a href=""https://stackoverflow.com/questions/636367/executing-a-java-application-in-a-separate-process"">here</a> ), start ignite in that process and then kill it by force using Process.destroy() or Process.destroyForcibly().</p>
</li>
</ol>
<p>Does anyone know a better approach?</p>
<p>I'm using Java 8.</p>
",https://stackoverflow.com/questions/76010538/simulating-apache-ignite-node-failure-for-unit-testing,"['java', 'ignite']",115,True,0,1
"Unit testing components Vitest, Vue Test Utils, Pinia","<pre><code>import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import { createTestingPinia } from '@pinia/testing'

// Import component
import NavBar from '../base/layout/NavBar.vue'

const wrapper = mount(NavBar, {
  plugins: [
    createTestingPinia({
      stubActions: false,
    }),
  ],
})

describe('NavBar Test', () =&gt; {
  it('it should render', () =&gt; {
    // Find Logo
    expect(wrapper.find('.nav-logo').exists()).toBeTruthy()
    // // Find Links
    expect(wrapper.find('.nav-links').exists()).toBeTruthy()
    // // Find Toggle
    expect(wrapper.find('.nav-toggles').exists()).toBeTruthy()
  })
})

</code></pre>
<p>Creating a unit tests for a navbar component that has a simple pinia store, running into an issue where I get the following:</p>
<p><code>TypeError: Cannot read properties of undefined (reading 'getNavState')</code></p>
<p>inside the component I do the following in areas to show an open class etc</p>
<p><code>&lt;a href=&quot;/&quot; class=&quot;nav-logo&quot; :class=&quot;{ open: navStore.getNavState }&quot;&gt;</code></p>
<p>I've read through several sources and used the main pinia/vitest doc but can't seem to see why my store is not available (getters should work) so the test is failing</p>
<p>Reading through I should not need to mock a store as it should automatically work setting <code>stubActions</code> but am I wrong? Any help would be much appreciated</p>
",https://stackoverflow.com/questions/76363785/unit-testing-components-vitest-vue-test-utils-pinia,"['vuejs3', 'vue-test-utils', 'pinia', 'vitest']",56,False,0,1
Unit testing does not fill the component object,"<p>I'm new in Angular, and I just implemented on an existing project the unit testing with Karma and Jasmine, so I created the spec.ts component and html as:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>describe('CashFlowSalariesComponent', () =&gt; {
      let fixture: ComponentFixture &lt; CashFlowSalariesComponent &gt; ;
      let mockCashFlowService;
      let data;

      beforeEach(async(() =&gt; {
        data = [{
          id: 1006,
          role: ""Test"",
          ...
        }]

        mockCashFlowService = jasmine.createSpyObj(['createTableData'])
        TestBed.configureTestingModule({
          schemas: [CUSTOM_ELEMENTS_SCHEMA],
          imports: [
            RouterTestingModule,
            FormsModule,
            ReactiveFormsModule,
            BrowserModule,
            HttpClientTestingModule,
            ToastrModule.forRoot({
              positionClass: 'toast-bottom-right'
            })
          ],
          declarations: [
            CashFlowSalariesComponent,
          ],
          providers: [{
              provide: ApiService,
              useValue: mockCashFlowService
            }, UserService, ProfileService, VettingStatusService, ApplicationRoleService,
            SeniorityLevelService, PlacementStatusService, EducationLevelService, UtilsService, ShirtSizeService,
            CountryService, CityService, PostalCodeService, StateService, ClientSectorService, JobService, ProfileActivityService, ProfileSalaryActivityService, ClientService, RequestTimeOffService, TimeOffTypeService, PulsecheckDetailService, PulsecheckMasterService,
            PulsecheckQuestionService, ExpenseService, DepartmentService, ExchangeRateService, SkillCategoriesService, ProfileRoleService,
            ToastrService
          ]

        })

        fixture = TestBed.createComponent(CashFlowSalariesComponent);
      }));

      it('should set salaries data correctly', () =&gt; {
        mockCashFlowService.userBelongsTo = 'operations'
        mockCashFlowService.createTableData.and.returnValue(of (data))
        debugger;
        fixture.detectChanges();
        expect(fixture.componentInstance.data.length).toBe(1);
      })</code></pre>
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;div class=""row"" *ngIf=""apiService.utilsService.userBelongsTo('operations')""&gt;
  &lt;div class=""col-12 my-2""&gt;
    &lt;div class=""shadow bg-white rounded""&gt;
      &lt;div class=""card"" *ngIf=""salariesCard""&gt;
        &lt;div class=""card-body""&gt;
          &lt;div class=""row px-4""&gt;
            &lt;div class=""col-md-6""&gt;
              &lt;h4 class=""my-card-title""&gt;Employee Salaries&lt;/h4&gt;
            &lt;/div&gt;
            &lt;div class=""col-md-6 text-right d-flex justify-content-end""&gt;
              &lt;h5 class=""card-title mr-2 my-2""&gt;{{ salariesCard.usdExpensesTotal | currency }}&lt;/h5&gt;
              &lt;csv-export-button [data]=""dataExport"" [propertyKeys]=""propertyKeysExport"" [headerNames]=""dataHeadersExport"" fileName=""Employee Salaries""&gt;
              &lt;/csv-export-button&gt;
            &lt;/div&gt;

          &lt;/div&gt;
          &lt;div class=""my-table-wrapper mt-4""&gt;

            &lt;table class=""table salaries-table""&gt;
              &lt;thead class=""""&gt;
                &lt;th scope=""col"" *ngFor=""let header of dataHeaders"" [width]=""header.width""&gt;{{header.name}}&lt;/th&gt;
              &lt;/thead&gt;
              &lt;tbody&gt;
                &lt;tr *ngFor=""let salary of data; index as i"" [class.bg-danger]=""salary.isPaymentHold""&gt;
                  &lt;td scope=""row""&gt;{{i + 1}}&lt;/td&gt;
                  &lt;td&gt;
                    &lt;span class=""badge"" [class.badge-outline-info]=""salary.role == 'Developer'"" [class.badge-outline-success]=""salary.role == 'Drafter'"" [class.badge-outline-warning]=""salary.role == 'Admin' || salary.role == 'Recruiter'""&gt;
                          {{
                            salary.role == 'Developer' ? 'Dev' :
                            salary.role == 'Drafter' ? 'Draft' :
                            salary.role.trim()
                          }}
                        &lt;/span&gt;
                  &lt;/td&gt;
                  &lt;td&gt;
                    &lt;strong class=""not-so-strong""&gt;{{ salary.name }}&lt;/strong&gt;
                  &lt;/td&gt;
                  &lt;td&gt;
                    &lt;div&gt;
                      {{ salary.client }}
                    &lt;/div&gt;
                  &lt;/td&gt;

                  &lt;td&gt;
                    &lt;input *ngIf=""selectedProfile != null &amp;&amp; selectedProfile.id == salary.id"" type=""number"" class=""form-control form-control-sm text-sm"" [(ngModel)]=""selectedProfileMXNExpense"" [disabled]=""selectedProfileExpenseCurrency == 1""&gt;
                    &lt;div *ngIf=""selectedProfile == null || selectedProfile.id != salary.id"" class=""profile-perception""&gt;
                      {{ salary.mxnAmount | currency }}
                    &lt;/div&gt;
                  &lt;/td&gt;

                  &lt;td&gt;
                    &lt;input *ngIf=""selectedProfile != null &amp;&amp; selectedProfile.id == salary.id"" type=""number"" class=""form-control form-control-sm text-sm"" [(ngModel)]=""selectedProfileUSDExpense"" [disabled]=""selectedProfileExpenseCurrency == 2""&gt;
                    &lt;div *ngIf=""selectedProfile == null || selectedProfile.id != salary.id"" class=""profile-perception""&gt;
                      {{ salary.usdAmount | currency }}
                    &lt;/div&gt;
                  &lt;/td&gt;

                  &lt;td&gt;
                    &lt;select *ngIf=""selectedProfile != null &amp;&amp; selectedProfile.id == salary.id"" type=""text"" class=""form-control form-control-sm text-sm"" [(ngModel)]=""selectedProfileExpenseCurrency"" (ngModelChange)=""setSelectedProfileCurrency()""&gt;
                      &lt;option value=""1""&gt;USD&lt;/option&gt;
                      &lt;option value=""2""&gt;MXN&lt;/option&gt;
                    &lt;/select&gt;
                    &lt;div *ngIf=""selectedProfile == null || selectedProfile.id != salary.id""&gt;
                      {{ salary.paymentCurrency }}
                    &lt;/div&gt;
                  &lt;/td&gt;

                  &lt;td&gt;
                    &lt;!-- Health Insurance Cost --&gt;
                    &lt;input *ngIf=""selectedProfile != null &amp;&amp; selectedProfile.id == salary.id"" type=""number"" class=""form-control form-control-sm text-sm"" [(ngModel)]=""selectedProfileInsuranceExpense""&gt;
                    &lt;div *ngIf=""selectedProfile == null || selectedProfile.id != salary.id"" class=""profile-expense""&gt;
                      {{ salary.mxnInsuranceCost | currency }}
                    &lt;/div&gt;
                  &lt;/td&gt;

                  &lt;td&gt;
                    &lt;!-- Net Payment --&gt;
                    &lt;div&gt;
                      {{ salary.mxnNetPayment | currency }}
                    &lt;/div&gt;
                  &lt;/td&gt;
                  &lt;td&gt;
                    &lt;!-- Enrolled in health insurance --&gt;
                    &lt;div&gt;
                      {{ salary.isEnrolledInHealthInsurance ? 'YES' : 'NO' }}
                    &lt;/div&gt;
                  &lt;/td&gt;

                  &lt;td&gt;
                    &lt;div class=""d-flex actions-container""&gt;
                      &lt;button *ngIf=""selectedProfile == null || selectedProfile.id != salary.id"" (click)=s etProfile(salary.profile) class=""btn"" ngbTooltip=""Edit""&gt;
                        &lt;i class=""mdi mdi-pencil""&gt;&lt;/i&gt;
                      &lt;/button&gt;
                      &lt;button *ngIf=""(selectedProfile == null || selectedProfile.id != salary.id) &amp;&amp; !salary.isPaymentHold"" (click)=""holdProfilePayment(profile, true)"" class=""btn"" ngbTooltip=""Hold Payment""&gt;
                        &lt;i class=""mdi mdi-pause""&gt;&lt;/i&gt;
                      &lt;/button&gt;
                      &lt;button *ngIf=""(selectedProfile == null || selectedProfile.id != salary.id) &amp;&amp; salary.isPaymentHold"" (click)=""holdProfilePayment(profile, false)"" class=""btn"" ngbTooltip=""Resume Payment""&gt;
                        &lt;i class=""mdi mdi-play""&gt;&lt;/i&gt;
                      &lt;/button&gt;
                      &lt;a *ngIf=""selectedProfile == null || selectedProfile.id != salary.id"" [href]=""'/profiles/detail/' + salary.id"" target=""_blank"" ngbTooltip=""Go to profile"" class=""btn""&gt;
                        &lt;i class=""mdi mdi-eye""&gt;&lt;/i&gt;
                      &lt;/a&gt;
                      &lt;button *ngIf=""selectedProfile != null &amp;&amp; selectedProfile.id == salary.id"" class=""btn"" (click)=""saveProfileExpense(salariesCard)"" ngbTooltip=""Save""&gt;
                        &lt;i class=""mdi mdi-check""&gt;&lt;/i&gt;
                      &lt;/button&gt;
                      &lt;button *ngIf=""selectedProfile != null &amp;&amp; selectedProfile.id == salary.id"" class=""btn"" (click)=""selectedProfile = null"" ngbTooltip=""Cancel""&gt;
                        &lt;i class=""mdi mdi-cancel""&gt;&lt;/i&gt;
                      &lt;/button&gt;
                      &lt;button *ngIf=""(selectedProfile == null || selectedProfile.id != salary.id) &amp;&amp; !salary.isPaymentHold"" (click)=""showHistory(salary.profile)"" class=""btn"" ngbTooltip=""Salary history""&gt;
                        &lt;i class=""mdi mdi-currency-usd""&gt;&lt;/i&gt;
                      &lt;/button&gt;
                    &lt;/div&gt;
                  &lt;/td&gt;
                &lt;/tr&gt;
              &lt;/tbody&gt;
            &lt;/table&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</code></pre>
</div>
</div>
</p>
<p><strong>TS:</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>@Component({
  selector: ""cash-flow-salaries"",
  templateUrl: ""./cash-flow-salaries.component.html"",
  styleUrls: [""./cash-flow-salaries.component.css""],
})
export class CashFlowSalariesComponent implements OnInit, OnChanges {
  @Input() salariesCard: SalariesCardItem;
  @Input() exchangeRate: number;
  @Input() roleNamesByProfileId: string[];
  @Input() clients: ClientModel[] = [];

  @Output() profileEdited: EventEmitter &lt; number &gt; = new EventEmitter &lt; number &gt; ();

  selectedProfile: ProfileModel = null;
  selectedProfileUSDExpense: string = """";
  selectedProfileMXNExpense: string = """";
  selectedProfileInsuranceExpense: string = """";
  selectedProfileExpenseCurrency: number = 2;
  selectedProfileClientId: number = 0;
  originalSalary: number;

  public dataHeaders = [{
      name: ""#"",
      width: ""6%""
    },
    {
      name: ""Role"",
      width: ""7%""
    },
    {
      name: ""Name""
    },
    {
      name: ""Client""
    },
    {
      name: ""MXN Amount""
    },
    {
      name: ""USD Amount""
    },
    {
      name: ""Payment Currency"",
      width: ""8%""
    },
    {
      name: ""MXN Insurance Cost""
    },
    {
      name: ""MXN Net Payment""
    },
    {
      name: ""Is Enrolled in Health Insurance?""
    },
  ];

  public dataHeadersExport = [
    ""#"",
    ""Role"",
    ""Name"",
    ""Client"",
    ""MXN Amount"",
    ""USD Amount"",
    ""Payment Currency"",
    ""MXN Insurance Cost"",
    ""MXN Net Payment"",
    ""Is Enrolled in Health Insurance?"",
    ""Uses TPS"",
    ""Hiring date"",
  ];
  public propertyKeys: string[];
  public propertyKeysExport: string[];

  public data = [];
  public dataExport = [];
  constructor(
    public apiService: ApiService,
    private modalService: NgbModal,
    private toastr: ToastrService
  ) {}

  ngOnInit() {
 
  }
  ngOnChanges() {
    this.createTableData();
  }

  createTableData() {
    this.propertyKeys = Object.keys(new SalaryDataModel());
    this.data =
      this.salariesCard &amp;&amp; this.salariesCard.shownProfiles ?
      this.salariesCard.shownProfiles.map((p) =&gt; {
        let salary: SalaryDataModel = new SalaryDataModel();
        salary.id = p.id;
        salary.role = this.roleNamesByProfileId[p.id];
        salary.name = p.firstName + "" "" + p.lastName;
        salary.client = this.salariesCard.getClientName(p);
        salary.mxnAmount =
          p.monthlyOfferedNetSalaryCurrencyId == 2 ?
          p.monthlyOfferedNetSalary :
          p.monthlyOfferedNetSalary * this.exchangeRate;
        salary.usdAmount =
          p.monthlyOfferedNetSalaryCurrencyId == 1 ?
          p.monthlyOfferedNetSalary :
          p.monthlyOfferedNetSalary / this.exchangeRate;
        salary.paymentCurrency =
          p.monthlyOfferedNetSalaryCurrencyId == 1 ? ""USD"" : ""MXN"";
        salary.mxnInsuranceCost = p.monthlyInsuranceCost;
        salary.mxnNetPayment = this.getNetPayment(p);
        salary.isEnrolledInHealthInsurance =
          p.isEnrolledInHealthInsuranceBonus;
        salary.isPaymentHold = p.isPaymentHold;

        salary.profile = p;

        return salary;
      }) :
      null;
  }


export class SalaryDataModel {
  id: number = 0;
  role: string = """";
  name: string = """";
  client: string = """";
  mxnAmount: number = 0;
  usdAmount: number = 0;
  paymentCurrency: string = """";
  mxnInsuranceCost: number = 0;
  mxnNetPayment: number = 0;
  isEnrolledInHealthInsurance ? : boolean = false;
  isPaymentHold: boolean = false;
  profile: ProfileModel;
}
export class SalaryDataModelExport {
  id: string = """";
  role: string = """";
  name: string = """";
  client: string = """";
  mxnAmount: number = 0;
  usdAmount: number = 0;
  paymentCurrency: string = """";
  mxnInsuranceCost: number = 0;
  mxnNetPayment: number = 0;
  isEnrolledInHealthInsurance ? : boolean = false;
  profile: ProfileModel;
  TXP: string = """";
  HiringDate: string = """";
}</code></pre>
</div>
</div>
</p>
<p>So, as you can see I try to access to:
<code>expect(fixture.componentInstance.data.length).toBe(1);</code>, but the length is always 0, this is weird because I specifying the value on:</p>
<pre><code>mockCashFlowService.createTableData.and.returnValue(of(data))
</code></pre>
<p>Why the data value is not detecting that I set the property on the test?</p>
",https://stackoverflow.com/questions/75167220/unit-testing-does-not-fill-the-component-object,"['javascript', 'angular', 'typescript', 'jasmine', 'karma-jasmine']",29,False,0,0
Unit testing plpgsql procedure which has TYPE data,"<p>we have a TYPE t_string_array in our postgres database defined as character varying[].</p>
<p>We have a stored procedure which takes list of names and  gives the result out in a cursor.</p>
<pre><code>the procedure definition is 
create or replace procedure test_lookup( in_speed t_string_array, inout display refcursor, 
 inout out_error_text TEXT);

I am trying to test this procedure with the block

do
$$
declare 
display refcursor;
out_error_text text;
begin
  call test_lookup(['Basic']::t_string_array,display::refcursor,out_error_text::text);

    RAISE NOTICE 'mymsg1 = %', out_error_text;
   RAISE NOTICE 'myvar1 = %', out_error_code;
END;
$$


I am getting error ERROR:  syntax error at or near &quot;[&quot;

I tried using call test_lookup('basic'::t_string_array,display::refcursor,out_error_text::text)

call test_lookup(array['basic']::character varying[],display::refcursor,out_error_text::text);

all gave me error.

Can you please suggest a way to test this procedure.
</code></pre>
",https://stackoverflow.com/questions/75341860/unit-testing-plpgsql-procedure-which-has-type-data,['postgresql'],31,False,0,0
Mock or spyOn location.reload in angular unit testing,"<p>I have the function with <code>location.reload()</code>. How to write the angular unit test cases for test that reload functionality.</p>
<pre><code>searchregion(){
location.reload();
}
</code></pre>
<p>I tried to written the test cases like below. But it shows error &quot;Error:  : could not find an object to spy upon reload()&quot;:</p>
<pre><code>it('should test the reload functions', () =&gt;{
spyOn(location, 'reload');
component.searchregion();
expect(location.reload).toHaveBeenCalled();
});
</code></pre>
<p>Can anyone please help me on this?</p>
",https://stackoverflow.com/questions/75381656/mock-or-spyon-location-reload-in-angular-unit-testing,"['karma-jasmine', 'reload', 'angular-unit-test']",61,False,0,0
Unit testing guard applied at nestjs controller level,"<p>NestJS backend with the following controller with multiple routes inside:</p>
<pre><code>...
@UseGuards(CustomGuard)
@Controller('pages')
export class PagesController {
...
</code></pre>
<p>As you can see CustomGuard is applied at controller level, not at individual route level. I need that guard for all the routes in controller. How can I unit test if the CustomGuard is applied to the controller?</p>
<p>Checked <a href=""https://stackoverflow.com/questions/59767377/how-can-i-unit-test-that-a-guard-is-applied-on-a-controller-in-nestjs"">this thread</a>, but the responses describe only testing if individual methods have the guard.</p>
",https://stackoverflow.com/questions/75776652/unit-testing-guard-applied-at-nestjs-controller-level,"['jestjs', 'nestjs']",23,False,0,0
How to set HttpResponse Header for Unit Testing,"<p>I have to write a unit test for a function that Imports and Converts a Cvs file to Components
To make that work I initialised the Controllers HtpContext in the Test. as follows</p>
<pre><code>public async Task Parse_ValidCsv()
{
    //*
    Test Data is implemented here 
    *// 
   var controller = _provider.GetService&lt;ComponentController&gt;();
            var content = new MultipartFormDataContent();
            var streamContent = new StreamContent(new                           

    MemoryStream(Encoding.UTF8.GetBytes(_fileContent)));
            content.Add(streamContent, &quot;file&quot;, &quot;file.csv&quot;);


    controller.ControllerContext = new ControllerContext();
    controller.ControllerContext.HttpContext = new DefaultHttpContext();
    controller.ControllerContext.HttpContext.Request.Headers.ContentType =   
    content.Headers.ContentType.ToString();
    controller.ControllerContext.HttpContext.Request.Body = await content.ReadAsStreamAsync();
    var response = await controller.Parse() as JsonResult;
    _jobs = response?.Value as Dictionary&lt;string, Guid&gt;;
    var dictionary = _jobs;
    Guid id;
    _jobs.TryGetValue(&quot;job&quot;, out id);
    var resultSetNew = await controller.GetImportJobResults(id, 1, 0, 5,&quot;&quot;,&quot;&quot;).ToListAsync();
...

}
</code></pre>
<p>That works so far and in the Debug Mode i can see that the Components are correctly parsed.
The error i encounterd now happens in following function</p>
<pre><code> private IQueryable&lt;T&gt; QueryResults&lt;T&gt;(IQueryable&lt;T&gt; query, int? skip, int? take, string orderBy,  
 string filter, bool supportWildcards = false, bool updateHeaders = false)
{
    if (!string.IsNullOrWhiteSpace(filter)) query = query.Where(supportWildcards ?   
         filter.TreatQueryNonWordCharactersAsWildcard() : filter);
    if (!string.IsNullOrWhiteSpace(orderBy)) query = query.OrderBy(orderBy);

    var count = query.Count();
    var range = (take.HasValue, skip.HasValue) switch
    {
        (true, true) =&gt; $&quot;{Math.Min(skip.Value, count - 1)}-{Math.Min(skip.Value + take.Value - 1,     
        count - 1)}&quot;,
        (true, false) =&gt; $&quot;0-{Math.Min(take.Value - 1, count - 1)}&quot;,
        (false, true) =&gt; $&quot;{Math.Min(skip.Value, count - 1)}-{count - 1}&quot;,
        (false, false) =&gt; &quot;*&quot;
     };

     if (updateHeaders) Response.Headers.ContentRange = $&quot;entries {range}/{count}&quot;;
     if (skip.HasValue) query = query.Skip(skip.Value);
     if (take.HasValue) query = query.Take(take.Value);
            
     return query;
}
</code></pre>
<p>In the Line if (updateHeaders) Response.Headers.ContentRange = $&quot;entries {range}/{count}&quot;;
A Null Exception is thrown. How do i initialize the Response.Headers correctly?</p>
<p>I tried setting the headers in the Arrange Part but because it is readonly i cannot do it.</p>
",https://stackoverflow.com/questions/76128160/how-to-set-httpresponse-header-for-unit-testing,"['c#', 'unit-testing', 'model-view-controller', 'controller', 'httpresponse']",30,False,0,0
Unit testing of Wire with ArduinoFake in PlatformIO,"<p>I'm creating unit tests in PlatformIO using Unity with the ArduinoFake library
I'm trying to test a piece of code that uses the Wire library</p>
<p>When I try to run the unit test (env:native), it complains that the build cannot find &lt;Wire.h&gt;</p>
<p>my platformio.ini file has the following...</p>
<pre><code>[env:native]
lib_deps = fabiobatsilva/ArduinoFake@^0.3.1
</code></pre>
<p>If I comment out <em>#include &lt;Wire.h&gt;</em> in the code under test, then the unit test works, so I assume the &lt;Arduino.h&gt; supplied by the ArduinoFake library also provides the necessary references for Wire - but then the build for the Uno platform fails because there's no reference to Wire.h</p>
<p>Anyone used ArduinoFake to test code using Wire? - how did you resolve this?</p>
",https://stackoverflow.com/questions/75391744/unit-testing-of-wire-with-arduinofake-in-platformio,"['unit-testing', 'arduino']",101,False,0,1
problem in WordPress unit testing single post page,"<p>I am working on a WordPress custom theme that has a right sidebar and after importing WordPress unit test xml to test my them I found that when I open any post from the imported post, it displays the sidebar under the post content after checking the page code by chrome developer tools that I found an extra div close is add, but when I open any post that I created from scratch, sidebar is displayed correctly on the right side</p>
<p>what may be the problem?</p>
",https://stackoverflow.com/questions/75786668/problem-in-wordpress-unit-testing-single-post-page,"['wordpress', 'wordpress-theming', 'custom-wordpress-pages', 'wordpress-rest-api']",11,False,0,0
PyCharm: Unit testing directory setup with remote interpreter,"<p>For years I've been running a Docker container on my local machine and using it as a remote Python interpreter via SSH in PyCharm. This works great (though 2022.2.1 brought a lot of new bugs that have been slowly being ironed out) for running my code! I'm now on 2022.2.3.</p>
<p>However, I'm having issues running unit tests. In the past (i.e. before version 2022.2.1), I could simply right click my tests directory (a direct child of my main project directory) and click <code>Run Python tests in test...</code> and it would all work as expected.</p>
<p>Now, though, when I click this, I receive an error message about &quot;No such file or directory.&quot;</p>
<p>I've tried everything I can think of- I've setup my path mappings in the Python test run config to exactly match those shown in my Python run config, and have tried every version of directory and subdirectory in the mappings and working directory, but I always receive an error about either having an empty test suite (no tests found), or that the directory &quot;must be in the project.&quot;</p>
<p>It seems like no matter what I do, PyCharm is trying to create a temp directory somewhere, or is trying to read from some temp directory that I never specified, because I see errors this like:</p>
<p><code>AssertionError: /tmp/pycharm_project_405/docker/tests: No such file or directory</code></p>
<p>Yet I never created, specified, or requested a temp directory of any sort, let alone one named <code>/tmp/pycharm_project_405/</code>; this is a mystery to me.</p>
<p>PyCharm with an SSH interpreter is rapidly becoming unusable for me and my team because we cannot figure out how to set this up. Can anybody please offer some guidance on what we need to do?</p>
<p>Thank you all so very much!</p>
<p>I tried:</p>
<ul>
<li>Changing run config for Python tests to match the working directory and path mapping of Python run configs (which work)</li>
<li>Directly specifying the path to the tests <em>from the container's perspective</em></li>
<li>Setting up run config templates</li>
<li>Specifying one directory up/down from the actual tests</li>
</ul>
<p>Expected:
Unit tests to be found and run as they were in previous versions of PyCharm</p>
",https://stackoverflow.com/questions/74998709/pycharm-unit-testing-directory-setup-with-remote-interpreter,"['docker', 'unit-testing', 'ssh', 'pycharm', 'interpreter']",106,True,0,1
EXPECT unit testing function behaviour in KDB/q,"<p>I am working on writing a unit-test in kdb+/q and trying to understand the expect function which seems to take the format:</p>
<pre><code>EXPECT[`function.name;1;ANY]
</code></pre>
<p>I could not find documentation on the function, or the function definition on the kdb/qunit github repo.</p>
<p>My assumptions, based on how the function looks were that the format covers:</p>
<pre><code>EXPECT[`.function.name;return value; input params]
</code></pre>
<p>However, changing the return value to anything but 1 raises errors, and when running the tests, despite writing an expect line, the function seems to be called with the original input parameters and tries to perform the calculation, rather than returning 1.</p>
<p>I was wondering if someone could provide an example of the EXPECT should behave?</p>
",https://stackoverflow.com/questions/75207884/expect-unit-testing-function-behaviour-in-kdb-q,['kdb'],68,False,0,0
Angular Unit testing : Error: Cannot match any routes,"<p>I Am working on unit testing under my angular 15 app. I am getting the below error while running the test:</p>
<p>Error: Cannot match any routes.URL Segment: 'signin'</p>
<p>Below is the unit test code for my component:</p>
<pre><code> fdescribe('ExtensionListComponent',()=&gt;{
   BeforeEach(() =&gt; {
     TestBed.configureTestingModule({
       imports: [
        RouteTestingModule.withRoutes([{
        path: 'extensions-list',
       component: ExtensionListComponent}]),
       HttpClientTestingModule
       ],
       declarations:[
       ExtensionListComponent
       ],
       providers: [
       TaskService
       ]
  }).compileComponents();
 });
</code></pre>
",https://stackoverflow.com/questions/75170240/angular-unit-testing-error-cannot-match-any-routes,"['angular', 'jasmine', 'angular-test']",47,True,0,1
Unit testing monaco editor renders only first line,"<p>I am using vite+vitest for my project. I installed <code>vitest-canvas-mock</code> and its successful in running the tests.
But it is rendering only the first line in the code. I am not able to add text or see any other features.</p>
<p>Did anyone figure out how to write proper unit tests involving monaco-editor.</p>
<p>We are heavily invested in monaco-editor and it would be good to be able to write unit tests.</p>
",https://stackoverflow.com/questions/75447247/unit-testing-monaco-editor-renders-only-first-line,"['unit-testing', 'monaco-editor', 'jsdom']",89,True,0,1
Unit Testing retry on http request in angular service,"<p>I am trying to test <code>retry</code> on a failed httpClient post request without using a for loop and I am having a hard time finding an example of doing so. Most solutions seem to show the for loop method.</p>
<p>Here is the service code and test in question. This currently works as expected, how can I do it the rxjs observable functional way?</p>
<p>Service code:</p>
<pre><code>public getUsers(): Observable&lt;UsersResponse&gt; {
    return this.httpClient.post&lt;UsersResponse&gt;(`${usersUrl}/fetchall`, '').pipe(
      retry(3),
      catchError(() =&gt; {
        return of({} as UsersResponse)
      }),
    )
  }
</code></pre>
<p>Test:</p>
<pre><code>  it('getUsers should return an empty value on error', () =&gt; {
    sub = usersService
      .getUsers()
      .pipe(
        tap((res) =&gt; {
          expect(res).toEqual({} as UsersResponse)
        }),
      )
      .subscribe()
    for (let i = 0, c = retryCount + 1; i &lt; c; i++) {
      const req = httpMock.expectOne('/api/fetchall')
      req.flush({}, { status: 404, statusText: 'Not Found' })
    }
  })
</code></pre>
",https://stackoverflow.com/questions/75726592/unit-testing-retry-on-http-request-in-angular-service,"['angular', 'unit-testing', 'rxjs', 'jasmine']",88,False,2,1
Node.js Unit Testing request.post(...).send is not a function,"<p>I am beginning to test the components of my node.js website using chai and mocha, but when I run npm test I get this error:</p>
<p>' TypeError: request.post(...).send is not a function'</p>
<p>This is the code in my test.js file:</p>
<pre><code>    const chai = require(&quot;chai&quot;);
const expect = chai.expect;
const app = require(&quot;./app.js&quot;);
const express = require(&quot;express&quot;);
const request = express();

describe(&quot;POST /register&quot;, () =&gt; {
  it(&quot;should register a new user and redirect to login page&quot;, (done) =&gt; {
    const user = {
      email: &quot;johndoe@example.com&quot;,
      username: &quot;johndoe&quot;,
      password: &quot;password&quot;,
      userType: &quot;user&quot;
    };
    request.post(&quot;/register&quot;)
      .send(user)
      .end((err, res) =&gt; {
        expect(res.status).to.equal(302);
        expect(res.header.location).to.equal(&quot;/login&quot;);
        done();
      });
  });
});
</code></pre>
<p>I am new to Node.js so I'm still understanding how unit tests are executed. any help would be a appreciated</p>
",https://stackoverflow.com/questions/76181871/node-js-unit-testing-request-post-send-is-not-a-function,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'chai']",48,False,2,2
Create list of imports service provider on unit testing,"<p>I'm new to Angular, and I have a new team that told me to implement unit testing on an old project with Angular 8. So after investigating that, I decided to use Karma + Jasmine, and I created <code>.spect.ts</code> document like this:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>describe(""CashFlowSalariesComponent"", () =&gt; {
      let fixture: ComponentFixture &lt; CashFlowSalariesComponent &gt; ;
      let instance;
      let profile: ProfileModel;

      beforeEach(async() =&gt; {
        TestBed.configureTestingModule({
          schemas: [CUSTOM_ELEMENTS_SCHEMA],
          imports: [
            RouterTestingModule,
            FormsModule,
            ReactiveFormsModule,
            BrowserModule,
            HttpClientModule,
            ToastrModule.forRoot({
              positionClass: ""toast-bottom-right"",
            }),
          ],
          declarations: [CashFlowSalariesComponent],
          providers: [
             ApiService,
    UserService,
    ProfileService,
    VettingStatusService,
    SkillService,
    ApplicationRoleService,
    SeniorityLevelService,
    PlacementStatusService,
    EducationLevelService,
    UtilsService,
    ShirtSizeService,
    GenderService,
    TimeZoneService,
    CountryService,
    CityService,
    PostalCodeService,
    StateService,
    ClientSectorService,
    JobService,
    ClientService,
    PulsecheckQuestionService,
    PulsecheckMasterService,
    ExchangeRateService,
    DepartmentService,
    ExpenseService,
    ProfileRoleService,
    SkillCategoriesService,
    ProfileActivityService,
    ProfileSalaryActivityService,
    TimeSheetService,
    HolidayService,
    RequestTimeOffService,
    TimeOffTypeService,
    InvoiceService,
    PulsecheckDetailService,
          ],
        }).compileComponents();

        fixture = TestBed.createComponent(CashFlowSalariesComponent);
        instance = fixture.componentInstance;

        fixture.detectChanges();

        profile = new ProfileModel();
        (instance as any).exchangeRate = 18.92;
      });

      afterEach(() =&gt; {
        fixture.destroy();
      });

      it(""To test instance creation of component"", () =&gt; {
        expect(instance).toBeTruthy();
      });</code></pre>
</div>
</div>
</p>
<p>As you can see, I had to import many services from providers because my ApiService had injected them, so if I no add them, it returned an error like this:</p>
<blockquote>
<p>NullInjectorError: No provider for {serviceName}!</p>
</blockquote>
<p>So each time I call the ApiService on each component, developers should copy and paste from this component all the services. So my question is: is this a way to create a class or something to import all providers in once without copying and pasting code each time? How can I achieve this?</p>
",https://stackoverflow.com/questions/75197251/create-list-of-imports-service-provider-on-unit-testing,"['javascript', 'angular', 'typescript', 'jasmine', 'karma-jasmine']",75,True,1,1
Unit testing view model that depends on a publisher,"<p>I implemented a service class with a function that returns a publisher when some data is loaded:</p>
<pre><code>class Service {
    let fileURL: URL // Set somewhere else in the program

    func loadModels() -&gt; AnyPublisher&lt;[MyModelClass], Error&gt; {
        URLSession.shared.dataTaskPublisher(for: fileURL)
            .map( { $0.data } )
            .decode(type: [MyModelClass].self, decoder: JSONDecoder())
            .receive(on: DispatchQueue.main)
            .eraseToAnyPublisher()
    }
}
</code></pre>
<p>This function is used in my view model class like this:</p>
<pre><code>class ViewModel: ObservableObject {
    @Published var models: [MyModelClass]?
    
    var cancellables = Set&lt;AnyCancellable&gt;()
    let service: Service
    
    init(service: Service) {
        self.service = service
        loadCityData()
    }
    
    func loadModels()  {
        service.loadModels()
            .sink { _ in
            } receiveValue: { [weak self] models in
                self?.models = models
            }
            .store(in: &amp;cancellables)
    }
}
</code></pre>
<p>I find the view model difficult to unit-test because I don't have the publisher returned from the service available directly in my unit test class, but I have the @Published property instead. So I tried to implement a test like this one:</p>
<pre><code>let expectation = expectation(description: &quot;loadModels&quot;)

viewModel.$models
    .receive(on: RunLoop.main)
    .sink(receiveCompletion: { _ in
        finishLoading.fulfill()
    }, receiveValue: { _ in
    })
    .store(in: &amp;cancellables) // class-scoped property

viewModel.loadModels()

wait(for: [expectation], timeout: 10)
</code></pre>
<p>The problem is that the receiveComplection callback is never called. If I had the publisher available (the one returned from the Service object), the same code applied to the publisher would run successfully and fulfill the expectation. Instead, the complection is not being called but the receiveValue is being called multiple times. Why?</p>
",https://stackoverflow.com/questions/75233539/unit-testing-view-model-that-depends-on-a-publisher,"['swift', 'combine']",185,False,1,2
Golang dependency injection for mock database in unit testing,"<p>I am creating a mock database with Golang interfaces to test my handler function. However, I don't seem to be performing the dependency injection correctly in my unit testing environment. I have created a <code>setup_test.go</code> file to set up my mock database environment. In the code snippets below, I will go over the flow of how my dependency injection works.</p>
<ol>
<li><code>main.go</code></li>
</ol>
<pre class=""lang-golang prettyprint-override""><code>package main

type application struct {
    DB repository.DatabaseRepo
}

func main() {
    app := application{}

    conn, err := app.connectToDB()
    if err != nil {
        log.Fatal(&quot;Failed to connect to PostgreSQL:&quot;, err)
    }

    defer func() {
        conn.Close(context.Background())
    }()

    app.DB = &amp;dbrepo.PostgresDBRepo{DB: conn}

    // Passing app.DB to routes function for DI
    mux := routes.Routes(app.DB)
</code></pre>
<pre class=""lang-golang prettyprint-override""><code>package repository

type DatabaseRepo interface {
    Connection() *pgx.Conn
    GetCountByUsername(ctx context.Context, username string) (int, error)
}
</code></pre>
<ol start=""2"">
<li><code>routes.go</code></li>
</ol>
<pre class=""lang-golang prettyprint-override""><code>package routes

func Routes(app repository.DatabaseRepo) http.Handler {
    mux := chi.NewRouter()

    signUpH := user.New(app)
    mux.Post(&quot;/signup&quot;, utils.MakeHTTPHandler(signUpH.SignUp))
}
</code></pre>
<ol start=""3"">
<li><code>SignUp.go</code> <br>
The code fails at this line which is calling the database. I have set up my mock database in point 4 in <code>setup_test.go</code>. This is the error message I am getting &quot;panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation ...]&quot;.</li>
</ol>
<pre class=""lang-golang prettyprint-override""><code>package user

type application struct {
    DB repository.DatabaseRepo
}

// Dependency Injection of Repository (Database)
func New(app repository.DatabaseRepo) *application {
    return &amp;application{DB: app}
}

func (app application) SignUp(w http.ResponseWriter, req *http.Request) error {
    // some other logic

    // When I run `go run .`, this prints out to be *dbrepo.PostgresDBRepo
    // When I run `go test -v ./...`, this prints out to be &lt;nil&gt; 
    // but the expected type should be *dbrepo.TestDBRepo
    fmt.Printf(&quot;Type of app.DB: %T\n&quot;, app.DB)

    // fails on this line in unit testing
    userCount, err := app.DB.GetCountByUsername(ctx, Username)

    // some other logic
}
</code></pre>
<ol start=""4"">
<li><code>setup_test.go</code></li>
</ol>
<pre class=""lang-golang prettyprint-override""><code>package main

var app application

func TestMain(m *testing.M) {

    app.DB = &amp;dbrepo.TestDBRepo{}

    fmt.Printf(&quot;Type of app.DB: %T\n&quot;, app.DB) // output type is *dbrepo.TestDBRepo

    os.Exit(m.Run())
}
</code></pre>
<p>I have seen many unit testing for similar mock database using this approach but they usually do it within the same package main which will not have this issue if you have nested folders and packages like mine.</p>
<p>What can I try next?</p>
",https://stackoverflow.com/questions/75857122/golang-dependency-injection-for-mock-database-in-unit-testing,"['unit-testing', 'go']",148,True,1,1
How to set a System.Type property for unit testing?,"<p>I've got a class that has a property of type Type. How can I set this for unit testing?</p>
<p>Example class:</p>
<pre><code>public class School
{
    public string Name { get; set; }
    public Type SchoolType { get; set; }
}
</code></pre>
<p>I can mock the Name but I'm not sure how to mock the SchoolType property.</p>
<p>Example test:</p>
<pre><code>string expectedName = &quot;Richmond&quot;;
var expectedType = ???

var school = new School();
school.Name = expectedName;
school.SchoolType = expectedType;

Assert.AreEqual(expectedName, school.Name);
Assert.AreEqual(?, school.SchoolType);
</code></pre>
",https://stackoverflow.com/questions/75135603/how-to-set-a-system-type-property-for-unit-testing,"['c#', 'unit-testing', 'types']",40,True,1,1
Nestjs can&#39;t resolve dependencies of the AppConfigService (Unit Testing),"<p>I am trying to set up Jest Unit Testing to my project, but I'm getting the following errors when trying to Unit Test:</p>
<p><a href=""https://i.stack.imgur.com/GVICh.png"" rel=""nofollow noreferrer"">Erro Message (Screenshot)</a></p>
<p>How do I fix this issue?</p>
",https://stackoverflow.com/questions/75292294/nestjs-cant-resolve-dependencies-of-the-appconfigservice-unit-testing,"['testing', 'nestjs']",28,False,0,2
Unit Testing Arduino ESP8266 in CI (Native) with libraries,"<p>I am using an Arduino <code>ESP8266</code> with <code>platformio</code>. I am adding Unit Testing with the <code>Unity</code> framework and I want to run the tests in Gitlab <code>CI</code>. In my project, I use other libraries, such as <code>ESP8266WiFi</code>.</p>
<p>I am using the <code>Native</code> platform to run tests and my <strong>platformio.ini</strong> file looks like this:</p>
<pre><code>[platformio]
default_envs = esp01

[env]
lib_deps = 
    dancol90/ESP8266Ping@^1.0

[env:esp01]
platform = espressif8266
framework = arduino
board = esp01
; Serial Monitor options
monitor_speed = 115200

[env:native]
; Testing without HW in CI, I am using this
platform = native
lib_deps = 
    ${env.lib_deps}
    fabiobatsilva/ArduinoFake@^0.3.1
; Coverage:
lib_compat_mode = off
build_src_filter = +&lt;*&gt; -&lt;*dirs*&gt; -&lt;to/&gt; -&lt;exclude/&gt;
build_flags =
  -lgcov
  --coverage
extra_scripts = ci/test_coverage.py
</code></pre>
<p>My <strong>test</strong> would be something like this:</p>
<pre><code>#include &lt;unity.h&gt;
#include &quot;data.h&quot;

void test_1(void) {
  uint8_t mode = get_value();
  TEST_ASSERT_EQUAL(mode, 0);
}

int main(int argc, char **argv) {
    UNITY_BEGIN();

    RUN_TEST(test_1);

    return UNITY_END();
}
</code></pre>
<p>My simplified <strong>code</strong> would be (data.cpp file):</p>
<pre><code>#include &lt;ESP8266WiFi.h&gt;

uint8_t mode = 0;
uint8_t get_value(){
  return mode;
}
</code></pre>
<p>The compilation is working fine with <code>pio run</code>.
I am running this command to run the tests:</p>
<pre><code>pio test -e native -vvv
</code></pre>
<p>The error is:</p>
<pre><code>test\test_main.cpp:2:25: fatal error: ESP8266WiFi.h: No such file or directory
</code></pre>
<p>Maybe <code>ArduinoFake</code> can't emulate this library? Or should I include the library somehow? Or can't I Unit Test the way I am trying to do it?</p>
<p>If I have this test without importing my code, the test passes:</p>
<pre><code>#include &lt;unity.h&gt;
// #include &quot;data.h&quot;

void test_1(void) {
  //uint8_t mode = get_value();
  TEST_ASSERT_EQUAL(0, 0);
}

int main(int argc, char **argv) {
    UNITY_BEGIN();

    RUN_TEST(test_1);

    return UNITY_END();
}
</code></pre>
",https://stackoverflow.com/questions/75790142/unit-testing-arduino-esp8266-in-ci-native-with-libraries,"['c++', 'continuous-integration', 'platformio', 'unity-test-framework']",87,True,0,1
unit testing issue with IDataProtectionProvider in ASP.NET Core MVC,"<p>I want to unit test a my action method in my ASP.NET Core MVC controller, but I get this error, please help.</p>
<blockquote>
<p>Message:
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: POSModels.CryptoParamsProtector.
Could not find a parameterless constructor.</p>
<p>Stack Trace:<br />
ProxyGenerator.CreateClassProxyInstance(Type proxyType, List<code>1 proxyArguments, Type classToProxy, Object[] constructorArguments) ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)   CastleProxyFactory.CreateProxy(Type mockType, IInterceptor interceptor, Type[] interfaces, Object[] arguments) line 62   Mock</code>1.InitializeInstance() line 311<br />
Mock<code>1.OnGetObject() line 325   Mock.get_Object() line 179   Mock</code>1.get_Object() line 283<br />
UnitTypesControllerTests.initController(Object obj) line 80<br />
UnitTypesControllerTests.IndexTest() line 86</p>
</blockquote>
<p>This is my unit test code and error is thrown from the last line in <code>initController</code> method.</p>
<pre><code>namespace PWEB.Controllers.Tests
{
    using Xunit;

    public class UnitTypesControllerTests
    {
        private Mock&lt;IHttpContextAccessor&gt; contextAccessor;
        private UnitTypesController unitTypesController;
        private Mock&lt;NetCorePOSSystemConfig&gt; config;
        private Mock&lt;IHttpClientFactory&gt; httpClientFactory;
        private Mock&lt;Microsoft.Extensions.Options.IOptions&lt;NetCorePOSSystemConfig&gt;&gt; configure;
        private Mock&lt;Microsoft.AspNetCore.Http.HttpContext&gt; mockHttpContext;
        private Mock&lt;MockHttpMessageHandler&gt; mock;
        private Mock&lt;CryptoParamsProtector&gt; cryptoParams;
        PaginationEntity&lt;UnitTypeModel&gt; paginationEntity = new PaginationEntity&lt;UnitTypeModel&gt;()
        {
            Items = new List&lt;UnitTypeModel&gt;(),
            MetaData = new PaginationMetaData()
            {
                Count = 1,
                TotalItemCount = 1,
                PageNumber = 1,
                FirstItemOnPage = 1,
                HasNextPage = false,
                HasPreviousPage = false,
                IsFirstPage = true,
                IsLastPage = false,
                LastItemOnPage = 1,
                PageCount = 1,
                PageSize = 20
            }
        };

        public UnitTypesControllerTests()
        {
            cryptoParams = new Mock&lt;CryptoParamsProtector&gt;(MockBehavior.Strict);
            mock = new Mock&lt;MockHttpMessageHandler&gt;(MockBehavior.Strict);
        }

        private void initController(object obj)
        {
            string value = &quot;1&quot;;
            byte[] val = new byte[] { 1 };             
            mock.Protected().Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;(&quot;SendAsync&quot;, ItExpr.IsAny&lt;HttpRequestMessage&gt;(), ItExpr.IsAny&lt;CancellationToken&gt;()).ReturnsAsync(new HttpResponseMessage()
            {
                Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(obj), System.Text.Encoding.UTF8, &quot;application/json&quot;),
                StatusCode = System.Net.HttpStatusCode.OK
            }).Verifiable();
            var client = new HttpClient(mock.Object)
            {
                BaseAddress = new Uri(&quot;http://xxxxxxxxxxxxxx&quot;)
            };

            httpClientFactory = new Moq.Mock&lt;IHttpClientFactory&gt;();
            httpClientFactory.Setup(x =&gt; x.CreateClient(It.IsAny&lt;string&gt;())).Returns(client);

            config = new Mock&lt;NetCorePOSSystemConfig&gt;();
            contextAccessor = new Mock&lt;IHttpContextAccessor&gt;();
            mockHttpContext = new Mock&lt;Microsoft.AspNetCore.Http.HttpContext&gt;();

            Mock&lt;ISession&gt; mocks = new Mock&lt;ISession&gt;();
            mocks.Setup(c =&gt; c.Set(&quot;JWToken&quot;, It.IsAny&lt;byte[]&gt;())).Callback&lt;string, byte[]&gt;((k, v) =&gt; value = v.ToString());
            mocks.Setup(v =&gt; v.TryGetValue(&quot;JWToken&quot;, out val)).Returns(true);
            mockHttpContext.Setup(v =&gt; v.Session).Returns(mocks.Object);
            contextAccessor.Setup(x =&gt; x.HttpContext).Returns(mockHttpContext.Object);
            configure = new Mock&lt;Microsoft.Extensions.Options.IOptions&lt;NetCorePOSSystemConfig&gt;&gt;();
            unitTypesController = new UnitTypesController(cryptoParams.Object, httpClientFactory.Object, configure.Object, contextAccessor.Object);
        }

        [Fact()]
        public void IndexTest()
        { 
                initController(paginationEntity);
                ViewResult result = unitTypesController.Index(1).Result as ViewResult;
                mock.Verify();
                Assert.IsType&lt;StaticPagedList&lt;UnitTypeModel&gt;&gt;(result.ViewData.Model);
            
        }
}
</code></pre>
<p>My controller is look like this,</p>
<pre><code>public class UnitTypesController : Controller
    {
        private readonly HttpClient _httpClient;
        private readonly IOptions&lt;NetCorePOSSystemConfig&gt; _options; 
        private readonly IHttpContextAccessor contextAccessor;
        private readonly CryptoParamsProtector cryptoParams;
       

        public UnitTypesController(CryptoParamsProtector paramsProtector, IHttpClientFactory httpClientFactory, IOptions&lt;NetCorePOSSystemConfig&gt; config, IHttpContextAccessor httpContext)
        {
           //code          
             ..................
        }
}
</code></pre>
<p>encryption class look like this,</p>
<pre><code>public class CryptoParamsProtector
    {
            IDataProtector _protector;

            public CryptoParamsProtector(IDataProtectionProvider dataProtectionProvider)
            {
                _protector = dataProtectionProvider.CreateProtector(GetType().FullName);
            }

            // ...........
    }
</code></pre>
",https://stackoverflow.com/questions/75451334/unit-testing-issue-with-idataprotectionprovider-in-asp-net-core-mvc,"['c#', 'unit-testing', 'asp.net-core-mvc']",77,False,0,1
Angular unit testing Unhandled promise rejection: ObjectUnsubscribedError: object unsubscribed,"<p>while testing code facing Unhandled promise rejection: ObjectUnsubscribedError: object unsubscribed.</p>
<p>how can I solve this error?</p>
",https://stackoverflow.com/questions/75256194/angular-unit-testing-unhandled-promise-rejection-objectunsubscribederror-objec,"['unit-testing', 'karma-jasmine', 'angular11']",64,False,0,0
how to mock Supabase with Flutter for unit testing?,"<p>I'm trying to do unit test with Supabase in Flutter like the code bellow:</p>
<pre><code>import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:supabase_flutter/supabase_flutter.dart';


class TestMClass {
  SupabaseClient client;
  TestMClass({
    required this.client,
  });
  Future&lt;AuthResponse&gt; signinMc() async {
    final respnse = await client.auth
        .signInWithPassword(email: 'example@gmail', password: 'password');
    return respnse;
  }
}

class MockSupabaseClient extends Mock implements SupabaseClient {}

void main() async {
  
  final MockSupabaseClient mockClient = MockSupabaseClient();

  final TestMClass testMCass = TestMClass(client: mockClient);
  setUp(() {});
  group('TestAuthBloc', () {
    test('description', () async {
      final auth = await testMCass.signinMc();
      expect(auth, isA&lt;AuthResponse&gt;());
    });
  });
}
</code></pre>
<p>it throw this error:....</p>
<blockquote>
<p>type 'Null' is not a subtype of type 'GoTrueClient'</p>
</blockquote>
<p>how I can Mock or do unit testing for Supabase functions with Flutter?</p>
",https://stackoverflow.com/questions/75953444/how-to-mock-supabase-with-flutter-for-unit-testing,"['flutter', 'dart', 'unit-testing', 'mocking', 'supabase']",195,False,0,2
method call not happening for method while unit testing,"<p>I have code like below trying to unit test it</p>
<pre><code>@Service
class MainClass {
public void simpleExe() {
webclient.post()
.uri(&quot;url&quot;)
.header(----)
.bodyValue(ReqPojo)
.retrieve()
.bodyToMono(Response.class)
.flatMap(this::add); **this line is running but the call not happening to add method**
}

private Mono&lt;Response&gt; add() {
// doing some calculation
}
}
</code></pre>
<p>Test class</p>
<pre><code>@SpringBootTest
class MainClassTest {

//mocked few other service calls

@Autowired
MainClass mainClass;
@Test
public void testsimpleExe() {
   mainClass.simpleExe();
 }
}
</code></pre>
<p><strong>this::add control coming to this line but call not happening to add method.</strong>
what could be the issue. any thing missing?</p>
",https://stackoverflow.com/questions/75054923/method-call-not-happening-for-method-while-unit-testing,"['java', 'spring-boot', 'junit', 'mockito']",83,False,0,1
Flutter unit testing - Binding has not yet been initialized,"<p>Used SharedPreference throwing error in Unit test. In one function I have used SharedPreference and during it's unit testing getting error as &quot;Binding has not yet been initialized&quot; and many other errors too.</p>
<p>Working unit test:
<a href=""https://i.stack.imgur.com/ukuPP.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ukuPP.png"" alt=""enter image description here"" /></a></p>
<p>After uncommenting SharedPreference code:
<a href=""https://i.stack.imgur.com/ullk0.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ullk0.png"" alt=""enter image description here"" /></a></p>
<p>Below is the code of my User.dart file</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>import 'package:shared_preferences/shared_preferences.dart';

class User {
  final String name;

  User(this.name);
  Future&lt;bool&gt; userName() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(""name"", name);
    return true;
  }
}</code></pre>
</div>
</div>
</p>
<p>and below is the code of test file (User_test.dart)</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>import 'dart:math';

import 'package:flutter_test/flutter_test.dart';
import 'package:unit_testf/user.dart';

void main() {
  test(""a unit test"", () async {
    User user = User(""flutter"");
    final result = await user.userName();
    expect(result, true);
  });
}</code></pre>
</div>
</div>
</p>
<p>Below is the errors I am getting.</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>Binding has not yet been initialized.
The ""instance"" getter on the ServicesBinding binding mixin is only available once that binding has been initialized.
Typically, this is done by calling ""WidgetsFlutterBinding.ensureInitialized()"" or ""runApp()"" (the latter calls the former). Typically this call is done in the ""void main()"" method. The ""ensureInitialized"" method is idempotent; calling it multiple times is not harmful. After calling that method, the ""instance"" getter will return the binding.
In a test, one can call ""TestWidgetsFlutterBinding.ensureInitialized()"" as the first line in the test's ""main()"" method to initialize the binding.
If ServicesBinding is a custom binding mixin, there must also be a custom binding class, like WidgetsFlutterBinding, but that mixes in the selected binding, and that is the class that must be constructed before using the ""instance"" getter.
package:flutter/src/foundation/binding.dart 284:9                               BindingBase.checkInstance.&lt;fn&gt;
package:flutter/src/foundation/binding.dart 366:6                               BindingBase.checkInstance
package:flutter/src/services/binding.dart 54:54                                 ServicesBinding.instance
package:flutter/src/services/platform_channel.dart 166:45                       BasicMessageChannel.binaryMessenger
package:flutter/src/services/platform_channel.dart 180:38                       BasicMessageChannel.send
package:shared_preferences_foundation/messages.g.dart 115:52                    UserDefaultsApi.getAll
package:shared_preferences_foundation/shared_preferences_foundation.dart 46:53  SharedPreferencesFoundation.getAll
package:shared_preferences/shared_preferences.dart 164:57                       SharedPreferences._getSharedPreferencesMap
package:shared_preferences/shared_preferences.dart 33:19                        SharedPreferences.getInstance
package:unit_testf/user.dart 8:55                                               User.userName
test/user_test.dart 9:31                                                        main.&lt;fn&gt;</code></pre>
</div>
</div>
</p>
<p>Below is the output of my flutter doctor command</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>Last login: Thu Feb 16 09:58:26 on console
anandsuthar@anands-MacBook-Air ~ % flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.3.10, on macOS 13.1 22C65 darwin-x64, locale en-GB)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2022.1)
[✓] VS Code (version 1.75.1)
[✓] Connected device (2 available)
[✓] HTTP Host Availability

• No issues found!
anandsuthar@anands-MacBook-Air ~ % </code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/75470485/flutter-unit-testing-binding-has-not-yet-been-initialized,"['flutter', 'dart', 'unit-testing', 'hybrid-mobile-app', 'dart-unittest']",477,True,0,1
Unit testing - how to test method calls of interface,"<p>I have a json parser that parse json of incoming signals. The parser receives an Interface of methods that can call, the method is decided by the siganl. i.e:</p>
<pre><code>{
   &quot;type&quot;: &quot;method1&quot;,
   &quot;light&quot; : false
}
</code></pre>
<p>and</p>
<pre><code>{
  &quot;type&quot;: &quot;method2&quot;,
  &quot;time&quot;: 12345
}
</code></pre>
<p>The interface looks like this:</p>
<pre><code>  interface SignalsInterface {

     fun method1(light: Boolean)
     fun method2(time: Long)
  }
</code></pre>
<p>I want to test the parser by inputing the parser with json from txt file, and check if the right method is being called. Is there a canonical way to do that? What is the industry standard?</p>
",https://stackoverflow.com/questions/74973994/unit-testing-how-to-test-method-calls-of-interface,"['android', 'kotlin', 'unit-testing']",25,True,0,1
Mocker.patch a function when unit testing a Flask blueprint,"<p>I've got a blueprint file <code>/views/index.py</code>:</p>
<pre><code>from flask import Blueprint, render_template
index = Blueprint('index', __name__)

def auth():
    return &quot;dog&quot;

@index.route('/')
def index_view():
    return render_template(
        'index.html', user=auth())
</code></pre>
<p>This is initialized fine from <code>/main.py</code>:</p>
<pre><code>from flask import Flask
from views.index import index
from views.login import login

app = Flask(__name__)
app.register_blueprint(index)
</code></pre>
<p>How can I mock the auth() function in my blueprint to return an override like &quot;cat&quot;?</p>
",https://stackoverflow.com/questions/75427436/mocker-patch-a-function-when-unit-testing-a-flask-blueprint,"['python', 'python-mock']",61,False,-1,1
UNIT TESTING SHOWS ERROR: file or directory not found:,"<p>Please, i am new to pytesting and i have been trying to run the test code file but it keeps displaying &quot;Error: file or directory not found&quot;. i need someone to put me through to know where i made mistake.
Thank you.</p>
<p><a href=""https://i.stack.imgur.com/geV4S.png"" rel=""nofollow noreferrer"">My TEST CODE</a></p>
",https://stackoverflow.com/questions/75535223/unit-testing-shows-error-file-or-directory-not-found,"['python', 'import', 'module', 'pytest']",375,True,0,1
Mocking a request object in bottle for unit testing,"<p>I am writing some test for my webapp built using bottle framework. I am using boddle to mock a request object. In the documentation of boddle, both the test function(testWoot()) and actual method(woot()) are in the same file. However, when I separate the two functions into different files,  I cant access the param sent from the mock request(keyError when trying to access name). Any idea how to fix this.</p>
<pre><code>import bottle, unittest
from boddle import boddle


@bottle.get('/woot')
def woot():
  return bottle.request.params['name']


class TestIt(unittest.TestCase):
  def testWoot(self):
    with boddle(params={'name':'derek'}):
      self.assertEqual(woot(), 'derek')


if __name__=='__main__':
  unittest.main()
</code></pre>
",https://stackoverflow.com/questions/75596172/mocking-a-request-object-in-bottle-for-unit-testing,"['python-unittest', 'bottle']",25,False,0,0
Nestjs can&#39;t resolve dependencies of the AppConfigService (Unit Testing),"<p>I am trying to set up Jest Unit Testing to my project, but I'm getting the following errors when trying to Unit Test:</p>
<p><a href=""https://i.stack.imgur.com/GVICh.png"" rel=""nofollow noreferrer"">Erro Message (Screenshot)</a></p>
<p>How do I fix this issue?</p>
",https://stackoverflow.com/questions/75292294/nestjs-cant-resolve-dependencies-of-the-appconfigservice-unit-testing,"['testing', 'nestjs']",28,False,0,2
Unit Testing Arduino ESP8266 in CI (Native) with libraries,"<p>I am using an Arduino <code>ESP8266</code> with <code>platformio</code>. I am adding Unit Testing with the <code>Unity</code> framework and I want to run the tests in Gitlab <code>CI</code>. In my project, I use other libraries, such as <code>ESP8266WiFi</code>.</p>
<p>I am using the <code>Native</code> platform to run tests and my <strong>platformio.ini</strong> file looks like this:</p>
<pre><code>[platformio]
default_envs = esp01

[env]
lib_deps = 
    dancol90/ESP8266Ping@^1.0

[env:esp01]
platform = espressif8266
framework = arduino
board = esp01
; Serial Monitor options
monitor_speed = 115200

[env:native]
; Testing without HW in CI, I am using this
platform = native
lib_deps = 
    ${env.lib_deps}
    fabiobatsilva/ArduinoFake@^0.3.1
; Coverage:
lib_compat_mode = off
build_src_filter = +&lt;*&gt; -&lt;*dirs*&gt; -&lt;to/&gt; -&lt;exclude/&gt;
build_flags =
  -lgcov
  --coverage
extra_scripts = ci/test_coverage.py
</code></pre>
<p>My <strong>test</strong> would be something like this:</p>
<pre><code>#include &lt;unity.h&gt;
#include &quot;data.h&quot;

void test_1(void) {
  uint8_t mode = get_value();
  TEST_ASSERT_EQUAL(mode, 0);
}

int main(int argc, char **argv) {
    UNITY_BEGIN();

    RUN_TEST(test_1);

    return UNITY_END();
}
</code></pre>
<p>My simplified <strong>code</strong> would be (data.cpp file):</p>
<pre><code>#include &lt;ESP8266WiFi.h&gt;

uint8_t mode = 0;
uint8_t get_value(){
  return mode;
}
</code></pre>
<p>The compilation is working fine with <code>pio run</code>.
I am running this command to run the tests:</p>
<pre><code>pio test -e native -vvv
</code></pre>
<p>The error is:</p>
<pre><code>test\test_main.cpp:2:25: fatal error: ESP8266WiFi.h: No such file or directory
</code></pre>
<p>Maybe <code>ArduinoFake</code> can't emulate this library? Or should I include the library somehow? Or can't I Unit Test the way I am trying to do it?</p>
<p>If I have this test without importing my code, the test passes:</p>
<pre><code>#include &lt;unity.h&gt;
// #include &quot;data.h&quot;

void test_1(void) {
  //uint8_t mode = get_value();
  TEST_ASSERT_EQUAL(0, 0);
}

int main(int argc, char **argv) {
    UNITY_BEGIN();

    RUN_TEST(test_1);

    return UNITY_END();
}
</code></pre>
",https://stackoverflow.com/questions/75790142/unit-testing-arduino-esp8266-in-ci-native-with-libraries,"['c++', 'continuous-integration', 'platformio', 'unity-test-framework']",87,True,0,1
How to fix unsaved transient instance during unit testing,"<p>I want to write some tests to find an object by some given attibute; but before that i want to make use of the setUp method to initialize the object i want to test for. but this object is also dependent on another object which i want to create as a mock, but i cant call the method the test methid as it throws this exception: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing.
This is the sample code below, please tell me what am missing and how to make it better, thanks.</p>
<pre><code>@DataJpaTest(properties = {
                &quot;spring.jpa.properties.javax.persistence.validation.mode=none&quot;
        })
@ExtendWith(MockitoExtension.class)
public class EmailVerificationTokenRepositoryTest {

    @Autowired
    private EmailVerificationTokenRepository repository;

    @Mock
    private UserRepository userRepository;

    /**
     * Test of findByToken method, of class EmailVerificationTokenRepository.
     */
    @BeforeEach
    public void setUp() {
        Set role = new HashSet&lt;&gt;();
        role.add(&quot;ROLE_USER&quot;);
        Users expected = Users.builder()
                .id(null)
                .email(&quot;david@gmail.com&quot;)
                .password(&quot;1234&quot;)
                .isEnabled(true)
                .isNonLocked(true)
                .roles(role)
                .createdAt(LocalDateTime.now())
                .build();               
        Mockito.when(userRepository.save(expected)).thenReturn(expected);
        Users actual = userRepository.save(expected);
        System.out.println(actual);
        EmailVerificationToken evt = EmailVerificationToken.builder()
                .createdAt(LocalDateTime.now())
                .expiresAt(LocalDateTime.now().plusHours(4))
                .token(&quot;token&quot;)
                .user(actual)
                .build();
        repository.save(evt);
    }

    @AfterEach
    public void tearDown() {
        repository.deleteAll();
    }

    @Test
    @DisplayName(&quot;Test to find Email Verification Object By Token&quot;)
    public void testFindByToken() {
        String token = &quot;token&quot;;
        Optional&lt;EmailVerificationToken&gt; result = repository.findByToken(token);
        assertTrue(result.isPresent());
    }

    /**
     * Test of findByUser method, of class EmailVerificationTokenRepository.
     */
    @Test
    @Disabled
    @DisplayName(&quot;Test to find Email Verification Object By User&quot;)
    public void testFindByUser() {
        //Given
        Set role = new HashSet&lt;&gt;();
        role.add(&quot;ROLE_USER&quot;);
        Users user = Users.builder()
                .id(null)
                .email(&quot;david@gmail.com&quot;)
                .password(&quot;1234&quot;)
                .isEnabled(true)
                .isNonLocked(true)
                .roles(role)
                .createdAt(LocalDateTime.now())
                .build();
        Optional&lt;EmailVerificationToken&gt; result = repository.findByUser(user);
        assertTrue(result.isPresent());
    }

}
</code></pre>
<p>And these are my logs:</p>
<pre><code>2023-02-26 18:57:11.507  INFO [,,] 12780 --- [           main] u.r.EmailVerificationTokenRepositoryTest : Started EmailVerificationTokenRepositoryTest in 7.485 seconds (JVM running for 11.929)
2023-02-26 18:57:11.588  INFO [,,] 12780 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@2b76ff4e testClass = EmailVerificationTokenRepositoryTest, testInstance = com.slinkdigital.user.repository.EmailVerificationTokenRepositoryTest@73eae5f, testMethod = testFindByToken@EmailVerificationTokenRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@7a1234bf testClass = EmailVerificationTokenRepositoryTest, locations = '{}', classes = '{class com.slinkdigital.user.UserApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{spring.jpa.properties.javax.persistence.validation.mode=none, org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@2f62ea70 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6f3187b0, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@189cbd7c, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@723e88f9, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@6ea2bc93, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@474abc3a, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@48c76607, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -&gt; false, 'org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.mocks' -&gt; org.mockito.internal.configuration.InjectingAnnotationEngine$$Lambda$406/0x0000000800e49720@4902c584]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@42ef5216]; rollback [true]
Users(id=null, email=david@gmail.com, password=1234, createdAt=2023-02-26T18:57:11.641991300, isNonLocked=false, isEnabled=false, roles=[ROLE_USER])
2023-02-26 18:57:11.774 DEBUG [,,] 12780 --- [           main] org.hibernate.SQL                        : 
    insert 
    into
        email_verification_token
        (id, created_at, expires_at, token, user_id) 
    values
        (default, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        email_verification_token
        (id, created_at, expires_at, token, user_id) 
    values
        (default, ?, ?, ?, ?)
2023-02-26 18:57:12.033  INFO [,,] 12780 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@2b76ff4e testClass = EmailVerificationTokenRepositoryTest, testInstance = com.slinkdigital.user.repository.EmailVerificationTokenRepositoryTest@73eae5f, testMethod = testFindByToken@EmailVerificationTokenRepositoryTest, testException = org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.slinkdigital.user.domain.EmailVerificationToken.user -&gt; com.slinkdigital.user.domain.Users; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.slinkdigital.user.domain.EmailVerificationToken.user -&gt; com.slinkdigital.user.domain.Users, mergedContextConfiguration = [MergedContextConfiguration@7a1234bf testClass = EmailVerificationTokenRepositoryTest, locations = '{}', classes = '{class com.slinkdigital.user.UserApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{spring.jpa.properties.javax.persistence.validation.mode=none, org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@2f62ea70 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6f3187b0, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@189cbd7c, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@723e88f9, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@6ea2bc93, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@474abc3a, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@48c76607, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -&gt; false, 'org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.mocks' -&gt; org.mockito.internal.configuration.InjectingAnnotationEngine$$Lambda$406/0x0000000800e49720@4902c584]]
Tests run: 2, Failures: 0, Errors: 1, Skipped: 1, Time elapsed: 10.605 s &lt;&lt;&lt; FAILURE! - in com.slinkdigital.user.repository.EmailVerificationTokenRepositoryTest
testFindByToken  Time elapsed: 0.024 s  &lt;&lt;&lt; ERROR!
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.slinkdigital.user.domain.EmailVerificationToken.user -&gt; com.slinkdigital.user.domain.Users; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.slinkdigital.user.domain.EmailVerificationToken.user -&gt; com.slinkdigital.user.domain.Users
    at com.slinkdigital.user.repository.EmailVerificationTokenRepositoryTest.testFindByToken(EmailVerificationTokenRepositoryTest.java:76)
Caused by: java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.slinkdigital.user.domain.EmailVerificationToken.user -&gt; com.slinkdigital.user.domain.Users
    at com.slinkdigital.user.repository.EmailVerificationTokenRepositoryTest.testFindByToken(EmailVerificationTokenRepositoryTest.java:76)
Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.slinkdigital.user.domain.EmailVerificationToken.user -&gt; com.slinkdigital.user.domain.Users
    at com.slinkdigital.user.repository.EmailVerificationTokenRepositoryTest.testFindByToken(EmailVerificationTokenRepositoryTest.java:76)

</code></pre>
<p>I will appreciate every assistance i can get, thanks.</p>
",https://stackoverflow.com/questions/75573999/how-to-fix-unsaved-transient-instance-during-unit-testing,"['spring-boot', 'unit-testing', 'spring-data-jpa', 'mockito', 'h2']",132,False,0,1
unit testing pipeline fail because of an old commit,"<p>hey guys so my problem is a little bit weird and i'm not a professional with all this kind of stuf so it's complicated haha...</p>
<p>My unit test pipeline on gitlab fail, when i check where the pipeline have failed i notice it's coming from an old error from a test i already fixed. So it's seems that the unit test pipeline is using old commit to do the job...</p>
<p>When i look into my recents commits, the modification concerning the failed test are present so the error should not be occur anymore but she does.</p>
<p>I try to change the image but i think mine is good (alpine3.17). That pipeline was working last week and i didn't change anything in his configuration.
i try to comment the test where the error still occurs (we can see the comments in the last commit but the pipeline still fail using old commit i guess because i see the old error)</p>
<p>Thanks for reading</p>
",https://stackoverflow.com/questions/75789169/unit-testing-pipeline-fail-because-of-an-old-commit,"['unit-testing', 'gitlab', 'pipeline']",8,False,0,0
Require assistance in unit testing zoom integration in flutter,"<p>Using <a href=""https://github.com/craigspicer/flutter_zoom_sdk"" rel=""nofollow noreferrer"">flutter_zoom_sdk</a> , the <a href=""https://github.com/craigspicer/flutter_zoom_sdk#join-meeting"" rel=""nofollow noreferrer"">joinMeeting()</a> method is used in the flutter application to join a zoom meeting upon clicking a meeting card.</p>
<p>Unit tests need to be written on the same. How to go about writing unit tests for the following:</p>
<ol>
<li>User successfully joined meeting.</li>
<li>User exited from meeting.</li>
</ol>
<p>This is what we wrote as of now :</p>
<pre><code>class zoomMeeting {
  bool hasMeetingStarted = false;
  bool hasMeetingEnded = false;
  bool hasMeetingServerConnected = false;
  String currentStatus = &quot;&quot;;

  zoomMeeting(hasMeetingStarted, hasMeetingEnded);
  void checkMeetingStarted() {}

  void joinMeeting(String meetingID, String meetingPassword) {
    // print(&quot;ssd&quot;);
    ZoomOptions zoomOptions = ZoomOptions(
      domain: &quot;zoom.us&quot;,
      appKey: API_KEY, //API KEY FROM ZOOM - Sdk API Key
      appSecret: API_SECRET, //API SECRET FROM ZOOM - Sdk API Secret
    );
    ZoomMeetingOptions meetingOptions = ZoomMeetingOptions(
        userEmail: &quot;&quot;,
        userId: &quot;Guest&quot;,
        meetingId: meetingID,
        meetingPassword: meetingPassword,
        disableMinimizeMeeting: &quot;true&quot;,
        disableDialIn: &quot;true&quot;,
        disableDrive: &quot;true&quot;,
        disableInvite: &quot;true&quot;,
        disableShare: &quot;false&quot;,
        disableTitlebar: &quot;false&quot;,
        viewOptions: &quot;false&quot;,
        noAudio: &quot;false&quot;,
        noDisconnectAudio: &quot;true&quot;);

    ZoomView zoom = ZoomView();
    zoom.initZoom(zoomOptions).then((results) {
      if (results[0] == 0) {
        zoom.onMeetingStatus().listen((status) {
          // String currentStatus = status[0];
          // print(&quot;Status: &quot; + currentStatus, name: 'Meeting.dart');
          switch (currentStatus) {
            case MEETING_STATUS_CONNECTING:
              // print(&quot;Its connecting&quot;);

              currentStatus = &quot;MEETING STATUS CONNECTING&quot;;
              break;
            case MEETING_STATUS_DISCONNECTING:

              // print(&quot;Its disconnecting&quot;);
              currentStatus = &quot;MEETING IS DISCONNECTING&quot;;
              print(currentStatus);
              break;
            case MEETING_STATUS_IN_MEETING:
              currentStatus = &quot;USER IS IN MEETING&quot;;
              break;
            case MEETING_STATUS_FAILED:
              currentStatus = &quot;MEETING HAS FAILED&quot;;
              break;
          }
        });
        zoom.joinMeeting(meetingOptions);
      }
    }).catchError((error) {
      // print(&quot;Error: &quot; + error, name: 'Meeting.dart');
      print(error);
    });
  }
}

</code></pre>
<p>The idea is to get the value of current status to match with the meeting status messages provided in github. However the expected value never matches actual value (currentStatus is always a empty string).</p>
",https://stackoverflow.com/questions/75992922/require-assistance-in-unit-testing-zoom-integration-in-flutter,"['flutter', 'dart']",13,False,0,0
Unit testing in NodeJS with different dependencies per test,"<p>(disclaimer: I am new to NodeJS, so maybe I am missing some basic concepts)</p>
<p>I want to write a test for my NodeJS code. I have multiple tests, while every test uses a different public nodejs dependency, for example - test1 uses dependency named X and test2 uses dependency name Y.</p>
<p>To make my tests as accurate as possible I want that while I am testing the first test, only dependency X will be installed, and when I am testing the test2 - only dependency Y.</p>
<p>Of course I can use some script delete <code>node_modules</code> after every test, copy a new <code>packages.json</code> file and installs only the dependencies required for the next test, but I am looking for something that will do that automatically.</p>
<p>(for example, if it was a python, I would be creating a venv for every test and run in inside it)</p>
<p>I tried to find any automatic testing platform which will give me that option, but didn't find anything like that, the most helpful project that I found is - <a href=""https://github.com/watson/test-all-versions"" rel=""nofollow noreferrer"">Test all versions</a>, but I am looking for something more automatic and &quot;smart&quot;.</p>
<p>is there any platform that I can use to automate it as I want ?</p>
",https://stackoverflow.com/questions/75683497/unit-testing-in-nodejs-with-different-dependencies-per-test,"['node.js', 'testing', 'npm']",78,False,0,1
Unit testing server component that uses next-intl Link,"<p>I'm trying to create a Jest unit test for a simple server component on Next.js (<a href=""https://next-intl-docs.vercel.app/docs/next-13/server-components"" rel=""nofollow noreferrer"">See here</a>). It Uses the next-intl Link replacement for the usual next/link (Link), but I'm getting this error: <code>Unable to find next-intl cookie, have you configured the middleware?</code>.</p>
<p>Component</p>
<pre><code>import { Link } from 'next-intl';

const Navigation = () =&gt; (
    &lt;div&gt;
        &lt;Link href=&quot;/&quot;&gt;
            Home Page
        &lt;/Link&gt;
                &lt;Link href=&quot;/about&quot;&gt;
            About
        &lt;/Link&gt;
    &lt;/div&gt;
);

export default Navigation;

</code></pre>
<p>Test</p>
<pre><code>import NavBar from './Navigation';
import { render,} from '@testing-library/react';

it('Should', () =&gt; {
    render(&lt;Navigation /&gt;);
});

</code></pre>
<p>The problem I'm facing is that I'm getting this error: <code>Unable to find next-intl cookie, have you configured the middleware?</code></p>
<p>I have the middleware configured as per: <a href=""https://next-intl-docs.vercel.app/docs/next-13/server-components"" rel=""nofollow noreferrer"">https://next-intl-docs.vercel.app/docs/next-13/server-components</a></p>
<p>Any ideas what am I missing?</p>
",https://stackoverflow.com/questions/75568504/unit-testing-server-component-that-uses-next-intl-link,"['unit-testing', 'next.js', 'jestjs']",80,False,0,0
Unit testing a unittest custom test runner in Django,"<p>I am trying to unit test a custom test runner using unittest framework but I get this error.</p>
<pre><code>  File &quot;/usr/local/lib/python3.7/dist-packages/django/test/runner.py&quot;, line 466, in setup_test_environment
    setup_test_environment(debug=self.debug_mode)
  File &quot;/usr/local/lib/python3.7/dist-packages/django/test/utils.py&quot;, line 111, in setup_test_environment
    &quot;setup_test_environment() was already called and can't be called &quot;
RuntimeError: setup_test_environment() was already called and can't be called again without first calling teardown_test_environment().
</code></pre>
<p>I understand that this error message is pretty self explanatory but the problem with running <code>teardown_test_environment</code> within the unit test ends up in this error message</p>
<pre><code>  File &quot;/usr/local/lib/python3.7/dist-packages/django/test/runner.py&quot;, line 588, in teardown_test_environment
    teardown_test_environment()
  File &quot;/usr/local/lib/python3.7/dist-packages/django/test/utils.py&quot;, line 144, in teardown_test_environment
    saved_data = _TestState.saved_data
AttributeError: type object '_TestState' has no attribute 'saved_data'
</code></pre>
<p>Has anyone encountered something like this before?</p>
",https://stackoverflow.com/questions/75381857/unit-testing-a-unittest-custom-test-runner-in-django,"['python', 'django', 'unit-testing', 'django-unittest']",28,False,0,0
Unit Testing in Commerce tools in .net/C# API,"<p>What unit testing framework/library is recommended for Commerce tools in.net/C# API especially for mocking the commerce tool .net API .</p>
<p>I tried mocking the .net API of commerce tools with moq framework but faced issues in that . It does not let mock the objects saying overriding is not allowed .</p>
",https://stackoverflow.com/questions/76351103/unit-testing-in-commerce-tools-in-net-c-api,['commercetools'],19,False,0,0
Java Unit Testing Http Get test user auto generate,"<p>I write function in rest to automatically generate user with admin role. Here's the function:</p>
<p>UserController.java</p>
<pre class=""lang-java prettyprint-override""><code>@RestController
@RequestMapping(&quot;users&quot;)
public class UserController {

    @Autowired
    private UserRepository userRepo;
    @Autowired
    private TokenRepository tokenRepo;
    
    @GetMapping(&quot;admin&quot;)
    public String getAdmin () {
        JSONObject report = new JSONObject();
        String dataAdmin = userRepo.findByUsername(&quot;admin&quot;);
        if(dataAdmin == null) {
            User myadmin = new User();
            myadmin.setUsername(&quot;admin&quot;);
            myadmin.setFirstname(&quot;admin&quot;);
            myadmin.setLastname(&quot;admin&quot;);
            myadmin.setEmail(&quot;admin@admin&quot;);
            myadmin.setRole(&quot;admin&quot;);
            userRepo.save(myadmin);
            report.put(&quot;message&quot;, &quot;admin generated&quot;);
        } else {
            report.put(&quot;message&quot;, &quot;admin only generated once&quot;);
        }
        return report.toString();
    }
</code></pre>
<p>I am trying to follow the instruction from here <a href=""https://www.springboottutorial.com/unit-testing-for-spring-boot-rest-services"" rel=""nofollow noreferrer"">https://www.springboottutorial.com/unit-testing-for-spring-boot-rest-services</a>.
In <em>Unit Testing Http Get Operation</em> section. I am getting several problem and also trying the different solution until I meet this <a href=""https://stackoverflow.com/questions/63008254/unit-testing-a-get-request-in-a-spring-project"">Unit testing a Get request in a spring project</a> from stackoverflow.
below is the testing script I've make so far.</p>
<pre class=""lang-java prettyprint-override""><code>package blablaaa.order;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import blablaaa.order.controller.UserController;
import blablaaa.order.dao.UserRepository;
import blablaaa.order.model.User;

//@ExtendWith(SpringExtension.class)
//@SpringBootTest
@WebMvcTest(value = UserController.class)
class OrderApplicationTests {
//  
    @Autowired
    private MockMvc mockMvc;
    
    @MockBean
    private UserRepository userRepo;

    @Test
    void contextLoads() throws Exception{

        User myadmin = new User();
        myadmin.setUsername(&quot;admin&quot;);
        myadmin.setFirstname(&quot;admin&quot;);
        myadmin.setLastname(&quot;admin&quot;);
        myadmin.setEmail(&quot;admin@admin&quot;);
        myadmin.setRole(&quot;admin&quot;);
        
        List&lt;User&gt; myUser = new ArrayList&lt;&gt;();
        myUser.add(myadmin);
        RequestBuilder rb = MockMvcRequestBuilders.get(&quot;/users/admin&quot;).accept(MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc.perform(rb).andReturn();
        JSONObject expect = new JSONObject();
        expect.put(&quot;message&quot;, &quot;admin generated&quot;);
//      System.out.println(result.toString());
        System.out.println(expect.toString());
//      Assertions.assertTrue(result.toString().contains(expect.toString()));
    }

}
</code></pre>
<p>I dont know, how the testing should be written. any keyword related to this?</p>
<p>[update]<br />
Here's my main:</p>
<pre class=""lang-java prettyprint-override""><code>// OrderApplication.java
@SpringBootApplication
@EnableMongoRepositories(&quot;blablaaa.order.dao&quot;)
public class OrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }

}
</code></pre>
<p>Here's my program error log</p>
<pre><code>Description:

Field tokenRepo in blablaaa.order.controller.UserController required a bean named 'mongoTemplate' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean named 'mongoTemplate' in your configuration.
</code></pre>
",https://stackoverflow.com/questions/75173863/java-unit-testing-http-get-test-user-auto-generate,"['java', 'spring', 'unit-testing']",58,True,0,2
Issue with creating new project for unit testing with NUnit,"<p>Im created on Mac new project to test my web rest api, but I can't make to work initial version of project. Every time I stuck on error:</p>
<pre><code>/Applications/Visual Studio.app/Contents/MonoBundle/MSBuild/Current/bin/Microsoft.Common.CurrentVersion.targets(5,5): Error MSB3971: The reference assemblies for &quot;.NETFramework,Version=v7.0&quot; were not found. You might be using an older .NET SDK to target .NET 5.0 or higher. Update Visual Studio and/or your .NET SDK. (MSB3971) (Core)
</code></pre>
<p>The whole project are written in .Net Core 7.0.</p>
<p>I checked  in both projects, and they are the same.
Project reference is also set.
Somebody can help me how to make it work on macOs?
Thanks.</p>
<p>After few changes and reverting - both project currently not starting because of the same error.</p>
",https://stackoverflow.com/questions/75925951/issue-with-creating-new-project-for-unit-testing-with-nunit,"['.net-core', 'nunit']",52,False,2,0
How to create a mock mongo client for unit testing?,"<p>I am new to Golang, trying to figure out how to create a mock mongo client for unit testing. I am able to create a mock mongo collection using go.mongodb.org/mongo-driver/mongo/integration/mtest,</p>
<pre><code>mt := mtest.New(t, mtest.NewOptions().ClientType(mtest.Mock))
    defer mt.Close()

collection := mt.Coll
</code></pre>
<p>However, for creating a client, using <code>mt.Client</code> or <code>mt.Coll.Database().Client()</code> don't work - getting nil client in result.</p>
<p>Is there anything that I am missing here possibly - kindly guide, thank you!</p>
",https://stackoverflow.com/questions/75692284/how-to-create-a-mock-mongo-client-for-unit-testing,"['mongodb', 'unit-testing', 'go']",148,False,2,1
Exporting arrow function in react for unit testing in Jest,"<p>The error I keep getting is that checkIfBlank is undefined I understand that I have to export the function however I don't know how to for an Arrow Function</p>
<p>Here is my function in register.js</p>
<pre><code>import React from &quot;react&quot;;
import axios from 'axios';
import bycrypt from 'bcryptjs';

import { Link } from &quot;react-router-dom&quot;;

import { Helmet } from &quot;react-helmet&quot;;

import { useState } from &quot;react&quot;;
// const bcrypt = require('bcryptjs');

import InputBoxForInfo from &quot;../components/input-box-for-info&quot;;
import Button from &quot;../components/button&quot;;
import &quot;./register.css&quot;;


const Register = (props) =&gt; {
  const [name, setName] = useState(&quot;&quot;);
  const [surname, setSurname] = useState(&quot;&quot;);
  const [email, setEmail] = useState(&quot;&quot;);
  const [username, setUsername] = useState(&quot;&quot;);
  const [password, setPassword] = useState(&quot;&quot;);
  const salt = bycrypt.genSaltSync(10);
  const hashedPassword = bycrypt.hashSync(password,salt);
  const[exist, setExistence] = useState(&quot;&quot;);
  const [errorMessage, setErrorMessage] = useState('');
  const postDetails = () =&gt;{
    axios.post(&quot;http://localhost:3002/api/post/register&quot;,{name:name, surname:surname, email: email, username: username, password: hashedPassword});
    setTimeout(function(){
    window.location.href = 'http://localhost:3000/login';
    }, 1000);
    
  }

  const checkIfUserExists = () =&gt;{
    axios
    .get(&quot;http://localhost:3002/api/get/doesExist/&quot; + username)
    .then(function(response){
      const userExists = response.data;
      console.log(response.data);
      if (JSON.stringify(userExists) == &quot;[]&quot;){
        setErrorMessage('Account created successfully');
        postDetails();
      }
      else{
        setErrorMessage('Username already exists');
      }
    });
  }

  
   const checkIfBlank=()=&gt;{
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const passwordPattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/;

    //If fields empty, warn
    if(name == &quot;&quot; || surname ==&quot;&quot; || email == &quot;&quot; || username == &quot;&quot; || password==&quot;&quot;){
      alert(&quot;Please enter all details&quot;);
    }

    //not empty
    else{
      //check if email correct and password is strong
      if(emailPattern.test(email) &amp;&amp; passwordPattern.test(password)){
        checkIfUserExists();
      }
      //otherwise warn
      else{
        //email not corect format
        if(!emailPattern.test(email)){
          setErrorMessage('Please enter a valid email');
        }
        if(!passwordPattern.test(password)){
          setErrorMessage(&quot;Please enter a stronger password&quot;);
        }
      }
    }
  }

  const handleRegister = () =&gt; {
    // Do something with the input values
    console.log(
      `Name: ${name}, Surname: ${surname} Email: ${email}, Username: ${username}, Password: ${hashedPassword}`
    );
    checkIfBlank();
  };
  

  return (
    &lt;div className=&quot;register-container&quot;&gt;
      &lt;Helmet&gt;
        &lt;title&gt;register - Project ARENA&lt;/title&gt;
        &lt;meta property=&quot;og:title&quot; content=&quot;register - Project ARENA&quot; /&gt;
      &lt;/Helmet&gt;
      &lt;div className=&quot;register-container1&quot;&gt;
        &lt;Link to=&quot;/&quot; className=&quot;register-navlink&quot;&gt;
          &lt;svg
            viewBox=&quot;0 0 877.7142857142857 1024&quot;
            className=&quot;register-backbtn&quot;
          &gt;
            &lt;path d=&quot;M519.429 797.143l58.286-58.286c14.286-14.286 14.286-37.143 0-51.429l-175.429-175.429 175.429-175.429c14.286-14.286 14.286-37.143 0-51.429l-58.286-58.286c-14.286-14.286-37.143-14.286-51.429 0l-259.429 259.429c-14.286 14.286-14.286 37.143 0 51.429l259.429 259.429c14.286 14.286 37.143 14.286 51.429 0zM877.714 512c0 242.286-196.571 438.857-438.857 438.857s-438.857-196.571-438.857-438.857 196.571-438.857 438.857-438.857 438.857 196.571 438.857 438.857z&quot;&gt;&lt;/path&gt;
          &lt;/svg&gt;
        &lt;/Link&gt;
      &lt;/div&gt;
      &lt;div className=&quot;register-container5&quot;&gt;
        &lt;span className=&quot;register-text&quot;&gt;
          &lt;span&gt;Register&lt;/span&gt;
          &lt;br&gt;&lt;/br&gt;
        &lt;/span&gt;

        &lt;InputBoxForInfo
          buttonText=&quot;NAME&quot;
          onChange={(e) =&gt; setName(e.target.value)}
          rootClassName=&quot;input-box-for-info-root-class-name&quot;
        &gt;&lt;/InputBoxForInfo&gt;

        &lt;InputBoxForInfo
          buttonText=&quot;SURNAME&quot;
          onChange={(e) =&gt; setSurname(e.target.value)}
          rootClassName=&quot;input-box-for-info-root-class-name2&quot;
        &gt;&lt;/InputBoxForInfo&gt;
    
        &lt;InputBoxForInfo
          buttonText=&quot;EMAIL&quot;
          onChange={(e) =&gt; setEmail(e.target.value)}
          rootClassName=&quot;input-box-for-info-root-class-name3&quot;
        &gt;&lt;/InputBoxForInfo&gt;
    
        &lt;InputBoxForInfo
          buttonText=&quot;USERNAME&quot;
          onChange={(e) =&gt; setUsername(e.target.value)}
          rootClassName=&quot;input-box-for-info-root-class-name4&quot;
        &gt;&lt;/InputBoxForInfo&gt;
    
        &lt;InputBoxForInfo
          buttonText=&quot;PASSWORD&quot;
          onChange={(e) =&gt; setPassword(e.target.value)}
          isPassword
          rootClassName=&quot;input-box-for-info-root-class-name5&quot;
        &gt;&lt;/InputBoxForInfo&gt;
    
        &lt;br&gt;&lt;/br&gt;
        &lt;Button 
          name=&quot;Register&quot;
          onClick={() =&gt; {
            console.log(&quot;Register button clicked&quot;);
            handleRegister();
          }}
          rootClassName=&quot;button-root-class-name&quot;
        &gt;&lt;/Button&gt;
        
        &lt;br&gt;&lt;/br&gt;
        {errorMessage &amp;&amp; &lt;div className=&quot;error&quot;&gt;{errorMessage}&lt;/div&gt;}
        &lt;span className=&quot;register-text3&quot;&gt;Already have an account?&lt;/span&gt;
        &lt;Link to=&quot;/login&quot; className=&quot;register-navlink1 button&quot;&gt;
          Login here
        &lt;/Link&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
};

export default Register;

</code></pre>
<p>Here is my unit test for the above code</p>
<pre><code>import React  from 'react';
import Register from './register';

// Import the necessary modules
const axios = require('axios');

// Import the function to be tested
import { checkIfBlank } from './register.js';
//const { checkIfBlank } = require('./register');

// Test suite for checkIfBlank function
describe('checkIfBlank', () =&gt; {

  // Mock the setErrorMessage and postDetails functions
  let setErrorMessage = jest.fn();
  let postDetails = jest.fn();

  // Test case when all fields are filled in and valid
  test('valid input', () =&gt; {
    // Set up the input data
    const name = 'John';
    const surname = 'Doe';
    const email = 'john.doe@example.com';
    const username = 'johndoe';
    const password = 'Passw0rd';

    // Call the function
    checkIfBlank(name, surname, email, username, password, setErrorMessage, postDetails);

    // Check that setErrorMessage and postDetails were not called
    expect(setErrorMessage).not.toHaveBeenCalled();
    expect(postDetails).not.toHaveBeenCalled();
  });

  // Test case when one or more fields are empty
  test('missing field', () =&gt; {
    // Set up the input data
    const name = '';
    const surname = 'Doe';
    const email = 'john.doe@example.com';
    const username = 'johndoe';
    const password = 'Passw0rd';

    // Call the function
    checkIfBlank(name, surname, email, username, password, setErrorMessage, postDetails);

    // Check that setErrorMessage was called with the correct message
    expect(setErrorMessage).toHaveBeenCalledWith('Please enter all details');

    // Check that postDetails was not called
    expect(postDetails).not.toHaveBeenCalled();
  });

  // Test case when the email is invalid
  test('invalid email', () =&gt; {
    // Set up the input data
    const name = 'John';
    const surname = 'Doe';
    const email = 'johndoe@examplecom';
    const username = 'johndoe';
    const password = 'Passw0rd';

    // Call the function
    checkIfBlank(name, surname, email, username, password, setErrorMessage, postDetails);

    // Check that setErrorMessage was called with the correct message
    expect(setErrorMessage).toHaveBeenCalledWith('Please enter a valid email');

    // Check that postDetails was not called
    expect(postDetails).not.toHaveBeenCalled();
  });

  // Test case when the password is weak
  test('weak password', () =&gt; {
    // Set up the input data
    const name = 'John';
    const surname = 'Doe';
    const email = 'john.doe@example.com';
    const username = 'johndoe';
    const password = 'password';

    // Call the function
    checkIfBlank(name, surname, email, username, password, setErrorMessage, postDetails);

    // Check that setErrorMessage was called with the correct message
    expect(setErrorMessage).toHaveBeenCalledWith('Please enter a stronger password');

    // Check that postDetails was not called
    expect(postDetails).not.toHaveBeenCalled();
  });
});


</code></pre>
<p>I have tried the following:</p>
<p>This in the resgiter.js in the fucntion
<code>export const checkIfBlank=()=&gt;{</code></p>
<p>At the end of register.js and add the beginning of regsiter.js
<code>export {checkIfBlank};</code></p>
<p>At the end of register.js and add the beginning of regsiter.js
<code>module.exports = { checkIfBlank };</code></p>
<p>This in the resgiter.js in the fucntion
<code>module.exports = checkIfBlank=()=&gt;{</code></p>
",https://stackoverflow.com/questions/75908803/exporting-arrow-function-in-react-for-unit-testing-in-jest,"['javascript', 'node.js', 'reactjs', 'unit-testing', 'jestjs']",88,True,-1,1
Unhandled promise rejection: NotAllowedError: Write permission denied Angular unit testing,"<p>I have a function that includes a timeout function + copies a text from the clipboard:</p>
<pre><code>  copyLink(linkAddress: string, index: number) {
    this.showTickForCopiedLink[index] = true;
    setTimeout(() =&gt; {
      this.showTickForCopiedLink[index] = false;
    }, 800); 
    return navigator.clipboard.writeText(linkAddress);
  }
</code></pre>
<p>I am trying to write a test for this function:</p>
<pre><code>beforeEach(waitForAsync(() =&gt; {
  TestBed.configureTestingModule({
  declarations: [SideBarNoteComponent],
  providers: [Clipboard],
  }).compileComponents();
}));
    
beforeEach(waitForAsync(() =&gt; {
 fixture = TestBed.createComponent(SideBarNoteComponent);
 component = fixture.componentInstance;
 fixture.detectChanges();
}));   
it('show tick icon for copied link for 800ms and then hide it', 
 fakeAsync(() =&gt; {
  component.showTickForCopiedLink = [
  false,
  false,
  false,
 ];
 component.copyLink('link1', 1);
 expect(component.showTickForCopiedLink[1]).toBeTrue();
 tick(799);
 expect(component.showTickForCopiedLink[1]).toBeTrue();
 tick(2);
 expect(component.showTickForCopiedLink[1]).toBeFalse();
}));
</code></pre>
<p>The test passes when running on its own, but when I run all the tests for the project, I get the error:</p>
<pre><code>An error was thrown in afterAll

Unhandled promise rejection: NotAllowedError: Write permission denied.
</code></pre>
<p>How can I write the right tests for this function?</p>
",https://stackoverflow.com/questions/75957467/unhandled-promise-rejection-notallowederror-write-permission-denied-angular-un,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",175,False,0,1
Unit testing can&#39;t find button and it equal to null,"<p>I am trying to do an unit testing for a reuseable component, the reuseable componet have an input and output. But It seem to can't find the button class. and also if there is a way, is thhere a way to not use fixture.</p>
<p>the error =TypeError: Cannot read properties of null</p>
<pre><code>describe('SelectorComponent', () =&gt; {
  let component: SelectorComponent;
  let fixture: ComponentFixture&lt;SelectorComponent&gt;;

  beforeEach(async () =&gt; {
    component = new SelectorComponent();
  });

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(SelectorComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });


  it('should select a dimension when clicked', () =&gt; {
    let selectors: Selector[] = [{
      id: '1', 
      name: 'Child ',
      parent: 'Parent ',
      sortOrder: 1,
      icon: 'brain',
      selected: true, 
      children: []
    }];
    spyOn(component, 'selectSelector');
    component.selectors = selectors;
    let btn = fixture.debugElement.query(By.css('.selectors'));
    btn.triggerEventHandler('click', null); 
    fixture.detectChanges();

    fixture.whenStable().then(() =&gt; {
      expect(component.selectorSelected.emit).toHaveBeenCalled();
    });
  });
});

</code></pre>
<pre><code>@Input() public selectors!: Selector[];
  @Output() public selectoSelected = new EventEmitter&lt;Dimension&gt;();

  constructor() { }

  selectselectors(selector: Selector) {
    this.selectoSelected.emit(selector);
  }
</code></pre>
<pre><code>&lt;button
    class=&quot;selector&quot;
    (click)=&quot;selectselectors(selectors)&quot;
    *ngFor=&quot;let selector of selectors&quot;
&gt;
    &lt;div class=&quot;name&quot;&gt;{{ selector.name }}&lt;/div&gt;
&lt;/button&gt;
</code></pre>
<p>Thank you in advance, I am new with Unit testing</p>
<p>I have try without fixture alsso, but it didnt seem to work, it keep sayying button is null</p>
",https://stackoverflow.com/questions/75001059/unit-testing-cant-find-button-and-it-equal-to-null,"['angular', 'karma-jasmine']",110,False,0,1
Problem with unit testing of Billing Library 5 in Android,"<p>I'm using wrapper for BillingClient and after migration from Billing Library 4.0 to 5.0 there is an issue with unit testing of specific builder - <code>BillingFlowParams.SubscriptionUpdateParams</code> builder.</p>
<p>Specific wrapper's method that is having issue looks like this:</p>
<pre><code>fun upgradeSubscription(sub: Purchase, product: Product, activity: Activity) {
    val newOfferToken = product.productDetails.getOffer()?.offerToken ?: return
    val updateParams = BillingFlowParams.SubscriptionUpdateParams.newBuilder()
        .setOldPurchaseToken(sub.purchaseToken)
        .setReplaceProrationMode(MODE)
        .build()
    val productDetailsParamsList = listOf(
        ProductDetailsParams.newBuilder()
            .setProductDetails(product.productDetails)
            .setOfferToken(newOfferToken)
            .build()
    )
    val billingFlowParams = BillingFlowParams.newBuilder()
        .setProductDetailsParamsList(productDetailsParamsList)
        .setSubscriptionUpdateParams(updateParams)
        .build()
    client.launchBillingFlow(activity, billingFlowParams)
}
</code></pre>
<p>and my test method looks like this:</p>
<pre><code>@Test
fun `should test upgradeSubscription`() { 
    mockkStatic(BillingFlowParams::class)
    val params = slot&lt;BillingFlowParams&gt;()
    val activity = mockkClass(Activity::class)
    val sub = getMockedPurchase()

    billingWrapper.upgradeSubscription(sub, product, activity)

    verify { client.launchBillingFlow(storeActivity, capture(params)) }
}
</code></pre>
<p>Test fails at <code>.build()</code> line of <code>BillingFlowParams.SubscriptionUpdateParams</code>'s builder with such exception:</p>
<blockquote>
<p>java.lang.IllegalArgumentException: Please provide Old SKU purchase
information(token/id) or original external transaction id, not both.</p>
</blockquote>
<p>Meanwhile in real-life usage it works fine. So I'm wondering how to fix this problem with the unit test.</p>
<p>I've found <a href=""https://github.com/android/play-billing-samples/issues/546"" rel=""nofollow noreferrer"">the same question</a>, but unfortunately it still has no answer and no solution.</p>
",https://stackoverflow.com/questions/75391157/problem-with-unit-testing-of-billing-library-5-in-android,"['unit-testing', 'android-billing', 'play-billing-library']",137,False,0,0
Pytest unit testing getting a Can&#39;t instantiate abstract class error,"<p>I'm currently testing this code using pytest from Storm_Centre.py</p>
<pre><code>class Storm_Centre:
    def __init__(self):
        self.storm_list = []
        
    def already_exists(self, name) -&gt; bool:
        for storm in self.storm_list:
            if storm.name == name:
                return True
        return False
</code></pre>
<p>this code uses code from Storm.py</p>
<pre><code>from abc import ABC, abstractmethod


class Storm(ABC):
    def __init__(self, name, wind_speed):
        self.name = name
        self.wind_speed = wind_speed
        super().__init__()

    @abstractmethod
    def calculate_classification(self):
        pass

    @abstractmethod
    def get_advice(self):
        pass
</code></pre>
<p>I'm testing the code in test_storm.py using the following code:</p>
<pre><code>import pytest
from Storm import Storm
from Storm_Centre import Storm_Centre

def test_already_exists():
    s1 = Storm('Jeff', 10)
    c1 = Storm_Centre()
    c1.storm_list.append(s1)
    assert(c1.already_exists('Jeff') == True)
    assert(c1.already_exists('Dave') == False)
</code></pre>
<p>When running the test I get a &quot;Can't instantiate abstract class&quot; error. If anyone could help solve this error it would be much appreciated. thank you!</p>
",https://stackoverflow.com/questions/76326254/pytest-unit-testing-getting-a-cant-instantiate-abstract-class-error,"['python', 'unit-testing', 'pytest']",28,True,-1,2
How to mock next/router for unit testing with vitest?,"<p>When trying to write simple tests for out Next.js app that uses <code>useRouter()</code> hook, <code>vitest</code> starts throwing errors.</p>
<p>Looking for ways to mock next/router for unit testing with vitest.</p>
",https://stackoverflow.com/questions/75831875/how-to-mock-next-router-for-unit-testing-with-vitest,"['javascript', 'node.js', 'unit-testing', 'next.js', 'vitest']",345,True,0,1
Angular unit testing disable button attribute when form is invalid,"<p>I am disabling button when the form is invalid. When form is filled in properly button is enabled. It works, but I have problems with testing it:</p>
<p>I wrote the test like this:</p>
<pre><code> it('should have enabled button when title was provided', () =&gt; {
        fixture.detectChanges();
        component.addTaskFormGroup.controls.title.setValue('TITLE');
        expect(component.addTaskFormGroup.invalid).toBeFalsy();
        fixture.detectChanges();
        const createBtn = fixture.debugElement.nativeElement.querySelector('[data-test-id=&quot;createTask&quot;]');
        expect(createBtn.disabled).toBeFalse();
    });
</code></pre>
<p>It is properly setting form to invalid, but the last assertion returns <code>Expected true to be false.</code></p>
<p>In html I have it stated like this:</p>
<pre><code>  &lt;button mat-raised-button color=&quot;primary&quot; [disabled]=&quot;addTaskFormGroup.invalid&quot; data-test-id=&quot;createTask&quot;  type=&quot;submit&quot; &gt;
</code></pre>
",https://stackoverflow.com/questions/75627192/angular-unit-testing-disable-button-attribute-when-form-is-invalid,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",209,False,0,1
why android studio MVVM observeForever return null in Unit testing?,"<p>I am  trying to unit test a simple viewmodel class with a method which is return a mutableLiveData.but when set observeForever() for my method , it retun a NullPointerException.</p>
<pre><code>@RunWith(MockitoJUnitRunner.class)
public class ListViewModelTest {
    @Rule
    public InstantTaskExecutorRule instantExecutorRule = new InstantTaskExecutorRule();


    ListViewModel SUT;

    @Mock
    Observer&lt;List&lt;Blog&gt;&gt; observer;

    @Mock
    BlogRepository repository;

    @Mock
    LifecycleOwner owner;


    List&lt;Blog&gt; data = new ArrayList&lt;&gt;();
    @Before
    public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        SUT = new ListViewModel(repository);
/*
        Blog da= new Blog();
        da.setDescription(&quot;s&quot;);
        da.setImageUrl(&quot;dssd&quot;);
        da.setTitle(&quot;dss&quot;);
        data.add(da);
        observer.onChanged(data);*/

    }

    @Test
    public void testfatchingDataSuccess(){
        SUT.getLiveBlogData().observeForever(observer);
        when(repository.getBlogList()).thenReturn(data);
        verify(observer).onChanged(data);
    }

    @After
    public void tearDown() throws Exception {
        SUT = null;
        repository = null;
    }

}
</code></pre>
<p>the log &quot;
java.lang.NullPointerException
at androidx.arch.core.executor.DefaultTaskExecutor.isMainThread(DefaultTaskExecutor.java:77)
at androidx.arch.core.executor.ArchTaskExecutor.isMainThread(ArchTaskExecutor.java:116)
at androidx.lifecycle.LiveData.assertMainThread(LiveData.java:486)
at androidx.lifecycle.LiveData.observeForever(LiveData.java:224)
at com.example.mvvmfirebase.viewmodel.ListViewModelTest.testfatchingDataNull(ListViewModelTest.java:61)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:61)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker$2.run(TestWorker.java:176)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
&quot;</p>
",https://stackoverflow.com/questions/75831652/why-android-studio-mvvm-observeforever-return-null-in-unit-testing,"['java', 'android-studio', 'unit-testing']",29,False,0,0
spy on method when unit testing http interceptor in angular,"<p>I'm trying to unit test an http interceptor.  The interceptor is used for authorization.  I can test the basic success case, but I'm trying now to test the case where the API call fails because access token is out of date.</p>
<p>My question is, how do I spy on the AuthInterceptorService.getNewTokenAndRetryRequest() method?   My interceptor &amp; unit test code are below.  When I run the unit tests, I get a &quot;Error: Expected spy getNewTokenAndRetryRequest to have been called.&quot; error.</p>
<p><strong>This is my unit test :</strong></p>
<pre><code>  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [TokenStorageService,
  
      {
          provide: HTTP_INTERCEPTORS,
          useClass: AuthInterceptorService,
          multi: true
      }      
      
      ]

    });
    service = TestBed.inject(AuthInterceptorService);
  });


     it('should proceed to refresh token logic on 500 error', inject([HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) =&gt; {
        let  thownError: Error = null;
    
        spyOn(service, &quot;getNewTokenAndRetryRequest&quot;).and.stub();
    
    
        Object.defineProperty(window.document, 'cookie', {
          writable: true,
          value: 'access_token=mycookie',
        });
    
        http.get('/data').subscribe(
            response =&gt; {
                expect(response).toBeTruthy();
            }
        );
    
    
        const req = httpMock.expectOne(r =&gt;
            r.headers.has('Authorization') &amp;&amp; 
            r.headers.get('Authorization').startsWith('Bearer ewogIC') );
    
        req.flush(&quot;failure&quot;,{ status: 500, statusText: &quot;500 error&quot; });
    
        expect(service.getNewTokenAndRetryRequest).toHaveBeenCalled();
    
        httpMock.verify();
      }));
</code></pre>
<p><strong>This is my code for the interceptor</strong></p>
<pre><code> export class AuthInterceptorService implements HttpInterceptor {

  constructor(private tokenStorageService: TokenStorageService, private httpClient: HttpClient) { }

  intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;any&gt; {
    const updatedHeaders:HttpHeaders = req.headers.set('Authorization', 'Bearer ' + this.tokenStorageService.getAccessToken());
    const updatedRequest = req.clone({headers: updatedHeaders})
    return next.handle(updatedRequest)
    .pipe(  
      catchError((error: HttpErrorResponse) =&gt; {
        if (error.status===500) {

          console.log('500 error, try to use the refresh token');
          try{
            this.getNewTokenAndRetryRequest(req);
            return of([]);
          }catch (error) {
            return throwError(error);
          }
        }else{
          let errorMsg =  `Error Code: ${error.status},  Message: ${error.message}`;

          return throwError(error.error);
        }
       
    })
   )
  }

  getNewTokenAndRetryRequest(req: HttpRequest&lt;any&gt;): void {
    //do stuff

  }
 
</code></pre>
",https://stackoverflow.com/questions/75114428/spy-on-method-when-unit-testing-http-interceptor-in-angular,"['angular', 'jasmine', 'angular-unit-test', 'httptestingcontroller']",360,False,0,1
How to create a custom task only for unit testing?,"<p>Currently, unit tests in c# needs a lot of shell parameters: <a href=""https://stackoverflow.com/questions/76258066/how-to-simplify-the-unit-tests-execution-in-c-sharp-when-shell-is-used-instead-v"">How to simplify the unit tests execution in c# when shell is used instead Visual Studio?</a></p>
<p>That's why I'm trying to create a custom task to be able to run the tests and code coverage with <strong>one line</strong> and also keep it cross-platform for windows developers.</p>
<p>I tried something like <code>dotnet foo</code> but I could not find any official or workaround.</p>
<h1>dotnet + msbuild</h1>
<p>The following task works</p>
<pre><code>&lt;Target Name=&quot;Foo&quot;&gt;
  &lt;Message Text=&quot;This is a Foo task&quot; /&gt;
&lt;/Target&gt;

dotnet msbuild -target:Foo
</code></pre>
<p>But the problem is: This command loads the main <strong>./src/Main.csproj</strong>, not the <strong>./test/Test.csproj</strong> of tests, so the custom task (for unit test) should be in the <strong>Main.csproj</strong>, which doesn't make sense</p>
<pre><code>./src
./src/Controllers
./src/Controllers/**
./src/Main.csproj
./src/Startup.cs
./test
./test/Controllers
./test/Controllers/**
./test/Test.csproj
</code></pre>
<p>I tried to pass the relative location of <strong>./test/Test.csproj</strong> with</p>
<ul>
<li><code>--project</code> without success</li>
</ul>
<p>But another error is raised: <code>error MSB1001: Unknown switch.</code></p>
<p>So my question is:</p>
<blockquote>
<p>How to create a custom task only for unit testing?</p>
</blockquote>
",https://stackoverflow.com/questions/76258850/how-to-create-a-custom-task-only-for-unit-testing,"['c#', 'unit-testing', '.net-core', 'msbuild']",28,True,0,1
How to authenticate Firestore in ReactJS app when unit testing?,"<p>So I'm using ReactJS to build an app with Firestore as its backend. I want to run some tests and the tests passed but some error was logged when running all tests.</p>
<p>The error:</p>
<pre><code>Attempted to log &quot;[FirebaseError: 7 PERMISSION_DENIED: Missing or insufficient permissions.] {
      code: 'permission-denied',
      customData: undefined,
      toString: [Function (anonymous)]
    }&quot;.
</code></pre>
<p>My question is that, are we authenticated when we run the tests? If we are not, how can I authenticate so that it can reads from the database? Because in the database, I have set up Firestore rules where if authenticated, then allow read.</p>
<p>If you need more information, feel free to comment below, as I'm pretty confused on how to approach this issue.</p>
",https://stackoverflow.com/questions/75029581/how-to-authenticate-firestore-in-reactjs-app-when-unit-testing,"['reactjs', 'firebase', 'google-cloud-firestore']",33,False,0,0
Zenject instantation error while unit testing a custom prefab factory,"<p>I am working on a Unity project using the Extenject / Zenject dependency injection framework, and I am having trouble writing unit tests for custom prefab factories.</p>
<p>I have an <code>ArchitectController</code> that needs to instantiate different prefab variants that all have the same <code>Placeable</code> component attached. It does this by referencing a Scriptable Object that references the respective prefab. The <code>Placeable</code> component takes in a <code>Direction</code> and a <code>IGameTile</code> as it's own dependencies, so they are passed to the factory too.</p>
<pre class=""lang-cs prettyprint-override""><code>// in Placeable.cs
[Inject]
public void Construct(Direction buildingOrientation, IGameTile host) { ... }
</code></pre>
<p>I created my custom factory:</p>
<pre class=""lang-cs prettyprint-override""><code>public class CustomPlaceableFactory : IFactory&lt;PlaceableSO, Direction, IGameTile, Placeable&gt;
{

    private DiContainer _container;

    public CustomPlaceableFactory(DiContainer container)
    {
        _container = container;
    }

    public Placeable Create(PlaceableSO placeableSO, Direction buildDirection, IGameTile hostingTile)
    {
        return _container.InstantiatePrefabForComponent&lt;Placeable&gt;(placeableSO.content, new object[]
        {
            buildDirection, hostingTile
        });
    }
}
</code></pre>
<p>and then implemented it into the <code>ArchitectController</code> class like so:</p>
<pre class=""lang-cs prettyprint-override""><code>// in ArchitectController.cs
public void PlaceContentAtTile(PlaceableSO currentContentSO, IGameTile hostTile)
{
    var direction = CurrentBuildingOrientation;
    var newContent = _placeablePlaceableFactory.Create(currentContentSO, direction, hostTile);
    hostTile.Content = newContent;
}

</code></pre>
<p>Now in runtime, this works great! 🎉</p>
<p>But when I wanted to write a unit test for this piece of code, I ran into some issues... Namely,</p>
<blockquote>
<p>Assert hit! Error occurred while instantiating object of type
'Placeable'. Instantiator should not be used to create new mono
behaviours.  Must use InstantiatePrefabForComponent,
InstantiatePrefab, or InstantiateComponent.</p>
</blockquote>
<p>Which in my eyes is weird, because my factory <em>is</em> making use of InstantiatePrefabForComponent?</p>
<p>I think I might be missing something. If anyone has any ideas as to what might be causing this, I'd be keen to know.</p>
<p>Here is the test installer with a comment that indicates the line that throws the assertion. The <a href=""https://pastebin.com/zv7HacfJ"" rel=""nofollow noreferrer"">stacktrace</a> then leads to the create method of my custom factory.</p>
<pre class=""lang-cs prettyprint-override""><code>public class ArchitectControllerTestInstaller : Installer&lt;ArchitectControllerTestInstaller&gt;
{
    public override void InstallBindings()
    {
        Container.Bind&lt;IGridManager&gt;().FromSubstitute();

        // bind the factory
        Container.BindFactory&lt;PlaceableSO, Direction, IGameTile, Placeable, Placeable.Factory&gt;();
        Container.Bind&lt;IArchitectController&gt;().To&lt;ArchitectController&gt;().AsSingle();
        
        Container.Bind&lt;IGameTile&gt;().FromSubstitute();
        Container.Bind&lt;IGameTileContent&gt;().FromSubstitute();

        // bind the scriptable object that we will get the to be instantiated prefab from
        Container.Bind&lt;PlaceableSO&gt;().FromScriptableObjectResource(&quot;Scriptable Objects/Placeable Blue&quot;).AsSingle();
    }
}

// BaseUnitTestFixture just calls `Container.Inject(this)` after the test setup
// it extends from ZenjectUnitTestFixture and adds no other behaviour other than
// ensuring I don't forget to call it.
public class ArchitectControllerTest : BaseUnitTestFixture 
{
    protected override void TestSetup() 
    {
        ArchitectControllerTestInstaller.Install(Container);
    }

    [Inject] private IArchitectController _controller;
    [Inject] private IGameTile _gameTile;
    [Inject] private PlaceableSO _content;

    [Test]
    public void PlaceContentAtTile()
    {
        // assert hit on this line:
        _controller.PlaceContentAtTile(_content, _gameTile);
    }
    
}
</code></pre>
",https://stackoverflow.com/questions/75739664/zenject-instantation-error-while-unit-testing-a-custom-prefab-factory,"['c#', 'unit-testing', 'unity-game-engine', 'zenject']",131,False,0,0
Unit testing Spring Security client with JPA ClientRegistrationRepository - thread issue,"<p>Our project has a setup with a JPA-based ClientRegistrationRepository</p>
<pre><code>@Service
public class DemoClientRegistrationRepository implements ClientRegistrationRepository {

    @Autowired
    private DemoJpaDao demoJpaDao;

    @Override
    @Transactional
    public ClientRegistration findByRegistrationId(String registrationId) {
        return Optional.ofNullable(demoJpaDao.getFirstByRegistrationId(registrationId))
            .map(this::toClientRegistration)
            .orElse(null);
    }

    private ClientRegistration toClientRegistration(DemoOAuthClient demoOauthClient) {
        return ClientRegistrations.fromIssuerLocation(demoOauthClient.getEndpoint())
            .clientId(demoOauthClient.getClientId())
            .clientSecret(demoOauthClient.getSecret())
            .clientName(demoOauthClient.getDescription())
            .build();
    }

}
</code></pre>
<p>now I'm writing a simple test which creates a DemoOAuthClient and then runs a GET</p>
<pre><code>@Test
void testGetFeedTarget() {
    DemoOAuthClient demoOAuthClient = createDemoOAuthClient ();
    demoJpaDao.save(demoOAuthClient );
    demoJpaDao.flush();
    // act
    String result = apiService.getTargetDescription(demoOAuthClient );
    // assert
    Assertions.assertEquals(&quot;foobar&quot;, result);
    
}
</code></pre>
<p>with the getTargetDescription() implementation as</p>
<pre><code>@Override
public String getTargetDescription(DemoOAuthClient demoOAuthClient ) {
    return this.webClient
        .get()
        .uri(demoOAuthClient.getEndpoint())
        .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(demoOAuthClient.getRegistrationId()))
        .retrieve()
        .bodyToMono(String.class)
        .block; // or .toFuture().get() ?
}
</code></pre>
<p>This fails because the call to findByRegistrationId() does not run in the &quot;main&quot; unit test thread, so the DB transaction doesn't find the (uncommited) DemoOAuthClient. Can I configure the OAuth2AuthorizedClientManager to run in the main thread for unit tests?</p>
",https://stackoverflow.com/questions/75484628/unit-testing-spring-security-client-with-jpa-clientregistrationrepository-thre,"['spring', 'spring-security', 'oauth-2.0', 'spring-webflux']",38,False,0,0
Unit testing a generic base Controller using Moq and Xunit,"<p>I currently have a base class like this:</p>
<pre><code>public abstract class AbstractControllerBase&lt;T&gt; : Controller where T : AbstractControllerBase&lt;T&gt;
{
    private ILogger&lt;T&gt; _logger;

    protected ILogger&lt;T&gt; Logger =&gt; _logger ??= HttpContext.RequestServices.GetService&lt;ILogger&lt;T&gt;&gt;();

    public AbstractControllerBase()
    { }
}
</code></pre>
<p>and inherited class like this:</p>
<pre><code>public abstract class ControllerBase&lt;T&gt; : AbstractControllerBase&lt;T&gt; where T : ControllerBase&lt;T&gt;
{
    private IRepository _repository;

    protected IRepository Repository
    {
        get
        {
            if (_repository == null &amp;&amp; HttpContext != null)
                _repository = (IRepository)HttpContext.RequestServices.GetService(typeof(IRepository));
            return _repository;
        }
    }

    public ControllerBase()
    { }

    public IActionResult CheckRedirectUrl(string url)
    {
        if (Url.IsLocalUrl(url))
        {
            var redirectResult = Redirect(url);
            return redirectResult;
        }
        else
        {
            return RedirectToAction(&quot;Index&quot;, &quot;Home&quot;);
        }
    }
}
</code></pre>
<p>There are 25 controllers which inherit from ControllerBase. How to init Repository while unit testing. I tried doing this:</p>
<pre><code>if (controller is Website.Controllers.ControllerBase &lt; typeof(controller) &gt;)
{
    ((Website.Controllers.ControllerBase)controller).Repository = repository;
}
</code></pre>
<p>But this requires generic arguments as well. Kindly suggest.</p>
",https://stackoverflow.com/questions/75691839/unit-testing-a-generic-base-controller-using-moq-and-xunit,"['c#', '.net', 'asp.net-core', 'moq', 'xunit.net']",100,False,0,1
How to mock cashier defaultPaymentMethod() while unit testing in laravel?,"<p>i am not being able to mock cashier's defaultPaymentMethod method while testing. i have a controller named PaymentController and there is method called exec() as below:</p>
<pre><code>public function exec()
{
   $user = Cashier::findBillable(\Auth::user()-&gt;stripe_id);
   $paymentMethodId = $user-&gt;defaultPaymentMethod()-&gt;id;

   return $paymentMethodId;
}
</code></pre>
<p>i am retrieving paymentMethodId calling function defaultPaymentMethod() from trait ManagesPaymentMethods.php which is used in User.php Model.</p>
<p>Now i want to retrieve paymentMethodId by mocking defaultPaymentMethod() while writing test.</p>
<p>I mocked defaultPaymentMethod() method from model User::class as ManagesPaymentMethods.php trait is used in User.php model.</p>
<pre><code>protected function setUp(): void
{
  parent::setUp();
  $this-&gt;setUpFaker();

  $this-&gt;user = User::factory()-&gt;create([
     'stripe_id' =&gt; Str::random(14)
  ]);
}

public function test_paymentmethod_id_is_retrieved()
{
  $defaultPaymentMethod = new BankAccount();

  $mock = Mockery::mock(User::class)-&gt;makePartial();
  $mock-&gt;shouldReceive('defaultPaymentMethod')
      -&gt;once()
      -&gt;andReturn($defaultPaymentMethod);

  $response = $this-&gt;actingAs($user)
            -&gt;post($this-&gt;url);

  $this-&gt;asertEquals($response['paymentMethodId']-&gt;id, $defaultPaymentMethod-&gt;id);
}
</code></pre>
",https://stackoverflow.com/questions/75407722/how-to-mock-cashier-defaultpaymentmethod-while-unit-testing-in-laravel,"['laravel', 'unit-testing', 'phpunit', 'mockery', 'laravel-cashier']",64,False,0,0
How to aggregate Unit testing and Integration test coverage result,"<pre><code>gradle-check:
  ...
  script:
    - ./gradlew check --console=plain ${GRADLE_CHECK_OPTS}
  after_script:
    - mkdir build/reports/tests/ut/
    - mv build/reports/tests/test/* build/reports/tests/ut/
  artifacts:
    when: always
    expire_in: 1 week
    reports:
      junit: build/test-results/test/**/TEST-*.xml
    paths:
      - build/reports/jacocoHtml/
      - build/reports/tests/ut/

integration-test:
  ...
  script:
    - ./gradlew test -Dtest.profile=integration --tests &quot;com.test.integrationtest.*&quot;
    - cat build/reports/jacocoHtml/index.html
  coverage: '/Total.*?([0-9]{1,3})%/'
  after_script:
    - mkdir build/reports/tests/it/
    - mv build/reports/tests/test/* build/reports/tests/it/
  artifacts:
    when: always
    expire_in: 1 week
    reports:
      junit: build/test-results/test/**/TEST-*.xml
    paths:
      - build/reports/jacocoHtml/
      - build/reports/tests/it/

pages:
  stage: pages
  dependencies:
    - gradle-check
    - integration-test
  script:
    - mkdir -p public
    - mv build/reports/tests/ut/ public/
    - mv build/reports/tests/it/ public/
    - mv build/reports/jacocoHtml/ public/
  artifacts:
    paths:
      - public
    expire_in: 100 yrs
  when: always
  ....
</code></pre>
<p>I wanted aggregation between Unit Testing &amp; Integration Testing coverage,
I can see only unit testing coverage is generated in gitlab pipeline,<br />
And integration test coverage is not getting generated in pipeline.</p>
<p>gradle.build file below</p>
<pre><code>def jacocoTestExclude = [
        'com/test/constants/**',
        'com/test/model/**',
]
jacocoTestReport {
    reports {
        xml.enabled false
        csv.enabled false
        html.enabled true
        html.destination file(&quot;${buildDir}/reports/jacocoHtml&quot;)
    }
    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it, exclude: jacocoTestExclude
            )
        }))
    }
}

jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = 0.0
            }

            failOnViolation true
        }
    }

    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it, exclude: 'jacocoExclude'
            )
        }))
    }
}

jacoco {
    toolVersion = &quot;0.8.7&quot;
}

test {
    testLogging {
        showStandardStreams = true
        exceptionFormat = 'full'
    }
    if (System.properties['test.profile'] != 'integration') {
        exclude '**/*integrationtest*'
    }
}

check.dependsOn jacocoTestCoverageVerification
jacocoTestCoverageVerification.dependsOn jacocoTestReport
</code></pre>
<p>Since integration test class is not required to run with unit test I have excluded that in test().
jacocoTestCoverageVerification doesn't have any exclusion, some dummy string it is</p>
",https://stackoverflow.com/questions/76109843/how-to-aggregate-unit-testing-and-integration-test-coverage-result,"['gitlab-ci', 'code-coverage', 'jacoco', 'test-coverage']",74,False,0,0
expect(received).toEqual(expected) // deep equality error Jest unit testing,"<p>I am doing unit testing with Jest and got the error in <code>user.controller.spec.ts</code> file. Other files got passed.</p>
<p>Old error:</p>
<pre><code> PASS  src/app.controller.spec.ts (10.482 s)
 PASS  src/users/services/users.service.spec.ts (11.629 s)
 FAIL  src/users/controllers/users.controller.spec.ts (12.239 s)
  ● UsersController › should create a user

    expect(received).toEqual(expected) // deep equality

    - Expected  - 5
    + Received  + 1

    - Object {
    -   &quot;birthDate&quot;: 2000-06-07T00:00:00.000Z,
    -   &quot;email&quot;: &quot;xs@gsuj.lk&quot;,
    -   &quot;name&quot;: &quot;aqs&quot;,
    - }
    + Promise {}

      45 |   it('should create a user' , () =&gt;{
      46 |     const dto ={id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : &quot;xs@gsuj.lk&quot; };
    &gt; 47 |     expect(controller.create(dto)).toEqual({
         |                                    ^
      48 |
      49 |       name:dto.name,
      50 |       birthDate :dto.birthDate,

      at Object.&lt;anonymous&gt; (src/users/controllers/users.controller.spec.ts:47:36)
</code></pre>
<p>Old error got resolved and now getting this new error:</p>
<pre><code> PASS  src/app.controller.spec.ts (10.573 s)
 PASS  src/users/services/users.service.spec.ts (11.867 s)
 FAIL  src/users/controllers/users.controller.spec.ts (12.282 s)
  ● UsersController › should create

    expect(received).toEqual(expected) // deep equality

    Expected: {&quot;birthDate&quot;: 2000-06-07T00:00:00.000Z, &quot;email&quot;: &quot;xs@gsuj.lk&quot;, &quot;id&quot;: 2, &quot;name&quot;: &quot;aqs&quot;}
    Received: &quot;user created successfully&quot;

      62 |     const data = await controller.create(dto);
      63 |
    &gt; 64 |          expect(data).toEqual({
         |                       ^
      65 |           id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : &quot;xs@gsuj.lk&quot;
      66 |          })
      67 |     expect(controller).toBeDefined();

      at src/users/controllers/users.controller.spec.ts:64:23
      at fulfilled (src/users/controllers/users.controller.spec.ts:5:58)

Test Suites: 2 failed, 2 passed, 4 total
Tests:       1 failed, 4 passed, 5 total
</code></pre>
<p>This is <strong>Older</strong> <code>user.controller.spec.ts</code> file:</p>
<pre><code>import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from '../services/users.service';
import { UsersController } from './users.controller';

describe('UsersController', () =&gt; {
  let controller: UsersController; 
  
   const mockUsersService ={
    create: jest.fn(dto =&gt; {
      return {
         
        ...dto
      };
    }),
    update:jest.fn((id,dto) =&gt;({
      id,
      ...dto
    }))
   }

  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UsersController],
      providers:[UsersService],
    })
    .overrideProvider(UsersService)
    .useValue(mockUsersService)
    .compile();

    //get service module from user module
     controller = module.get&lt;UsersController&gt;(UsersController);
  });

  //check if service available
  it('should be defined', () =&gt; {
    expect(controller).toBeDefined();
  });

  // it('hould create a user', () =&gt; {
  //   expect(controller.create({name:'aqs'})).toEqual({

  //   });
  // });

  it('should create a user' , () =&gt;{
    const dto ={id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : &quot;xs@gsuj.lk&quot; };
    expect(controller.create(dto)).toEqual({
      id:dto.id,
      name:dto.name,
      birthDate :dto.birthDate,
      email : dto.email
    });

    expect(mockUsersService.create).toHaveBeenCalledWith(dto);
  });
})
</code></pre>
<p>This is <strong>new</strong> <code>user.controller.spec.ts</code> file:</p>
<pre><code>import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from '../services/users.service';
import { UsersController } from './users.controller';

describe('UsersController', () =&gt; {
  let controller: UsersController; 
  
   const mockUsersService ={
    create: jest.fn(dto =&gt; {
      return {
         
        ...dto
      };
    }),
    update:jest.fn((id,dto) =&gt;({
      id,
      ...dto
    }))
   }

  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UsersController],
      providers:[UsersService],
    })
    .overrideProvider(UsersService)
    .useValue(mockUsersService)
    .compile();

    //get service module from user module
     controller = module.get&lt;UsersController&gt;(UsersController);
  });

  //check if service available
  it('should be defined', () =&gt; {
    expect(controller).toBeDefined();
  });

  // it('hould create a user', () =&gt; {
  //   expect(controller.create({name:'aqs'})).toEqual({

  //   });
  // });

  // it('should create a user' , () =&gt;{
  //   const dto ={id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : &quot;xs@gsuj.lk&quot; };

  //   expect(controller.create(dto)).toEqual({
  //     id:dto.id,
  //     name:dto.name,
  //     birthDate :dto.birthDate,
  //     email : dto.email
  //   });
    
  //   expect(mockUsersService.create).toHaveBeenCalledWith(dto);
  // });

  it('should create', async () =&gt; {

    const dto ={id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : &quot;xs@gsuj.lk&quot; };

    const data = await controller.create(dto);
     
         expect(data).toEqual({ 
          id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : &quot;xs@gsuj.lk&quot; 
         })
    expect(controller).toBeDefined();
  });
})
</code></pre>
<p><code>user.service.spec.ts</code> file:</p>
<pre><code>import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { getRepository } from 'typeorm';
//import { UsersController } from '../controllers/users.controller';
import { UsersService } from './users.service';
import {User} from '../entities/user.entity'

describe('UsersService', () =&gt; {
  let service: UsersService;
//  let providers:UsersController;

const mockUsersRepository ={
  create:jest.fn().mockImplementation(dto =&gt;dto),
  save:jest.fn().mockImplementation(user =&gt; Promise.resolve({id:2, ...user}))

}

  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      providers: [UsersService, {
        provide:getRepositoryToken(User),
        useValue:mockUsersRepository,
      },
    ],
    }).compile();

    service = module.get&lt;UsersService&gt;(UsersService);
  });

  it('should be defined', () =&gt; {
    expect(service).toBeDefined();
  });

  it('should be create a new user record and return that', async () =&gt; {
    expect( await service.create({id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : &quot;xs@gsuj.lk&quot; })).toEqual({
      id:2, 
      name:'aqs',
      birthDate: new Date('2000-06-07'), 
      email : &quot;xs@gsuj.lk&quot; ,
    });
  });
});
</code></pre>
",https://stackoverflow.com/questions/75043375/expectreceived-toequalexpected-deep-equality-error-jest-unit-testing,"['jestjs', 'nestjs', 'deepequals']",1186,False,0,1
Why am I facing this TypeError in Angular unit testing?,"<pre><code>this.columnDefs.forEach((columnDef) =&gt; {
  columnDef.floatingFilter = this.hasFloatingFilter;
});
this.gridApi.setColumnDefs(this.columnDefs);
</code></pre>
<p>ERROR: 'ERROR', TypeError: this.gridApi.setColumnDefs is not a function
TypeError: this.gridApi.setColumnDefs is not a function</p>
<p>I have declared a variable gridApi of type GridApi from 'ag-grid-community'.
Even though setColumnDefs() is a function. On unit testing, I find the above mentioned error.</p>
",https://stackoverflow.com/questions/76235126/why-am-i-facing-this-typeerror-in-angular-unit-testing,"['angular', 'typescript', 'typeerror', 'ag-grid']",24,False,0,1
How can I use Apache Beam TestPubSub for unit testing,"<p>I am trying to unit test a Java Apache Beam pipeline. I wanted to try and use the org.apache.beam.sdk.io.gcp.pubsub.TestPubsub class (<a href=""https://beam.apache.org/releases/javadoc/2.7.0/org/apache/beam/sdk/io/gcp/pubsub/TestPubsub.html"" rel=""nofollow noreferrer"">https://beam.apache.org/releases/javadoc/2.7.0/org/apache/beam/sdk/io/gcp/pubsub/TestPubsub.html</a>) as it looks like it will enable topics to be created and destroyed within tests.</p>
<p>I am however unsure how this works, is it going to create an in memory pub sub instance for my tests? Or does it require me to either have a project connected to it or the pubsub emulator running in my local environment? Has anyone had any experience with using this and would they be able to provide me with any guidance/examples of how they have used it?</p>
<p>I ask this because at the moment I have a rule defined (detailed below) and when running my test it breaks while initialising the rule with the exception &quot;com.google.api.gax.rpc.PermissionDeniedException: io.grpc.StatusRuntimeException: PERMISSION_DENIED: User not authorized to perform this action.&quot;.</p>
<pre><code>@Rule
public TestPubsub testPubsub = TestPubsub.create();
</code></pre>
",https://stackoverflow.com/questions/76334100/how-can-i-use-apache-beam-testpubsub-for-unit-testing,"['java', 'apache-beam', 'google-cloud-pubsub']",42,True,0,1
"CICD Pipeline Filed Python, Unit Testing TypeError: missing positional argument","<p>Hello guys good afternoon, I hope everything is going well.</p>
<p>I have a project and of course locally works amazing without any problem. The issues comes when I push to GitLab and the CICD test_job doesn't pass so never is build.</p>
<p>Basically the problem is the test part.</p>
<p>The project has a <code>conftest.py</code> file that has some functions, like this:</p>
<pre><code>
def app(client_app):
    f = partial(TestClient, client_app)
    yield f

</code></pre>
<p>And the project has unit testing files, one example is like this:</p>
<pre><code>
import unittest

class MyTestApplicationTopic(unittest.TestCase):

    URL = &quot;/someUrl&quot;
    data_app_topic = {
        &quot;topic&quot;: &quot;burning&quot;,
        &quot;topic_remarks&quot;: &quot;burning&quot;,
        &quot;application_id&quot;: 1
    }



    def test_connection(self, app):
        with app() as client:
            response = client.get(self.URL)
            self.assertEqual(response.status_code, 200)
            print('test passed')


if __name__ == '__main__':
    tester = MyTestApplicationTopic()
    tester.test_connection()

</code></pre>
<p>So basically as you see it's a normal unit test.</p>
<p>As you see the <code>app()</code> function from <code>conftest.py</code> is passed to the <code>test_connection(self, app)</code> function as argument</p>
<p>Of course this is not going to work because when I initialized the class I don't pass the argument:</p>
<pre><code>
if __name__ == '__main__':
    tester = MyTestApplicationTopic()
    tester.test_connection()

</code></pre>
<p>The thing is that I don't know how to pass the argument because as I mentioned before, the <code>tes_conecction(self, app)</code> function, takes this argument from the conftest.py.</p>
<p>So, Obviusly I get the error:</p>
<p><code>'TypeError: test_connection() missing 1 required positional argument: 'app'</code></p>
<p>So basically is something confuse for me because I need to pass the app from conftest.py because this is something related with the project configuration so bascially I pass app() function as argument but also the app()function takes another fucntios as argument and that fucntion takes another function as argument and so on and so for.</p>
<p>So at the end I don't know how handle the error: <code>'TypeError: test_connection() missing 1 required positional argument: 'app'</code> in this specific scenario.</p>
",https://stackoverflow.com/questions/75363138/cicd-pipeline-filed-python-unit-testing-typeerror-missing-positional-argument,"['python', 'unit-testing', 'cicd']",32,True,0,1
Angular Unit - Testing (Jasmin Karma) : Error :Cannot find name &#39;google&#39;,"<p>google.directives.ts:-</p>
<pre><code>  getAutocompletes(addresstext: ElementRef) {
    const autocomplete = new  google.maps.places.Autocomplete(addresstext.nativeElement,
      {
       ...
      });
  google.maps.event.addListener(autocomplete, 'place_changed', () =&gt; 
  {
   ...
  }
</code></pre>
<p>after testing code in jasmin &amp; karma, I got Error :-&gt;
Cannot find name 'google'.</p>
<p>How can I solve this issue for unit testing?
I alreday added &quot;googlemaps&quot; in tsconfig.app.json.</p>
",https://stackoverflow.com/questions/75168369/angular-unit-testing-jasmin-karma-error-cannot-find-name-google,"['angular', 'unit-testing', 'karma-jasmine', 'angular11']",116,True,0,1
How to mock the JavaScript function while writing unit testing,"<p>I am trying to write a unit test for a JavaScript async function , I am using jest. I posting the function below</p>
<p>myClient.js</p>
<pre><code>const {authClient} = require(&quot;../service/gMemry&quot;);

const getResource = async(req,res) =&gt;{
 try{
     const gMemory = authClient(req.header['px-token'];
     const result = await gMemory.api(conFigItem.auth.clientId).get();
     if(!result){
        return res.sendStatus(401).send();
     }
      res.send({result});
    }catch(e){
     res.sendStatus(401).send({result:null]);
   }
  };
</code></pre>
<p>myClientManager.js</p>
<pre><code> const graph = require('@microsoft/mirosoft-graph-client);
 require('isomorphic-fetch');

 authClient = (accessToken)=&gt;{
 const client = graph.Client.init({
 authProvider : (done) =&gt; {
 done(null,accessToken);
  }
});
</code></pre>
<p>myClient.spec.js</p>
<pre><code> import {getResource} from &quot;./docs&quot;;

 describe('getResource' , () =&gt;{
   it('auth req &amp; response' , async()=&gt;{
    const mockReq = {
     headers :{
       'px-token':'my-token',
     },
    };
   ...............
  
</code></pre>
<p>i am getting the below exception</p>
<p>authClient is not defined</p>
<blockquote>
<p>authClient = (accessToken)=&gt;{</p>
</blockquote>
<p>How i can write the unit test for this method, please help ,i am new to javascript unit test.</p>
",https://stackoverflow.com/questions/76212635/how-to-mock-the-javascript-function-while-writing-unit-testing,"['javascript', 'unit-testing', 'jestjs']",20,False,0,0
How would I go about unit testing this using pytest?,"<p>I'm trying to unit test the below code using pytest but I'm completely unsure link a list value with the function I'm testing.</p>
<pre><code>def already_exists(self, name) -&gt; bool:
        for storm in self.storm_list:
            if storm.name == name:
                return True
        return False
</code></pre>
<p>This is the complete code from where I got the function from:</p>
<pre><code>class Storm(ABC):
    def __init__(self, name, wind_speed):
        self.name = name
        self.wind_speed = wind_speed
        super().__init__()

class control_Centre:
    def __init__(self):
        self.storm_list = []

    def already_exists(self, name) -&gt; bool:
        for storm in self.storm_list:
            if storm.name == name:
                return True
        return False
</code></pre>
",https://stackoverflow.com/questions/76325228/how-would-i-go-about-unit-testing-this-using-pytest,"['python', 'unit-testing', 'pytest']",29,True,0,1
Unit Testing unable to use mock setup for extension method,"<pre><code>namespace Producer.UnitTests.Controllers
{
    public class ParticipantsControllerTests
    {
        private readonly Mock&lt;IDbConnectionFactory&gt; _mockDbConnectionFactory;
        private readonly Mock&lt;ILogger&lt;Participant&gt;&gt; _mockLogger;
        private readonly Mock&lt;IMapper&gt; _mapper;
        public ParticipantsControllerTests()
        {
            _mockDbConnectionFactory = new Mock&lt;IDbConnectionFactory&gt;();
            _mockLogger = new Mock&lt;ILogger&lt;Participant&gt;&gt;();
            _mapper = new Mock&lt;IMapper&gt;();
        }

        [Fact]
        public async Task Get_ShouldReturnOkResponse_WhenIdExists()
        {
            var expectedSport = new Participant { Id = 1, Name = &quot;Matan&quot;};
            var mockDb = new Mock&lt;IDbConnection&gt;();
            mockDb.Setup(x =&gt; x.LoadSingleByIdAsync&lt;Participant&gt;(1, It.IsAny&lt;string[]&gt;(), It.IsAny&lt;CancellationToken&gt;())).ReturnsAsync(expectedSport);
            _mockDbConnectionFactory.Setup(x =&gt; x.OpenAsync(It.IsAny&lt;CancellationToken&gt;())).ReturnsAsync(mockDb.Object);
            var controller = new ParticipantsController(_mockDbConnectionFactory.Object, _mockLogger.Object, _mapper.Object);

            var result = await controller.Get(1);

            Assert.IsType&lt;OkObjectResult&gt;(result);
            var okResult = (OkObjectResult)result;
            var sport = (Sport)okResult.Value;
            Assert.Equal(expectedSport.Id, sport.Id);
            Assert.Equal(expectedSport.Name, sport.Name);
        }
    }
}

</code></pre>
<p>the setup on LoadSingleByIdAsync and OpenAsync isn't working because they are extension methods.
what can I do to fix that?
The error I get:
System.NotSupportedException : Unsupported expression: x =&gt; x.LoadSingleByIdAsync((object)1, It.IsAny&lt;string[]&gt;(), It.IsAny())
Extension methods (here: OrmLiteReadApiAsync.LoadSingleByIdAsync) may not be used in setup / verification expressions.</p>
",https://stackoverflow.com/questions/75604772/unit-testing-unable-to-use-mock-setup-for-extension-method,"['c#', 'unit-testing', 'mocking']",14,False,0,0
Unit Testing Error when i use JsonRequired Attribute in Dto Class,"<p>My unit testing is failed when i change Required field to <code>JsonRequired</code>
my Dto Class</p>
<p>class name = customerDto</p>
<pre><code>[JsonRequired]
public int ID {get; set;}
[JsonRequired]
public int Name{get; set;}
</code></pre>
<p>When use Required Attribute it was passed.</p>
<p>My Test Code</p>
<pre><code>var data = new customerDto {ID = ValidID};
byte[] byteArray = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
httpContext.Request.Body = new MemoryStream(byteArray);
</code></pre>
<p>in above line debug will stop. i need to fix this.</p>
<p>My unit testing failed when i use JsonRequired Attribute. But it will successfully debug when i use Required attribute</p>
",https://stackoverflow.com/questions/75280518/unit-testing-error-when-i-use-jsonrequired-attribute-in-dto-class,"['c#', 'json.net']",52,True,1,1
calling a url with reverse with query string during unit testing,"<p>I have this URL that i want to test:</p>
<p><code>urlpatterns = [ path('produce&lt;str:code&gt;', ProduceSpreadSheet.as_view(), name=&quot;produce&quot; ), ]</code></p>
<p>my test is:</p>
<pre><code>class ProduceSpreadSheetTest(TestCase):

    
    def setUp(self):
        self.code = &quot;abcd&quot;
        
    def test_valid_token(self):
        url = reverse('produce', query_kwargs={'code': self.code})
        
        response = client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
</code></pre>
<p>I get the error:</p>
<p>TypeError: reverse() got an unexpected keyword argument 'query_kwargs'</p>
<p>when I change query_kwargs to kwargs: I get the error:</p>
<pre><code>  TypeError: get() got an unexpected keyword argument 'code'
</code></pre>
<p>The method to be tested is:</p>
<pre><code>class ProduceSpreadSheet(APIView):

   def get(self, request):

        code = request.query_params.get('code',None)
        // continue
        
</code></pre>
<p>I want to call it with</p>
<pre><code>     .../produce?code=abcd
</code></pre>
<p>query_kwargs and kwargs and reverse('produce') + 'code=code'</p>
",https://stackoverflow.com/questions/75784802/calling-a-url-with-reverse-with-query-string-during-unit-testing,"['django', 'django-rest-framework']",27,True,1,1
Data Not Found Hit API of Unit Testing Laravel 8.x,"<p>I'm new to working on backend to make a unit testing of index method with Bearer Token for authentication.</p>
<p>But, I got failure after I run the command : <code>.\vendor\bin\phpunit</code> like below :</p>
<pre><code>PHPUnit 9.5.27 by Sebastian Bergmann and contributors.

..F                                                                 3 / 3 (100%)

Time: 00:00.228, Memory: 24.00 MB

There was 1 failure:

1) Tests\Feature\UserControllerTest::test_returns_user_data_list_successfully
Expected response status code [200] but received 404.

The following errors occurred during the request:

{
    &quot;success&quot;: false,
    &quot;message&quot;: &quot;Failed&quot;,
    &quot;error_code&quot;: 4041,
    &quot;errors&quot;: {
        &quot;message&quot;: &quot;Data not found&quot;
    }
}

Failed asserting that 200 is identical to 404.

C:\Users\artha\Documents\Switch\vendor\laravel\framework\src\Illuminate\Testing\TestResponse.php:177
C:\Users\artha\Documents\Switch\tests\Feature\UserControllerTest.php:18
</code></pre>
<p>For UserContoller.php :</p>
<pre><code>class UserController extends Controller
{
    public function __construct()
    {
        $this-&gt;middleware('auth.jwt');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = User::orderBy('created_at', 'DESC')-&gt;all();
        $message = 'Success';
        return $this-&gt;sendResponse($user-&gt;makeVisible('role'), $message, 200);
    }
}
</code></pre>
<p>The code of <code>route/api.php</code> :</p>
<pre><code>Route::resource('user', UserController::class, ['except' =&gt; ['create', 'edit']]);
</code></pre>
<p>And I made <code>UserContollerTest.php</code> like below :</p>
<pre><code>&lt;?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class UserControllerTest extends TestCase
{
    public function test_returns_user_data_list_successfully()
    {
        $token    = 'eyJ0eXA.....dY3CtVO1T4o--8nM';
        $response = $this-&gt;withHeaders(['Authorization' =&gt; 'Bearer '. $token,
                        'Accept' =&gt; 'application/json'])
                        -&gt;get('api/user/index');

        $response-&gt;assertStatus(200);
    }
}
</code></pre>
<p>I tried to solved with various ways on internet like read all official documentations and others but I didn't get insight right to solve this. I made <code>.env.testing</code>, too.</p>
<p>Any idea, how to solving this problem?</p>
<p>Thank you for your insight.</p>
<p>I tried to solve with these link :
<a href=""https://www.stackoverflow.com/"">https://stackoverflow.com/questions/46769959/laravel-phpunit-test-with-api-token-authentication</a></p>
<p><a href=""https://www.stackoverflow.com/"">https://stackoverflow.com/questions/55568924/how-to-pass-bearer-token-to-test-api-using-phpunit-and-liip</a></p>
<p><a href=""https://www.stackoverflow.com/"">https://laravel.com/docs/6.x/http-tests#session-and-authentication</a></p>
",https://stackoverflow.com/questions/75016126/data-not-found-hit-api-of-unit-testing-laravel-8-x,"['unit-testing', 'laravel-8', 'bearer-token']",33,False,1,0
Code using HttpConnectionResponseContent for unit testing in a .NET 6 solution,"<p>Here is info about our technical development environment :</p>
<p>•            .NET 6</p>
<p>•            C# 10</p>
<p>•            Visual Studio 2022</p>
<p>I’m trying to Mock System.Net.Http.HttpMessageHandler in my mock Unit test code.</p>
<pre><code>Mock&lt;HttpMessageHandler&gt; handlerMock = new Mock&lt;HttpMessageHandler&gt;(MockBehavior.Strict);

       handlerMock
           .Protected()
           // Setup the PROTECTED method to mock
           .Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;(
              &quot;SendAsync&quot;,
              ItExpr.IsAny&lt;HttpRequestMessage&gt;(),
              ItExpr.IsAny&lt;CancellationToken&gt;()
           )
        // prepare the expected response of the mocked http call
        .Returns(async (HttpRequestMessage request, CancellationToken token) =&gt;
        {
            HttpResponseMessage response = new HttpResponseMessage();
            response.Headers.Add(&quot;Date&quot;, &quot;Mon, 17 Apr 2023 14:55:43 GMT&quot;);
            response.Headers.Add(&quot;Server&quot;, &quot;Warp/3.3.23&quot;);
            response.Headers.Add(&quot;X-Request-ID&quot;, &quot;adaf6342-a007-4155-8480-4cd2eacc3a0b&quot;);
                               response.Content =  ….fill-in-blank code…….

            response.StatusCode = HttpStatusCode.OK;
            //...decide what to put in the response after looking at the contents of the request

            return response;
        }).Verifiable();
</code></pre>
<p>To get more specific, Microsoft.Net.Http.Client package contains the HttpConnectionResponseContent class ( which inherits from HttpContent ).</p>
<p>In the fill-in-blank code area above, I’m trying to implement something like the following code excerpt:</p>
<pre><code>response.Content =  System.Net.Http.HttpConnectionResponseContent(….)
</code></pre>
<p>I’ve been searching the internet to find what dll package contains System.Net.Http.HttpConnectionResponseContent API.
However, it’s a little strange, I found the following github.com link:</p>
<p><a href=""https://github.com/stefanprodan/dockerdash/blob/master/src/Docker.DotNet/Microsoft.Net.Http.Client/HttpConnectionResponseContent.cs"" rel=""nofollow noreferrer"">https://github.com/stefanprodan/dockerdash/blob/master/src/Docker.DotNet/Microsoft.Net.Http.Client/HttpConnectionResponseContent.cs</a></p>
<p>It indicates that the HttpConnectionResponseContent class is part of the Microsoft.Net.Http.Client namespace</p>
<p>However, when I added Microsoft.Net.Http.Client package dll reference to my .NET 6-based solution, it gives the following warning:</p>
<pre><code>Package 'Microsoft.Net.Http 2.2.29' was restored using '.NETFramework,Version=v4.6.1,  
.NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1,   
.NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1'      
instead of the project target framework 'net6.0'. This package may not be fully     compatible  
with your project.
</code></pre>
<p>Furthermore, it shows the problem because when I added the namespace, it states that the following namespace does not exist:</p>
<pre><code>using Microsoft.Net.Http;
</code></pre>
<p>Could someone please post back code and explain how I can implement something along the following sample code?</p>
<pre><code>response.Content =  System.Net.Http.HttpConnectionResponseContent(….)
</code></pre>
",https://stackoverflow.com/questions/76069442/code-using-httpconnectionresponsecontent-for-unit-testing-in-a-net-6-solution,"['c#', '.net-6.0', 'httpresponsemessage']",66,False,0,0
ViewModel with Mock don&#39;t get array of objects in Unit Testing,"<p>I have a project for practicing Unit testing with Swift, normally the project work in the simulator, in the view is the data from a external api and it's functional.</p>
<p>When I try to make the Unit Testing with a mock for get fake data from a Bundle, the test indicates the object with the data in published var is empty, but in the completion block in the result this data is ok.</p>
<p>ViewModel:</p>
<pre><code>final class UserViewModel: ObservableObject {
    @Published var users : [UserModel] = []
    @Published var messageError: String?
    @Published var alertError: Bool = false
    
    private let userRepository: UserRepo
    
    init(userRepository: UserRepo = UserRepository()){
        self.userRepository = userRepository
    }
    
    func getUsers(){
        userRepository.sendRequest(.getUsers, [UserModel].self) {[weak self] result in
            DispatchQueue.main.async {
                switch result {
                case .success(let users):
                    self?.users = users
                case .failure(let error):
                    self?.messageError = error.errorDescription
                    self?.alertError = true
                }
            }
        }
    }
}
</code></pre>
<p>Repository:</p>
<pre><code>protocol UserRepo {
    func sendRequest&lt;T: Decodable&gt;(_ route: APIAssembleRequest, _ type: T.Type, _ params: Any?..., completionBlock: @escaping (Result&lt;T, NetworkError&gt;) -&gt; Void)
}

final class UserRepository: UserRepo {
    
    private let userDatasource: UserData
    
    init (userDatasource: UserData = UserDatasource()){
        self.userDatasource = userDatasource
    }
    
    func sendRequest&lt;T: Decodable&gt;(_ route: APIAssembleRequest, _ type: T.Type, _ params: Any?..., completionBlock: @escaping (Result&lt;T, NetworkError&gt;) -&gt; Void){
        userDatasource.sendRequest(route, type, params, completionBlock: completionBlock)
    }
}
</code></pre>
<p>Datasource:</p>
<pre><code>protocol UserData {
    func sendRequest&lt;T: Decodable&gt;(_ route: APIAssembleRequest, _ type: T.Type, _ params: Any?..., completionBlock: @escaping HandlerUser&lt;T&gt;)
}

final class UserDatasource: UserData, RequestGenerator, RequestHandler, ResponseHandler {
    
    func sendRequest&lt;T: Decodable&gt;(_ route: APIAssembleRequest, _ type: T.Type, _ params: Any?..., completionBlock: @escaping HandlerUser&lt;T&gt;){
        
        let request = self.generateRequest(route: route, params: params)
        _ = self.send(request: request) { response in
            self.handleResponse(response, type, completionBlock: completionBlock)
        }
    }    
}
</code></pre>
<p>UserModel:</p>
<pre><code>struct UserModel: Decodable, Encodable, Equatable {
    var id: Int
    var name: String?
    var email: String?
    var genre: String?
    var status: String?
    
    enum CodingKeys: String, CodingKey {
        case id
        case name
        case email
        case genre = &quot;gender&quot;
        case status
    }
    
    init(from decoder: Decoder) throws{
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.id = try container.decode(Int.self, forKey: .id)
        self.name = try container.decode(String.self, forKey: .name)
        self.email = try container.decode(String.self, forKey: .email)
        self.genre = try container.decode(String.self, forKey: .genre)
        self.status = try container.decode(String.self, forKey: .status)
    }
}
</code></pre>
<p>For that code is working fine</p>
<p>Now the mock</p>
<pre><code>import Foundation
@testable import UsersMVVMURLSessionAndGenericsEnvironmentObject


final class MockUser: UserRepo {
    
    func sendRequest&lt;T&gt;(_ route: UsersMVVMURLSessionAndGenericsEnvironmentObject.APIAssembleRequest, _ type: T.Type, _ params: Any?..., completionBlock: @escaping (Result&lt;T, UsersMVVMURLSessionAndGenericsEnvironmentObject.NetworkError&gt;) -&gt; Void) where T : Decodable {
        completionBlock(.success(decodeData(route: route)))
    }
    
    func decodeData&lt;T:Decodable&gt;(route: APIAssembleRequest) -&gt; T{
        let bundlePath = Bundle.main.path(forResource: &quot;Stub&quot;, ofType: &quot;bundle&quot;)
        let bundle = Bundle(path: bundlePath!)
        switch route {
        case .getUsers:
            return bundle!.decode([UserModel].self, from: &quot;Users.json&quot;) as! T
        default:
            return bundle!.decode(UserModel.self, from: &quot;Users.json&quot;) as! T
        }
        
    }
}
</code></pre>
<p>Bundle extension for decode fake data and function for decode data and compare</p>
<pre><code>import Foundation
@testable import UsersMVVMURLSessionAndGenericsEnvironmentObject

extension Bundle {
    
    func decode&lt;T: Decodable&gt;(_ type: T.Type, from file: String, dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate, keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) -&gt; T {
        guard let url = self.url(forResource: file, withExtension: nil) else {
            fatalError(&quot;Failed to locate \(file) in bundle.&quot;)
        }

        guard let data = try? Data(contentsOf: url) else {
            fatalError(&quot;Failed to load \(file) from bundle.&quot;)
        }

        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = dateDecodingStrategy
        decoder.keyDecodingStrategy = keyDecodingStrategy

        do {
            return try decoder.decode(T.self, from: data)
        } catch DecodingError.keyNotFound(let key, let context) {
            fatalError(&quot;Failed to decode \(file) from bundle due to missing key '\(key.stringValue)' not found – \(context.debugDescription)&quot;)
        } catch DecodingError.typeMismatch(_, let context) {
            fatalError(&quot;Failed to decode \(file) from bundle due to type mismatch – \(context.debugDescription)&quot;)
        } catch DecodingError.valueNotFound(let type, let context) {
            fatalError(&quot;Failed to decode \(file) from bundle due to missing \(type) value – \(context.debugDescription)&quot;)
        } catch DecodingError.dataCorrupted(_) {
            fatalError(&quot;Failed to decode \(file) from bundle because it appears to be invalid JSON&quot;)
        } catch {
            fatalError(&quot;Failed to decode \(file) from bundle: \(error.localizedDescription)&quot;)
        }
    }
}


extension Bundle {
    static func getUsersJson() -&gt; [UserModel] {
        let bundlePath = Bundle.main.path(forResource: &quot;Stub&quot;, ofType: &quot;bundle&quot;)
        let bundle = Bundle(path: bundlePath!)
        
        return bundle!.decode([UserModel].self, from: &quot;Users.json&quot;)
    }
}
</code></pre>
<p>Users.json</p>
<pre><code>[
    {
        &quot;id&quot;: 204656,
        &quot;name&quot;: &quot;Kalyani Acharya&quot;,
        &quot;email&quot;: &quot;acharya_kalyani@becker-white.co&quot;,
        &quot;gender&quot;: &quot;female&quot;,
        &quot;status&quot;: &quot;active&quot;
    },
    {
        &quot;id&quot;: 204655,
        &quot;name&quot;: &quot;Divjot Reddy&quot;,
        &quot;email&quot;: &quot;reddy_divjot@bergnaum.info&quot;,
        &quot;gender&quot;: &quot;female&quot;,
        &quot;status&quot;: &quot;inactive&quot;
    },
    {
        &quot;id&quot;: 204581,
        &quot;name&quot;: &quot;Baidehi Kapoor&quot;,
        &quot;email&quot;: &quot;baidehi_kapoor@cruickshank.name&quot;,
        &quot;gender&quot;: &quot;male&quot;,
        &quot;status&quot;: &quot;inactive&quot;
    },
    {
        &quot;id&quot;: 204503,
        &quot;name&quot;: &quot;Chapal Varman&quot;,
        &quot;email&quot;: &quot;varman_chapal@rippin.com&quot;,
        &quot;gender&quot;: &quot;female&quot;,
        &quot;status&quot;: &quot;inactive&quot;
    },
    {
        &quot;id&quot;: 204424,
        &quot;name&quot;: &quot;Navin Verma&quot;,
        &quot;email&quot;: &quot;navin_verma@bosco-leffler.co&quot;,
        &quot;gender&quot;: &quot;male&quot;,
        &quot;status&quot;: &quot;inactive&quot;
    },
    {
        &quot;id&quot;: 204423,
        &quot;name&quot;: &quot;Gajadhar Nayar&quot;,
        &quot;email&quot;: &quot;nayar_gajadhar@jacobi.org&quot;,
        &quot;gender&quot;: &quot;female&quot;,
        &quot;status&quot;: &quot;inactive&quot;
    },
    {
        &quot;id&quot;: 204421,
        &quot;name&quot;: &quot;Aditeya Nayar&quot;,
        &quot;email&quot;: &quot;aditeya_nayar@paucek.org&quot;,
        &quot;gender&quot;: &quot;female&quot;,
        &quot;status&quot;: &quot;inactive&quot;
    },
    {
        &quot;id&quot;: 204420,
        &quot;name&quot;: &quot;Gajabahu Khan&quot;,
        &quot;email&quot;: &quot;khan_gajabahu@friesen.io&quot;,
        &quot;gender&quot;: &quot;female&quot;,
        &quot;status&quot;: &quot;active&quot;
    },
    {
        &quot;id&quot;: 204419,
        &quot;name&quot;: &quot;Javas Khatri&quot;,
        &quot;email&quot;: &quot;khatri_javas@purdy-klocko.biz&quot;,
        &quot;gender&quot;: &quot;female&quot;,
        &quot;status&quot;: &quot;active&quot;
    },
    {
        &quot;id&quot;: 204329,
        &quot;name&quot;: &quot;Chandramohan Chaturvedi&quot;,
        &quot;email&quot;: &quot;chandramohan_chaturvedi@turcotte.com&quot;,
        &quot;gender&quot;: &quot;male&quot;,
        &quot;status&quot;: &quot;inactive&quot;
    }
]
</code></pre>
<p>And the testable class with function for compare the results with fake data</p>
<pre><code>import XCTest
@testable import UsersMVVMURLSessionAndGenericsEnvironmentObject

final class UsersMVVMURLSessionAndGenericsEnvironmentObjectTests: XCTestCase {
    
    var mockUserViewModel: UserViewModel!
    
    override func setUpWithError() throws{
        mockUserViewModel = UserViewModel(userRepository: MockUser())
        
    }
    
    func test_GetUsers(){
        mockUserViewModel.getUsers()
        XCTAssertEqual(mockUserViewModel.users, Bundle.getUsersJson())
    }
    
    override func tearDownWithError() throws {
        mockUserViewModel = nil
    }
}
</code></pre>
<p>This is the result of the test</p>
<blockquote>
<p>test_GetUsers(): XCTAssertEqual failed: (&quot;[]&quot;) is not equal to (&quot;[UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204656, name: Optional(&quot;Kalyani Acharya&quot;), email: Optional(&quot;acharya_kalyani@becker-white.co&quot;), genre: Optional(&quot;female&quot;), status: Optional(&quot;active&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204655, name: Optional(&quot;Divjot Reddy&quot;), email: Optional(&quot;reddy_divjot@bergnaum.info&quot;), genre: Optional(&quot;female&quot;), status: Optional(&quot;inactive&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204581, name: Optional(&quot;Baidehi Kapoor&quot;), email: Optional(&quot;baidehi_kapoor@cruickshank.name&quot;), genre: Optional(&quot;male&quot;), status: Optional(&quot;inactive&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204503, name: Optional(&quot;Chapal Varman&quot;), email: Optional(&quot;varman_chapal@rippin.com&quot;), genre: Optional(&quot;female&quot;), status: Optional(&quot;inactive&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204424, name: Optional(&quot;Navin Verma&quot;), email: Optional(&quot;navin_verma@bosco-leffler.co&quot;), genre: Optional(&quot;male&quot;), status: Optional(&quot;inactive&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204423, name: Optional(&quot;Gajadhar Nayar&quot;), email: Optional(&quot;nayar_gajadhar@jacobi.org&quot;), genre: Optional(&quot;female&quot;), status: Optional(&quot;inactive&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204421, name: Optional(&quot;Aditeya Nayar&quot;), email: Optional(&quot;aditeya_nayar@paucek.org&quot;), genre: Optional(&quot;female&quot;), status: Optional(&quot;inactive&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204420, name: Optional(&quot;Gajabahu Khan&quot;), email: Optional(&quot;khan_gajabahu@friesen.io&quot;), genre: Optional(&quot;female&quot;), status: Optional(&quot;active&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204419, name: Optional(&quot;Javas Khatri&quot;), email: Optional(&quot;khatri_javas@purdy-klocko.biz&quot;), genre: Optional(&quot;female&quot;), status: Optional(&quot;active&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204329, name: Optional(&quot;Chandramohan Chaturvedi&quot;), email: Optional(&quot;chandramohan_chaturvedi@turcotte.com&quot;), genre: Optional(&quot;male&quot;), status:Optional(&quot;inactive&quot;))]&quot;)</p>
</blockquote>
<p>Thanks for your answers</p>
<p>I try debugging test but the result for completion block is good, only when the test finish is the message with the error</p>
",https://stackoverflow.com/questions/75317626/viewmodel-with-mock-dont-get-array-of-objects-in-unit-testing,"['arrays', 'swift', 'unit-testing', 'mvvm', 'viewmodel']",59,False,0,0
Unit testing not working (Jest + RTL) on Hotkey Provider React JS,"<p>I use Hotkey Provider from Blueprint JS (<a href=""https://blueprintjs.com/docs/#core/components/hotkeys-target2.usage"" rel=""nofollow noreferrer"">blueprint js docs</a>), and I'm not sure how to test it.</p>
<p>It was something like :</p>
<pre><code>&lt;HotkeysTarget2 hotkeys={hotkeys}&gt;
  {({ handleKeyDown, handleKeyUp }) =&gt; (
     &lt;div onKeyDown={handleKeyDown} onKeyUp={handleKeyUp}&gt;
       {/* code... */}
     &lt;/div&gt;
  )}
&lt;/HotkeysTarget2&gt;
</code></pre>
<p>hotkeys :</p>
<pre><code>{
 combo: &quot;1&quot;,
 global: true,
 label: &quot;Press button 1&quot;,
 onKeyUp: () =&gt; fillText(&quot;button 1 pressed&quot;), // Here is function to fill html input
},
</code></pre>
<p>I have tried to write a test case like this :</p>
<pre><code>describe(&quot;test&quot;, () =&gt; {
  it(&quot;should response when press button 1&quot;, () =&gt; {
    const inputField = screen.getByTestId(&quot;pressed-button&quot;);
    userEvent.keyboard(&quot;{1}&quot;);
    expect(inputField).toHaveDisplayValue(&quot;button 1 pressed&quot;)
  });
});
</code></pre>
<p>But it doesn't work. Does anyone have similar issues (or maybe related issues)?</p>
",https://stackoverflow.com/questions/76110716/unit-testing-not-working-jest-rtl-on-hotkey-provider-react-js,"['reactjs', 'jestjs', 'react-testing-library', 'hotkeys', 'blueprintjs']",41,False,0,0
Testing Firestore rules with unit testing v9 SDK and Firestore emulator,"<p>I have a test suite that worked fine when I last used it. I didn't make any fundamental changes except for fixing some typos. Today it is failing with the following error:</p>
<pre class=""lang-bash prettyprint-override""><code>  1) &quot;before all&quot; hook in &quot;{root}&quot;
  2) &quot;after all&quot; hook in &quot;{root}&quot;
  0 passing (308ms)
  2 failing

  1) &quot;before all&quot; hook in &quot;{root}&quot;:
     Error: {&quot;error&quot;:{&quot;code&quot;:500,&quot;status&quot;:&quot;UNKNOWN&quot;}}
      at loadFirestoreRules (file:///home/me/repositories/my-app/node_modules/@firebase/rules-unit-testing/dist/esm/index.esm.js:401:15)
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
      at async initializeTestEnvironment (file:///home/me/repositories/my-app/node_modules/@firebase/rules-unit-testing/dist/esm/index.esm.js:486:9)
      at async Context.&lt;anonymous&gt; (file:///home/me/repositories/my-app/firebase/firestore/__tests__/rules/users.notifications-inbox.test.mjs:26:13)

  2) &quot;after all&quot; hook in &quot;{root}&quot;:
     TypeError: Cannot read properties of undefined (reading 'cleanup')
      at Context.&lt;anonymous&gt; (file:///home/me/repositories/my-app/firebase/firestore/__tests__/rules/users.notifications-inbox.test.mjs:40:17)
</code></pre>
<p>What does this error mean and how can I fix it?</p>
<p>What is <code>{root}</code> in a Mocha test suite? I have no such thing as a &quot;root&quot; file in my test suite. Just a couple of different <code>*.test.mjs</code> files that test different parts of the rule set.</p>
",https://stackoverflow.com/questions/76178060/testing-firestore-rules-with-unit-testing-v9-sdk-and-firestore-emulator,"['google-cloud-firestore', 'mocha.js', 'firebase-security']",17,False,0,1
Angular Unit Testing - Cannot read properties of undefined (reading &#39;size&#39;) NgRx,"<p>I get an error about my spec file unit test without success to solve, the error display when I run <code>npm test</code>, on <code>karma chrome</code>:</p>
<p><a href=""https://i.stack.imgur.com/g5gsJ.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
<p>agent.service.spec.ts:</p>
<pre><code>import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { MemoizedSelector, Store } from '@ngrx/store';
import { MockStore, provideMockStore } from '@ngrx/store/testing';
import * as fromGrid from './../grid/store/grid.reducer';

import { GridActions } from './../grid/store/grid.actions';
import { AgentService } from './agent.service';
import { GridSizeEnum } from '../models/enums/GridSize';


describe('AgentService', () =&gt; {

    let agentService: AgentService;
    let mockStore: MockStore&lt;fromGrid.State&gt;;
    let mockGridSizeSelector: MemoizedSelector&lt;fromGrid.State, GridSizeEnum&gt;;
    let size: GridSizeEnum = GridSizeEnum.GRID_1


    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule,
                RouterTestingModule
            ],
            providers: [
                AgentService,
                provideMockStore({}),

            ],
        });

        agentService = TestBed.get(AgentService);
        mockStore = TestBed.get(Store);
        mockGridSizeSelector = mockStore.overrideSelector(fromGrid.getGridSize, size);
    });

    it('should return the default state', () =&gt; {

        const action = {} as GridActions;
        const state = fromGrid.reducer(fromGrid.initialState, action);
        expect(state).toBe(fromGrid.initialState);

    });

    it('should be created', () =&gt; {

        expect(agentService).toBeTruthy();
    });

    afterEach(() =&gt; {

    })


});
</code></pre>
<p>agent.service.ts :</p>
<p>the constructor part-</p>
<pre><code>  constructor(private http: HttpClient,
    private router: Router,
    private store: Store&lt;fromRoot.State&gt;,
    private gridStore: Store&lt;fromGrid.State&gt;,
    private commandWebSocket: CommandWebsocketService,
    private logService: LogService) {

    this.commandWebSocket.connect();
    this.commandWebSocket.messages$.subscribe((data) =&gt; {
      this.commandWebsocketData(data);
    });

    this.store.pipe(select(fromGrid.getGridSize), takeUntil(this.destroyed$)).subscribe((size) =&gt; {
      if (size) {
        this.gridSize = size;
      }
    });

    this.gridStore.pipe(select(fromGrid.getGridVideoStreamIDs, this.gridSize), takeUntil(this.destroyed$)).subscribe(data =&gt; {
      if (data &amp;&amp; data.length) {
        this.gridStreamIDs = data;
        const byPassCpuIdsCopy = this.byPassCpuIds;
        this.byPassCpuIds = [];
        this.gridStreamIDs.filter((dta) =&gt; {
          this.byPassCpuIds[dta] = byPassCpuIdsCopy[dta];
        });
      }
    });
  }
</code></pre>
<p>grid.reducer.ts :</p>
<pre><code>export const getGridSize = createSelector(
  getGridFeatureState,
  state =&gt; state.size
);
</code></pre>
<p>This error appears a lot in another case, when I have subscribe to specific selector at <code>constructor()</code> or at <code>ngOnInit()</code>  (if it component unit test ).</p>
<p>For solution i tried to initial the state in spec file, see above in <code>agent.service.spec</code>... but it isn't solved.
Need your help, thanks!</p>
<p>How can i solve this error:</p>
<pre><code>Cannot read properties of undefined (reading 'size')
</code></pre>
",https://stackoverflow.com/questions/76004038/angular-unit-testing-cannot-read-properties-of-undefined-reading-size-ngrx,"['angular', 'typescript', 'unit-testing', 'ngrx']",83,True,0,2
Unit testing a ng-container *ngFor which spawns a few components,"<p>Currently, I am trying to unit test the spawning of <strong><code>MatOption</code></strong> elements within a <em><code>ng-container</code></em>.</p>
<p>The problem is that the unit test does not spawn the <strong><code>MatOption</code></strong>, even though they are generated correctly when the code is deployed.</p>
<p>Here is the template code of the component being tested:</p>
<pre><code> &lt;ng-container *ngIf=&quot;attribute.dataType.startsWith('enum#')&quot;&gt;
    &lt;mat-select
      [id]=&quot;attribute.id&quot;
      [formControlName]=&quot;attribute.id&quot;
      [required]=&quot;!attribute.optional&quot;
    &gt;
      &lt;ng-container
        *ngFor=&quot;
          let enumValue of definition.getOptionsForEnum$(attribute.dataType)
            | async
        &quot;
      &gt;
        &lt;mat-option [value]=&quot;enumValue.value&quot;&gt;
          {{ enumValue.name }}
        &lt;/mat-option&gt;
      &lt;/ng-container&gt;
    &lt;/mat-select&gt;
  &lt;/ng-container&gt;
</code></pre>
<p>The <strong><code>MatSelect</code></strong> component is created correctly within the unit test, but for some reason, the <em><code>mat-option</code></em> directives are not being rendered within the unit test.</p>
<p>Here is the spec.ts code:</p>
<pre><code>describe('CategoryAttributesComponent', () =&gt; {
  let component: CategoryAttributesComponent
  let fixture: ComponentFixture&lt;CategoryAttributesComponent&gt;
  let definitionService: DefinitionService
  let entityProviderService: EntityProviderService

  beforeEach(async () =&gt; {
    definitionService = new DefinitionServiceMock()
    entityProviderService = new EntityProviderService()

    await TestBed.configureTestingModule({
      declarations: [
        CategoryAttributesComponent,
        ProductCompositionComponent,
        ProductCompositionDialogComponent,
      ],
      imports: [
        MatFormFieldModule,
        MatInputModule,
        MatSelectModule,
        MatDividerModule,
        MatCheckboxModule,
        ReactiveFormsModule,
        MatDatepickerModule,
        MatNativeDateModule,
        MatChipsModule,
        MatIconModule,
        ControlsModule,
        BrowserAnimationsModule,
      ],
      providers: [
        {
          provide: DefinitionService,
          useValue: definitionService,
        },
        {
          provide: EntityProviderService,
          useValue: entityProviderService,
        },
      ],
    }).compileComponents()

    fixture = TestBed.createComponent(CategoryAttributesComponent)
    component = fixture.componentInstance
    fixture.detectChanges()
  })

  it('enum contains all options given by the service', () =&gt; {
    let enumOnlyCategory = new Category(
      'enumOnly',
      'Le Enum Only',
      false,
      [new Attribute('enum_select', 'Enum Select', 'enum#example', false)],
      [],
      [],
    )

    component.category = enumOnlyCategory
    component.ngOnInit()
    fixture.detectChanges()

    expect(fixture.debugElement.queryAll(By.directive(MatSelect)).length).toBe(
      1,
    )

    for (const element of fixture.debugElement.queryAll(
      By.directive(MatSelect),
    )) {
      printChildren(element)
    }

    expect(fixture.debugElement.queryAll(By.directive(MatOption)).length).toBe(
      4,
    )
  })
})

function printChildren(element: DebugElement) {
  console.log('element: ' + element.name + '; value: ' + element.nativeElement)

  for (const child of element.children) {
    printChildren(child)
  }
}

</code></pre>
<p>Finally here is the code of the service which provides the options for the select:</p>
<pre><code>public override getOptionsForEnum$(enumId: string): Observable&lt;EnumValue[]&gt; {
        let observable: Observable&lt;EnumValue[]&gt; | undefined = this._enumOptionsCachePropietary.get(enumId);

        if (!observable) {
            observable = new Observable(observer =&gt; {
                let example: EnumValue[] = [
                    new EnumValue(0, &quot;Test&quot;),
                    new EnumValue(1, &quot;Example&quot;),
                    new EnumValue(2, &quot;Abcd&quot;),
                    new EnumValue(3, &quot;Efgh&quot;)
                ];

                observer.next(example)
                observer.complete();
            });

            this._enumOptionsCachePropietary.set(enumId, observable);
        }

        return observable;
    }
</code></pre>
<p>Is there any function for rendering in the unit test that I am missing?</p>
<p>I have tried converting the <code>getOptionsForEnum</code> observable into a sync function, thinking it could be a race condition, but no luck.</p>
<p>What I expect to happen is the test to pass, since 4 is the number of expected options that must be within the select.</p>
",https://stackoverflow.com/questions/75826226/unit-testing-a-ng-container-ngfor-which-spawns-a-few-components,"['angular', 'typescript', 'angular-test']",59,False,0,0
.Net Core Snapshot unit testing - Verify does not serialize Newtonsoft.Json JObject,"<p>I try to use <a href=""https://github.com/VerifyTests/Verify/"" rel=""nofollow noreferrer"">Verify</a> to write a snapshot unit test to test a complex object. However, <em>Newtonsoft.Json JObject</em> properties are serialized into an empty array.</p>
<p>Verify version is 19.6.0.</p>
<p>How to make Verify to serialize JObject properly?</p>
<p>Code to validate:</p>
<ul>
<li>in the production project</li>
</ul>
<pre><code>public class TestController : ControllerBase
{
    public async Task&lt;ActionResult&gt; ReturnStubResult()
    {
        return Ok( 
        new {
            Property1 = &quot;value1&quot;,
            Property2 = 5,
            Property3 = new JObject()
            {
                [&quot;ChildProperty1&quot;] = &quot;child value 1&quot;,
                [&quot;ChildProperty2&quot;] = 2
            }
        });
    }
}
</code></pre>
<ul>
<li>in the unit test project (reference Verify.Xunit library)</li>
</ul>
<pre><code>[Fact]
public async Task TestSnapshotSerialization()
{
    var controller = new TestController();

    var actionResult = await controller.ReturnStubResult();

    var okObjectResult = actionResult.Should().BeOfType&lt;OkObjectResult&gt;().Which;

    await Verifier.Verify(okObjectResult.Value);
}
</code></pre>
<pre><code>returned JSON:

{
  Property1: value1,
  Property2: 5,
  Property3: {
    ChildProperty1: [],
    ChildProperty2: []
  }
}
</code></pre>
",https://stackoverflow.com/questions/75147268/net-core-snapshot-unit-testing-verify-does-not-serialize-newtonsoft-json-jobj,"['.net-core', 'verify', 'snapshot-testing']",79,False,0,1
Integration testing and unit testing options for kubernetes deployment (via Openshift),"<p>I am currently deploying application (Ansible automation platform) on Openshift clusters using helm chart and operators. I would like to have worker nodes in Openshift to run as instance group in Ansible automation platform. For this set up is done. Including the deployment via gitlab CICD pipeline.</p>
<p>However, I would like to have unit test, intergration test and performance test for my deployment.
E.G</p>
<ul>
<li>whether Correct release and revision of helm chart is deployed</li>
<li>All resources on Openshift is up</li>
<li>Connectivity to controller</li>
<li>Connectivity to gitlab (scm)</li>
<li>Connectivity between execution nodes (might be with API call)</li>
<li>Running a test job template
(preferably including the test steps to be also included in the pipeline stage)</li>
</ul>
<p>Could you suggest testing options or tools to perform this testing?
Maybe with pros and cons</p>
<p>Thank you</p>
<hr />
<p>I first though about using Helm hook for checking connectivities between kubernetes resources.
Helm hook seems to provide post install options for the life cycle deployment stage.</p>
<p>I wonder whethere there are other options or this options might have cons.</p>
",https://stackoverflow.com/questions/75388057/integration-testing-and-unit-testing-options-for-kubernetes-deployment-via-open,"['kubernetes', 'testing', 'deployment', 'automated-tests', 'openshift']",30,False,0,0
Asynchronous Notifier initialization will cause error &quot;asynchronous gap&quot; in unit testing,"<p>Describe the bug
I have a StateNotifierProvider which is (cardOnboardingProvider), that holds CardTypesState. when I initialize this provider in the constructor function, I make an API call, and on &quot;.then( () =&gt; {})&quot; I set the state of that provider.
When I want to test it. There is another provider (onboardingProvider) and trigger this provider and make it initialize.
After running the test, it shows an error and says this
<code>===== asynchronous gap ===========================</code></p>
<p>And also :
<code>MissingStubError: 'getCardTypesList' No stub was found which matches the arguments of this method call: getCardTypesList('', {isMock: true})</code>
which is not an issue because I've removed the asynchronous API call from to provider and I saw this one resolved as well.</p>
<p>This works fine for me in the app. It's just the testing that shows an error.</p>
<p>To Reproduce</p>
<p>** Provider **</p>
<pre><code>@freezed
class CardTypesState with _$CardTypesState {
  const factory CardTypesState.idle() = _CardTypesIdle;

  const factory CardTypesState.showError() = _CardTypeShowError;

  const factory CardTypesState.loading() = _CardTypesLoading;

  const factory CardTypesState.showCardList({required List&lt;CardTypesModel&gt; cardList}) = _CardTypeShowCardList;
}

final cardOnboardingProvider = StateNotifierProvider&lt;CardOnboardingNotifier, CardTypesState&gt;((ref) {
  return CardOnboardingNotifier(ref: ref, filteringApiCalls: ref.watch(cardTypesListApiCallsProvider));
});

class CardOnboardingNotifier extends StateNotifier&lt;CardTypesState&gt; {
  Ref ref;
  final CardTypeListApiCalls filteringApiCalls;

  CardOnboardingNotifier({required this.ref, required this.filteringApiCalls}) : super(CardTypesState.loading()) {
    getListTypes();
  }

  void getListTypes() {
    state = CardTypesState.loading();
    filteringApiCalls.getCardTypesList().then((value) {
      state = CardTypesState.showCardList(cardList: value);
    });
  }
}

</code></pre>
<p>** Test file **</p>
<pre><code>Future&lt;List&lt;ListTypeResponse&gt;&gt; listTypesMockFromFile() {
  final listTypeResponse = File('sample/sample/sample/sample.json').readAsStringSync();
  final listTypeJson = json.decode(listTypeResponse);
  final List&lt;ListTypeResponse&gt; listTypes =
  listTypeJson.map&lt;ListTypeResponse&gt;((i) =&gt; ListTypeResponse.fromJson(i as Map&lt;String, dynamic&gt;)).toList();
  return Future.value(listTypes);
}

@GenerateMocks([FacadeStoreService, FacadeHttpRestClient])
void main() {
  group(&quot;Group test&quot;, () {
    final happyPath = ProviderContainer(
      overrides: [
        storeProvider.overrideWith((ref) =&gt; MockFacadeStoreService()),
        httpClientProvider.overrideWith((ref) =&gt; MockFacadeHttpRestClient()),
      ],
    );

    test(&quot;Initial value&quot;, () async {
      /// Check onboardingProvider state
      expect(happyPath.read(onboardingProvider), OnboardingState.showVehicleType(isNextAvailable: false));
      expect(happyPath.read(onboardingProvider.notifier).pageIndex, 0);

      // ATTENTION : the above provider(onboardingProvider) is triggering (cardOnboardingProvider) which is
      // The provider that makes the asynchronous API call.

      /// Check CardOnboardingProvider state
      final Future&lt;List&lt;ListTypeResponse&gt;&gt; futureListTypes = listTypesMockFromFile();
      when(happyPath.read(httpClientProvider).getCardTypesList(&quot;&quot;, {&quot;isMock&quot;: &quot;true&quot;})).thenAnswer((_) =&gt; futureListTypes);
      expect(happyPath.read(httpClientProvider).getCardTypesList(&quot;&quot;, {&quot;isMock&quot;: &quot;true&quot;}), same(futureListTypes));
    });
  });
}

</code></pre>
<p>Expected behavior
We need to make an API call and set the value on the initialization of the provider.
How come it can't just initiate the provider and then change the value after the asynchronous function?</p>
",https://stackoverflow.com/questions/76304224/asynchronous-notifier-initialization-will-cause-error-asynchronous-gap-in-unit,"['flutter', 'dart', 'unit-testing', 'riverpod', 'dart-test']",22,False,0,0
Cannot use SQLAlchemy Session() outside Flask application context for unit testing,"<p>This is my inside <code>flaskapp/__init__.py</code> for creating my Flask app, with it I can access Session inside any module in the package, by just importing Session from <code>flaskapp/db.py</code>:</p>
<pre class=""lang-py prettyprint-override""><code>import os
from flask import Flask

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)

    app.config.from_mapping(
        SECRET_KEY=b'some_secret_key',
        DEBUG=True,
        SQLALCHEMY_DATABASE_URI=f'sqlite:///{os.path.join(app.instance_path, &quot;flaskapp.sqlite&quot;)}',
    )

    if test_config is None:
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(test_config)

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    with app.app_context():
        from flaskapp.routes import home, auth

        from flaskapp.db import init_db
        init_db()

    return app
</code></pre>
<p>This is my <code>flaskapp/db.py</code>:</p>
<pre class=""lang-py prettyprint-override""><code>from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from flask import current_app

engine = create_engine(current_app.config['SQLALCHEMY_DATABASE_URI'], echo=True)
Session = sessionmaker(bind=engine)

def init_db():
    import flaskapp.models as models
    models.Base.metadata.create_all(engine)

def drop_db():
    import flaskapp.models as models
    models.Base.metadata.drop_all(engine)
</code></pre>
<p>With that, I can access the database in any other module, for example, <code>flaskapp/auth.py</code>:</p>
<pre class=""lang-py prettyprint-override""><code>from flask import flash, session
from sqlalchemy import select

from flaskapp.db import Session
from flaskapp.models import User

def log_user(username: str, password: str) -&gt; bool:
    with Session() as db_session:
        stmt1 = select(User).where(User.username == username)
        query_user = db_session.execute(stmt1).first()

        if not query_user:
            flash('Some error message')

        # Some password verifications and other things
        session['username'] = query_user[0].username
        flash('Successfully logged in')

        return True

</code></pre>
<p>Until that point, I don't have any problem, the problem comes when I try to do unit testing with <code>unittest</code>, I can't set the test environment and I don't know how can I use the <code>Session</code> object defined in <code>flaskapp/db.py</code> for testing in a separate database. Everything I've tried until now gets me an error, this is my <code>tests/__init__.py</code>:</p>
<pre class=""lang-py prettyprint-override""><code>import unittest

from flaskapp import create_app
from flaskapp.db import Session
from flaskapp.models import User

class BaseTestClass(unittest.TestCase):
    def setUp(self):
        self.app = create_app(test_config={
            'TESTING': True,
            'DEBUG': True,
            'APP_ENV': 'testing',
             # I pass the test database URI expecting the engine to use it
            'SQLALCHEMY_DATABASE_URI': 'sqlite:///testdb.sqlite',
        })
        self.client = self.app.test_client()

        # Context
        with self.app.app_context():
            self.populate_db()

    def tearDown(self):
        pass

    def populate_db(self):
        with Session() as db_session:
            db_session.add(User(
                username='Harry',
                email='harry@yahoo.es',
                password = 'Harry123.'
            ))

            db_session.commit()
</code></pre>
<p>When I try to use the Session object inside <code>populate_db()</code> I get this error:</p>
<pre class=""lang-bash prettyprint-override""><code>=====================================================================
ERROR: tests.test_auth (unittest.loader._FailedTest.tests.test_auth)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.test_auth
Traceback (most recent call last):
  File &quot;/usr/local/lib/python3.11/unittest/loader.py&quot;, line 407, in _find_test_path
    module = self._get_module_from_name(name)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File &quot;/usr/local/lib/python3.11/unittest/loader.py&quot;, line 350, in _get_module_from_name
    __import__(name)
  File &quot;/home/chus/usb/soft/proy/SAGC/tests/test_auth.py&quot;, line 1, in &lt;module&gt;
    from flaskapp.db import Session
  File &quot;/home/chus/usb/soft/proy/SAGC/flaskapp/db.py&quot;, line 5, in &lt;module&gt;
    engine = create_engine(current_app.config['SQLALCHEMY_DATABASE_URI'], echo=True)
                           ^^^^^^^^^^^^^^^^^^
  File &quot;/home/chus/usb/soft/proy/SAGC/venv/lib/python3.11/site-packages/werkzeug/local.py&quot;, line 316, in __get__
    obj = instance._get_current_object()  # type: ignore[misc]
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File &quot;/home/chus/usb/soft/proy/SAGC/venv/lib/python3.11/site-packages/werkzeug/local.py&quot;, line 513, in _get_current_object
    raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.


----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
</code></pre>
<p>Can someone help me out? I've tried everything to make the tests use the app context in order to populate the test database and make queries but it appears to be conflicting with it being created in <code>create_app()</code> or something.</p>
",https://stackoverflow.com/questions/75416281/cannot-use-sqlalchemy-session-outside-flask-application-context-for-unit-testi,"['python', 'sqlite', 'flask', 'sqlalchemy', 'python-unittest']",99,False,-1,1
Unit testing mocked repositories in a C# Unit of Work project?,"<p>Our project is a Swashbuckle.AspNetCore project setup using the CLEAN pattern.
The infrastructure layer is structured with the Unit of Work pattern.</p>
<p>I'm trying to create a unit test repository using MSTest and Moq4. Now my
question is how do I Unit test the Service properly? The dependency injection is
too complicated for me. What I dont understand is how to instantiate a Service object in
the unit test function with a UnitOfWork object that has a mocked
ApplicationDbContext.</p>
<p>As far as I can tell the GenericRepository, context and UnitOfWork are not tightly coupled
(as recommended in <a href=""https://stackoverflow.com/questions/21847306/how-to-mock-repository-unit-of-work"">21847306/how-to-mock-repository-unit-of-work</a>).</p>
<p>The code I'm working with looks like the following:</p>
<pre class=""lang-cs prettyprint-override""><code>public interface IGenericRepository&lt;T&gt; where T : class
{
    IQueryable&lt;T&gt; All();
    void Delete(T entity);
    //.. Other functions
}

public class GenericRepository&lt;T&gt; : IGenericRepository&lt;T&gt; where T : class
{
    protected readonly ApplicationDBContext _context;
    protected readonly IConfiguration _configuration;
    protected DbSet&lt;T&gt; dbSet;

    public GenericRepository(ApplicationDBContext context, IConfiguration configuration)
    {
        _context = context;
        _configuration = configuration;
        this.dbSet = _context.Set&lt;T&gt;();
    }

    public IQueryable&lt;T&gt; All()
    {
        return _context.Set&lt;T&gt;().AsQueryable().AsNoTracking();
    }

    public void Delete(T entity)
    {
        _context.Set&lt;T&gt;().Remove(entity);
    }

    //.. Other functions
}

public interface ISomeRepository : IGenericRepository&lt;Some&gt;
{
    public Task&lt;bool&gt; AddSomeWithCustomLogicAsync(Some some);
    public Task&lt;bool&gt; DeleteSomeWithCustomLogicAsync(int someId);
}

class SomeRepository : GenericRepository&lt;Some&gt;, ISomeRepository
{
    public SomeRepository(ApplicationDBContext dbContext, IConfiguration configuration) : base(dbContext, configuration)
    {
    }

    public async Task&lt;bool&gt; AddSomeWithCustomLogicAsync(Some some)
    {
        // Add logic..
    }

    public async Task&lt;bool&gt; DeleteSomeWithCustomLogicAsync(int someId)
    {
        // Delete logic..
    }
}
</code></pre>
<pre class=""lang-cs prettyprint-override""><code>public interface IUnitOfWork : IDisposable
{
    public ISomeRepository SomeRepository { get; }
    public IAnotherRepository AnotherRepository { get; }

    int SaveChanges();
}

public class UnitOfWork : IUnitOfWork
{
    private readonly ApplicationDBContext _dBContext;
    private readonly IConfiguration _configuration;
    private readonly ILogger _logger;

    private ISomeRepository _someRepository;
    private IAnotherRepository _anotherRepositoty;

    public UnitOfWork(ApplicationDBContext applicationDBContext, ILoggerFactory loggerFactory, IConfiguration configuration)
    {
        _dBContext = applicationDBContext;
        _configuration = configuration;
        _logger = loggerFactory.CreateLogger(&quot;logs&quot;);
    }

    public ISomeRepository SomeRepository
    {
        get
        {
            _someRepository ??= new SomeRepository(_dBContext, _configuration);
            return _someRepository;
        }
    }

    public int SaveChanges()
    {
        return _dBContext.SaveChanges();
    }
}
</code></pre>
<pre class=""lang-cs prettyprint-override""><code>public abstract class GenericService&lt;T&gt; : IGenericService&lt;T&gt; where T : class
{
    public IUnitOfWork _unitOfWork;

    protected readonly IMapper _mapper;
    protected readonly IValidateService _validateService;
    protected readonly ISignalService _signalService;
    protected readonly ILogBoekService _logBoekService;
    protected readonly IHttpContextAccessor _context;
    private readonly IUriService _uriService;

    public GenericService(IUnitOfWork unitOfWork, IMapper mapper, IValidateService validateService, ISignalService signalService,
                          ILogBoekService logBoekService, IHttpContextAccessor context, IUriService uriService)
    {
        _unitOfWork = unitOfWork;
        _mapper = mapper;
        _validateService = validateService;
        _signalService = signalService;
        _logBoekService = logBoekService;
        _context = context;
        _uriService = uriService;
    }
}

public interface ISomeService : IGenericService&lt;Some&gt;
{
    public Task&lt;bool&gt; DoWork();
}

public class SomeService : GenericService&lt;Some&gt;, ISomeService
{
    public SomeService(IUnitOfWork unitOfWork, IMapper mapper, IValidateService validateService,
                       ISignalService signalService, ILogBoekService logBoekService, IHttpContextAccessor context,
                       IUriService uriService)
        : base(unitOfWork, mapper, validateService, signalService, logBoekService, context, uriService)
    {
    }

    // This is the function I want to test
    public async Task&lt;bool&gt; DoWork()
    {
        return await _unitOfWork.SomeRepository.All() == 0;
    }
}
</code></pre>
<pre class=""lang-cs prettyprint-override""><code>[TestClass]
public class SomeUnitTest
{
    private SomeService _someService;

    public void GenerateService(IQueryable&lt;Some&gt; documenten)
    {
        var mockDbSet = new Mock&lt;DbSet&lt;Some&gt;&gt;();
        mockDbSet.As&lt;IQueryable&lt;Some&gt;&gt;().Setup(x =&gt; x.Provider).Returns(documenten.Provider);
        mockDbSet.As&lt;IQueryable&lt;Some&gt;&gt;().Setup(x =&gt; x.Expression).Returns(documenten.Expression);
        mockDbSet.As&lt;IQueryable&lt;Some&gt;&gt;().Setup(x =&gt; x.ElementType).Returns(documenten.ElementType);
        mockDbSet.As&lt;IQueryable&lt;Some&gt;&gt;().Setup(x =&gt; x.GetEnumerator()).Returns(documenten.GetEnumerator());

        var mockContext = new Mock&lt;ApplicationDBContext&gt;();
        mockContext.Setup(x =&gt; x.Some).Returns(mockDbSet.Object);

        // This seems like an inefficient way of doing it, how can it be improved?
        var unitOfWork = new UnitOfWork(mockContext.Object, null, null);
        _someService = new SomeService(unitOfWork, null, null, null, null, null, null);
    }

    [TestMethod]
    public async Task GetPaginatedSomeAsyncTest()
    {
        // Prepare data

        var someThings = new List&lt;Some&gt; {
            new Some { Id = 1, Name = &quot;Some 1&quot; },
            new Some { Id = 2, Name = &quot;Some 2&quot; },
            new Some { Id = 3, Name = &quot;Some 3&quot; }
        }.AsQueryable();

        GenerateService(someThings);

        // Test

        var retrievedDocumenten = await _someService.DoWork();

        Assert.AreEqual(0, retrievedDocumenten.Data.Count);

        return;
    }

    [TestMethod]
    public void GetSomeAsyncTest()
    {
        Assert.Fail();
    }
}
</code></pre>
<p>I did not succeed at creating a mocked UnitOfWork object properly, I dont know how to reproduce the dependency injection that occurs automatically in the unit test.</p>
",https://stackoverflow.com/questions/75547368/unit-testing-mocked-repositories-in-a-c-unit-of-work-project,"['c#', 'mstest']",92,True,0,1
@aws-sdk/client-cloudwatch-logs Angular v15 and Jest Unit testing,"<p>I have been try to wrap my brain around Unit testing with Jest and Angular 15 (using @briebug/jest-schematic to make my live easier)</p>
<p>// jest.config</p>
<pre><code>`module.exports = {
  maxWorkers: '50%',
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['&lt;rootDir&gt;/src/setup-jest.ts'],
  globalSetup: 'jest-preset-angular/global-setup',
  verbose: true,
  collectCoverage: true,
  notify: true,
  moduleNameMapper: {
    '@core/(.*)': ['&lt;rootDir&gt;/src/app/core/$1'],
    '@shared/(.*)': ['&lt;rootDir&gt;/src/app/shared/$1'],
    '@assets/(.*)': ['&lt;rootDir&gt;/src/assets/$1'],
    '@env/(.*)': ['&lt;rootDir&gt;/src/environments/$1']
  }
};`
</code></pre>
<p>// setup-jest</p>
<pre><code>`import 'zone.js';
import 'zone.js/testing';
import { TestBed } from &quot;@angular/core/testing&quot;;
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from &quot;@angular/platform-              browser-dynamic/testing&quot;;
</code></pre>
<p>TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());`</p>
<blockquote>
<p>Test suite failed to run</p>
<p>Jest encountered an unexpected token</p>
<p>Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.</p>
<p>Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.</p>
<p>By default &quot;node_modules&quot; folder is ignored by transformers.</p>
<p>Here's what you can do:
If you are trying to use ECMAScript Modules, see <a href=""https://jestjs.io/docs/ecmascript-modules"" rel=""nofollow noreferrer"">https://jestjs.io/docs/ecmascript-modules</a> for how to enable it.
If you are trying to use TypeScript, see <a href=""https://jestjs.io/docs/getting-started#using-typescript"" rel=""nofollow noreferrer"">https://jestjs.io/docs/getting-started#using-typescript</a>
To have some of your &quot;node_modules&quot; files transformed, you can specify a custom &quot;transformIgnorePatterns&quot; in your config.
If you need a custom transformation specify a &quot;transform&quot; option in your config.
If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the &quot;moduleNameMapper&quot; config option.</p>
<p>You'll find more details and examples of these config options in the docs:
<a href=""https://jestjs.io/docs/configuration"" rel=""nofollow noreferrer"">https://jestjs.io/docs/configuration</a>
For information about custom transformations, see:
<a href=""https://jestjs.io/docs/code-transformation"" rel=""nofollow noreferrer"">https://jestjs.io/docs/code-transformation</a></p>
<p>Details:</p>
<p>C:\Users\Robert Leeuwerink\Documents\GitHub\P-VR_BackEnd\AwsOnlineServices\BE-Tools\CQLTool\Web\node_modules\uuid\dist\esm-browser\index.js:1
({&quot;Object.&quot;:function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';</p>
</blockquote>
<p>so I managed to get most working but @aws-sdk seems to be a bit of a blocker for me. I have been reading a bit about moduleNameMapper/transforms and ignorePatterns but they do not seem to help me move forward.</p>
<p>Tried the suggestions in here: (which results in everything failing)
<a href=""https://github.com/nrwl/nx/issues/812"" rel=""nofollow noreferrer"">https://github.com/nrwl/nx/issues/812</a></p>
<p>Basic results at the moment
<em>Test Suites: 3 failed, 10 passed, 13 total
Tests:       17 passed, 17 total
Snapshots:   0 total
Time:        9.585 s
Ran all test suites.</em></p>
<p>I'm trying to resolve the 3 test suites which rely on @aws-sdk/client-cloudwatch-logs</p>
",https://stackoverflow.com/questions/75690321/aws-sdk-client-cloudwatch-logs-angular-v15-and-jest-unit-testing,"['angular', 'jestjs', 'amazon-cloudwatchlogs', 'aws-sdk-js']",75,False,0,0
Angular&#39;s unit testing for server sent events with just Karma-Jasmine,"<p>I am using Angular for frontend and Python for backend. I am using server sent events (SSE) to stream data from server to UI. Everything is working fine, but I am unable to write unit tests for the same in angular.</p>
<p><strong>abc.component.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>streamMessages() {
  this.isPaused = false;
  this.messages = [];

  const url = this.urlConfig.stream;

  var eventSource = new EventSource(url);

  eventSource.addEventListener('message', (e) =&gt; {
    this.messages.push(e.data);
  });

  eventSource.addEventListener('error', (e) =&gt; {
    eventSource.close();

    console.log('ERROR!');

    this.isPaused = true;
  });

  eventSource.addEventListener('close', () =&gt; {
    eventSource.close();

    console.log('CLOSED!');
  });
}
</code></pre>
<p><strong>abc.component.spec.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>describe('#streamMessages', () =&gt; {
  let mockEventSource: jasmine.SpyObj&lt;EventSource&gt;;

  beforeEach(() =&gt; {
    mockEventSource = jasmine.createSpyObj('EventSource', ['addEventListener']);
  });

  it('should push new message when new message is received', () =&gt; {

    mockEventSource.addEventListener.and.callFake((type: string, event: any) =&gt; {
      console.log(type, event)
    });

    component.streamMessages();

    expect(component.messages.length).toBeGreaterThan(0);
  });
});

</code></pre>
<p>I need to write unit tests for all the three scenarios.</p>
<p>Any leads would be a great help. Thanks in advance!</p>
<hr />
<p>P.S: I don't want to use test bed. I need to accomplish this just with the help of Karma-Jasmine.</p>
",https://stackoverflow.com/questions/75542530/angulars-unit-testing-for-server-sent-events-with-just-karma-jasmine,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-jasmine']",177,True,0,1
Unit Testing Object Box for Flutter App in macOS is failing,"<p>While reading from object box for doing unit testing for flutter app in mac, it is giving error like</p>
<p><code>RangeError (byteOffset): Invalid value: Valid value range is empty: 0</code></p>
<p>It is coming for any call of <code>query.find()</code>. Object box version is 1.6.2</p>
<p>How to get around this ?</p>
<p>Edit code for reproducibility</p>
<pre><code>final query = _box.query(any query).build(); 
final data = query.find(); 
query.close(); 
return data;
</code></pre>
",https://stackoverflow.com/questions/76236329/unit-testing-object-box-for-flutter-app-in-macos-is-failing,"['flutter', 'flutter-objectbox']",20,False,0,0
how can i do a unit testing of axios.create mock with vitest?,"<p>i am learning unit testing in vue with typescript and i want to test this function</p>
<pre><code>const getCLients =async (): Promise&lt;Client[]&gt; =&gt; {
        const {data} = await clientsApi.get('/clients')
        return data
}
</code></pre>
<p>But i got an error due to the clientsApi. My clients api is aun axios instance and looks like this:</p>
<pre><code>import axios from 'axios'

const clientsApi = axios.create({
   baseURL:import.meta.env.VITE_API_URL
})
export default clientsApi
</code></pre>
<p>my error is this:</p>
<blockquote>
<p>TypeError: Cannot read properties of undefined (reading 'get')
❯ getCLients ../src/clients/composables/useClients.ts:14:41</p>
</blockquote>
<blockquote>
<p>14|         const {data} = await clientsApi.get('/clients')</p>
</blockquote>
<p>In my tests i have done the axios mock:</p>
<pre><code>vi.mock('axios')
const mockedAxios = axios as jest.Mocked&lt;typeof axios&gt;;

mockedAxios.get.mockResolvedValue({
            data: mockClients,
})
</code></pre>
<p>I suposed that i had to make a mock of the axios.create but i have tried with a lot of ways but i always got the same typoe error. I need your help, how could you solve this?</p>
",https://stackoverflow.com/questions/75093486/how-can-i-do-a-unit-testing-of-axios-create-mock-with-vitest,"['typescript', 'axios', 'vuejs3', 'vitest', 'axios-mock-adapter']",1319,True,3,1
How do I assert on an error message in Ruby unit testing?,"<p>In a Ruby on Rails project, I want to assert on the exception message in my code to make sure it fails for the right reason and mentions important details.</p>
<p>Here is a function that always raises:</p>
<pre class=""lang-rb prettyprint-override""><code>class Quiz &lt; ApplicationRecord
  def self.oops
    raise ArgumentError.new(&quot;go away&quot;)
  end
end
</code></pre>
<p>The test:</p>
<pre class=""lang-rb prettyprint-override""><code>require &quot;test_helper&quot;

class QuizTest &lt; ActiveSupport::TestCase
  test &quot;error message&quot; do
    assert_raises(ArgumentError, match: /whatever/) do
      Quiz.oops()
    end
  end
end
</code></pre>
<p>When I run <code>bin/rake test</code>, this passes, but I expected it to fail cause the actual error message doesn't match the <code>match</code> in <code>assert_raises</code>.</p>
<p>How can I capture the error message and assert against it?</p>
",https://stackoverflow.com/questions/76213604/how-do-i-assert-on-an-error-message-in-ruby-unit-testing,"['ruby-on-rails', 'ruby', 'unit-testing']",35,True,2,1
Swift UI Search app view model return nil error on unit testing,"<p>I am trying to test the search function. When I enter the text App, it should return 3 records, but instead it returns nil and showing error <strong>testSearcFruit_success_WithLatter_A(): XCTAssertEqual failed: (&quot;0&quot;) is not equal to (&quot;3&quot;) - Total is empty</strong> I thought there might be problems with using debounce and delay and I added the delay but still it showing the same error.</p>
<p>I tried the following code to make the delay … but still some problems.</p>
<pre><code> DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            let resultCount = self.viewModel.filterFruits(text: &quot;App&quot;, fruit: self.filteredFruit)
            XCTAssertEqual(resultCount.count ,3, &quot;Total is empty&quot;)
            expectation.fulfill()
        }
</code></pre>
<p>My view model code:</p>
<pre><code>final class FruitListViewModel: FruitListViewModelType, ObservableObject {
    
    private let service: Service
    @Published private(set) var fruits = [Fruits]()
    @Published var filteredFruit: [Fruits] = []
    @Published var searchText: String = &quot;&quot;
    private var cancellable = Set&lt;AnyCancellable&gt;()

    init(service:Service = ServiceImpl()) {
        self.service = service
        fetchFruit()
    }
    
    func fetchFruit() {
        let client = ServiceClient(baseUrl:EndPoints.baseUrl.rawValue, path:Path.fruitList.rawValue, params:&quot;&quot;, method:&quot;get&quot;)
        
        service.fetchData(client: client, type: [Fruits].self)
            .receive(on: RunLoop.main)
            .sink { completion in
                switch completion {
                case let .failure(error):
                    print(error)
                default:
                    break
                }
            } receiveValue: { response in
                self.fruits = response
            }.store(in: &amp;cancellable)
        
        $searchText
            .combineLatest($fruits)
            .debounce(for: .seconds(0.5), scheduler: RunLoop.main)
            .map(filterFruits)
            .sink { [weak self] (filterList) in
                self?.filteredFruit = filterList
            }
            .store(in: &amp;cancellable)
    }
    public func filterFruits(text: String, fruit: [Fruits]) -&gt; [Fruits] {

        guard !searchText.isEmpty else {
            return fruit
        }
        let lowercasedText = searchText.lowercased()
        let filterFruitList = fruit.filter { (fruit) -&gt; Bool in
            fruit.name.lowercased().contains(lowercasedText) ||
            fruit.genus.lowercased().contains(lowercasedText) ||
            fruit.family.lowercased().contains(lowercasedText)
        }
        return filterFruitList
    }
}
</code></pre>
<p>The mock service code:</p>
<pre><code>class MockService: Service {
    
    var responseFileName = &quot;&quot;
    
    func fetchData&lt;T&gt;(client: FruitsDemoSwiftUI.ServiceClient, type: T.Type) -&gt; AnyPublisher&lt;T,ServiceError&gt; where T : Decodable, T : Encodable {
        
        let bundle = Bundle(for: MockService.self)
        guard let url = bundle.url(forResource: responseFileName, withExtension:&quot;json&quot;),
              let data = try? Data(contentsOf: url) else {
            return Fail(outputType: type, failure: ServiceError.requestNotCreated(message: Constants.requestNotCreated)).eraseToAnyPublisher()
        }
        do {
            let decodeObject = try JSONDecoder().decode(T.self, from: data)
            return Just(decodeObject)
                .setFailureType(to: ServiceError.self)
                .eraseToAnyPublisher()
        } catch {
            return Fail(outputType: type, failure: ServiceError.requestNotCreated(message: Constants.requestNotCreated))
                .eraseToAnyPublisher()
        }

    }
}
</code></pre>
<p>My testing code :</p>
<pre><code>import XCTest
@testable import FruitsDemoSwiftUI

final class FruitsDemoSwiftUISearchTests: XCTestCase {
    var mockService: MockService!
    var viewModel: FruitListViewModel!
     var filteredFruit: [Fruits] = []

    override func setUp() {
        mockService = MockService()
        viewModel = FruitListViewModel(service: mockService)
    }

    override func tearDownWithError() throws {
        viewModel = nil
    }
    
    func testSearcFruit_success_WithLatter_A() {
        let expectation = expectation(description: &quot;Wait for async code to complete&quot;)
        mockService.responseFileName = &quot;FruitSuccessResponse&quot;
        viewModel.fetchFruit()
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            let resultCount = self.viewModel.filterFruits(text: &quot;App&quot;, fruit: self.filteredFruit)
            XCTAssertEqual(resultCount.count ,3, &quot;Total is empty&quot;)
            expectation.fulfill()
        }
        wait(for: [expectation], timeout: 2.0)
    }
}
</code></pre>
<p>The result on debug mode:</p>
<p><a href=""https://i.stack.imgur.com/9Tbzz.png"" rel=""nofollow noreferrer"">debug result</a></p>
<p>Here is the screenshot of the error ..</p>
<p><a href=""https://i.stack.imgur.com/NeY6V.png"" rel=""nofollow noreferrer"">error</a></p>
",https://stackoverflow.com/questions/76039070/swift-ui-search-app-view-model-return-nil-error-on-unit-testing,"['swift', 'unit-testing', 'combine', 'debouncing', 'combinelatest']",80,False,1,0
How can I do unit testing for my Spring Boot service classes?,"<p>i need to do some Unit Testing for my Service Classes im using Springboot and this is my code. The Problem is that i have more then one question im abit under presure because i have to present my solution tuesday. So i hope anyone can help me..</p>
<ol>
<li>As far as i understood the Controller class takes the HTTP request and calls then the Service Class methods which handels the logic. In my code i dont understand how i can call the add function because there is not much logic there for its just copy pasted....</li>
<li>I need to do Unit teting for my Service classes and i absolutly dont understand how Testing works. Iam a beginner so understanding the Youtube tutorials are quit hard for me.</li>
</ol>
<p>If anyone could help i would be very Thankful. Maybe anyone has abit time over and could give me a litil course (1houre) via discord ?</p>
<p>And lastly im sory for my bad english if you didnt udnerstund evrything or need more information pls let me know.</p>
<pre><code>

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import de.lhind.digicard.dto.CardDTO;
import de.lhind.digicard.entity.Card;
import de.lhind.digicard.repository.CardRepository;
import de.lhind.digicard.service.CardService;


@RestController  
public class CardController {
    // Variablen deklaration
    private final CardRepository cardRepository;
    private final CardService cardService; 

    //Contruktor erstellt damit services richtig aufgerufen werden
    public CardController (CardRepository cardRepository, CardService cardService){
                                this.cardRepository= cardRepository;
                                this.cardService=cardService;
                            }
    // create endpoint  
    @GetMapping(&quot;/allcard&quot;)  
    // when Card hit the endpoint, it returns the response body  
    @ResponseBody  
    public List&lt;CardDTO&gt; getAllCard() {  
        // call getAllCard() method from the service which we created before  
        // store the result in a list of UserLocationDTO  
        List &lt;CardDTO&gt; card = cardService.getAllCard();  
        // return usersLocation  
        return card;  
    }  

    @PostMapping(path = &quot;/addcard&quot;)
    public String addNewCard(@RequestBody Card card) {
        cardRepository.save(card);
         return &quot;Saved&quot;;
    }

}  





import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import de.lhind.digicard.dto.CardDTO;
import de.lhind.digicard.entity.Card;
import de.lhind.digicard.repository.CardRepository;
import de.lhind.digicard.service.CardService;


@RestController  
public class CardController {
    // Variablen deklaration
    private final CardRepository cardRepository;
    private final CardService cardService; 

    //Contruktor erstellt damit services richtig aufgerufen werden
    public CardController (CardRepository cardRepository, CardService cardService){
                                this.cardRepository= cardRepository;
                                this.cardService=cardService;
                            }
    // create endpoint  
    @GetMapping(&quot;/allcard&quot;)  
    // when Card hit the endpoint, it returns the response body  
    @ResponseBody  
    public List&lt;CardDTO&gt; getAllCard() {  
        // call getAllCard() method from the service which we created before  
        // store the result in a list of UserLocationDTO  
        List &lt;CardDTO&gt; card = cardService.getAllCard();  
        // return usersLocation  
        return card;  
    }  

    @PostMapping(path = &quot;/addcard&quot;)
    public String addNewCard(@RequestBody Card card) {
        cardRepository.save(card);
         return &quot;Saved&quot;;
    }

}  
</code></pre>
",https://stackoverflow.com/questions/76330187/how-can-i-do-unit-testing-for-my-spring-boot-service-classes,"['spring-boot', 'unit-testing']",14,False,1,0
Unit testing a compnent that is getting data from Angular Replay Subject,"<p>I have this service called EmployeeService where I am using Angular's ReplaySubject to get data from an api. I'm subcribing to this ReplaySubject from another component which I am trying to test now. But because I'm unable to mock the data from the service mentioned above, the unit test is not working.</p>
<p>This is a bare bones of the EmployeeService:</p>
<pre><code>class EmployeeService extends ApiService {

  public currentEmployeeSub: ReplaySubject&lt;EmployeeModel&gt; = new ReplaySubject&lt;EmployeeModel&gt;(1);
  private currentEmployee: EmployeeModel;
  private uuid: UuidService;

  constructor(
    auth: AuthService,
    http: HttpClient,
    uuid: UuidService
  ) {
    super('employees', auth, http);
    this.uuid = uuid;
  }

  // other methods
}
</code></pre>
<p>This is a utilService which is also being used to parse the data:</p>
<pre><code>class UtilService {
  parse(object: any) {
    return JSON.parse(JSON.stringify(object));
  }
}
</code></pre>
<p>Now this is the component I'm trying to test. Please note that this is a huge component but I'm just showing the most important part which is needed for this component to work and that is the employee data coming from EmployeeService.</p>
<pre><code>class SalaryComponent implements OnInit, OnDestroy, AfterViewInit {

  private utilService: UtilService;
  private employeeService: EmployeeService;

  employee: EmployeeModel;
  employeeSubscription: Subscription;

  constructor(utilService: UtilService, employeeService: EmployeeService
  ) {
    this.utilService = utilService;
    this.employeeService = employeeService;

    this.employeeSubscription = this.employeeService.currentEmployeeSub.subscribe((employee: EmployeeModel) =&gt; {
      this.employee = this.utilService.parse(employee);
    });
}
</code></pre>
<p>The above component is subscribing to ReplaySubject in EmployeeService, gets the data of the employee and sets <code>this.employee</code> after parsing the data. I just need to set the data for <code>this.employee</code> in the test spec so that I can unit test a component which relies on this data like this:</p>
<pre><code>&lt;div class=&quot;cb-col-12&quot;&gt;
   &lt;dropdown
      *ngIf=&quot;employee&quot;
      name=&quot;employee&quot;
      formControlName=&quot;employee&quot;
      (handlerSelect)=&quot;onEmployeeChange($event)&quot;
      [options]=&quot;employeeOptions&quot;
   &gt;
   &lt;/dropdown&gt;
&lt;/div&gt;
</code></pre>
<p>This is how the test spec look like:</p>
<pre><code>describe('SalaryComponent', () =&gt; {
  let component: SalaryComponent;
  let fixture: ComponentFixture&lt;SalaryComponent&gt;;

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [],
      declarations: [],
      providers: [],
    })
      .compileComponents();
  });

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(SalaryComponent);
    component = fixture.componentInstance;
  });

  fit('should show drop down if there is employee data', async ()  =&gt; {
    fixture.detectChanges();
    await fixture.whenStable();
  
    component.employee = {
      name: 'John Doe',
      age: 23,
      qualifications: [],
      address: {},
    }

    fixture.detectChanges();
    await fixture.whenStable();

    const hostElement: HTMLElement = fixture.nativeElement;
    const dropDown: HTMLInputElement = hostElement.querySelector(
      'dropdown[name=&quot;employee&quot;]'
    );

    expect(dropDown).toBeTruthy();
  } 
}
</code></pre>
<p>I am getting <code>null</code> for the dropdown element even when there is employee data set in the component.</p>
<p>How can I mock ReplaySubject to set employee data in the component so that it takes effect?</p>
",https://stackoverflow.com/questions/76053868/unit-testing-a-compnent-that-is-getting-data-from-angular-replay-subject,"['angular', 'unit-testing', 'testing', 'rxjs', 'jasmine']",59,True,1,1
How to mock JobExecution.builder() using mockito and mock DynamoDBMapper for unit testing?,"<p>I want to test below method using mockito. jobExecution object is saved in DynamoDB. Please refer the code below.</p>
<pre><code>private void saveOrUpdateToDynamoDb(final JobExecution existingJobExecution) {
final JobExecution jobExecution = JobExecution.builder().jobMasterId(&quot;12&quot;).jobType(&quot;lamda&quot;)
                    .jobAction(&quot;Entry message load into MC&quot;).status(&quot;running&quot;).startDate(startTime).referenceId(&quot;225&quot;)
                        .payload(messageBody).ttlExpiry(5259600+Instant.now().getEpochSecond()).build();
saveOrUpdateToDynamoDb(jobExecution);
}

private void saveOrUpdateToDynamoDb(final JobExecution existingJobExecution) {
    dbMapper.save(existingJobExecution,
                    new TableNameOverride(String.format(STRING_CONCAT, CAPABILITY_CODE, envName, TABLE_NAME)).config());
}
</code></pre>
",https://stackoverflow.com/questions/75593139/how-to-mock-jobexecution-builder-using-mockito-and-mock-dynamodbmapper-for-uni,"['java', 'unit-testing', 'amazon-dynamodb', 'mockito']",57,False,0,1
How to unit testing for json file is loaded in django views.py,"<p>I want to unit testing for json file is opened in <code>views.py</code> in django</p>
<pre><code>def get_json_data():
    json_data = json.load(open(JSON_DIRECTORY+'my.json'))
    return json_data
</code></pre>
<p>Please help me how to unit testing for <code>json</code> file is loaded or not</p>
<pre><code>def test_read_file_data(self):

    def read_file_data(filename, path):
        os.chdir(path)
        with open(filename,  encoding=&quot;utf8&quot;) as data_file:
            json_data = json.load(data_file)
        return json_data

    sample_json = {

    }
    sample_json = json.dumps(sample_json, ensure_ascii=False)
    path = my file path
    filename = real file
    self.assertEqual(read_file_data(filename, path), sample_json)
</code></pre>
<p>In <code>json</code> there is <code>null</code> as well so I do not know how to deal with the <code>null</code></p>
",https://stackoverflow.com/questions/75808038/how-to-unit-testing-for-json-file-is-loaded-in-django-views-py,"['python', 'django', 'unit-testing']",44,False,0,1
Type &#39;string&#39; is not assignable to type &#39;Date nest js unit testing,"<p>I created a sample project with CRUD using NestJs. I create a User with a randomly generated <code>Id</code>, <code>name</code>, <code>birthdate</code> and <code>email</code>. I need to do unit testing for this create CRUD operation. But I do not know how to test the birthDate. It gives me an error.</p>
<p><a href=""https://i.stack.imgur.com/JPHWr.png"" rel=""nofollow noreferrer"">This is what I got when I tried to pass the date </a></p>
<p><strong>User Entity:</strong></p>
<pre class=""lang-js prettyprint-override""><code>import {
  Column,
  CreateDateColumn,
  Entity,
  PrimaryGeneratedColumn,
} from 'typeorm';

@Entity('users')
export class User {
  //auto increment
  @PrimaryGeneratedColumn('increment')
  id: number;

  @Column({ nullable: true, default: null })
  name: string;

  @CreateDateColumn({ nullable: true })
  birthDate: Date;

  @Column({ type: 'varchar' })
  email: string;
}
</code></pre>
",https://stackoverflow.com/questions/74994452/type-string-is-not-assignable-to-type-date-nest-js-unit-testing,"['unit-testing', 'date', 'nestjs', 'crud']",310,True,0,1
Replacing standard library functions with custom higher order functions for unit testing,"<p>I'm working on increasing unit test coverage for my repository, covering to maximum extent possible. I have a particular routine in the package, that makes <code>ssh</code> and <code>sftp</code> connections. I'm trying to replace them with higher order functions (see <a href=""https://eli.thegreenplace.net/2023/higher-order-functions-in-go/"" rel=""nofollow noreferrer"">Higher-order functions in Go</a> for reference) for the purposes of unit testing.</p>
<p>One such example set I have is below</p>
<pre class=""lang-golang prettyprint-override""><code>type (
    // ssh.Dial prototype
    sshDialer     func(string, string, *ssh.ClientConfig) (*ssh.Client, error)
    // sftp.NewClient prototype
    sftpNewClient func(conn *ssh.Client, opts ...sftp.ClientOption) (*sftp.Client, error)
)
</code></pre>
<p>which I'm trying to convert to</p>
<pre class=""lang-golang prettyprint-override""><code>type (
    // ssh.Dial prototype - Updated
    sshDialer     func(string, string, *ssh.ClientConfig) (SSHConnector, error)
    // sftp.NewClient prototype - updated
    sftpNewClient func(conn *ssh.Client, opts ...sftp.ClientOption) (SFTPConnector, error)
)
</code></pre>
<p>where <code>SSHConnector</code> and <code>SFTPConnector</code> are the custom interfaces satisfied by the native types respectively (see below playground link for full code)</p>
<p>Here is a full example (reproducible) of the code I’m dealing with in a Go snippet - <a href=""https://go.dev/play/p/DZ3H9FRlbGI"" rel=""nofollow noreferrer"">https://go.dev/play/p/DZ3H9FRlbGI</a></p>
<p>The problem is I'm not able to make <code>ssh.Dial()</code> or <code>sftp.NewClient()</code> accept interface as their first arguments.</p>
<p>Seeing errors as below, which is meaningful, but just interested in finding a way to make it work</p>
<pre class=""lang-none prettyprint-override""><code>./prog.go:48:18: cannot use ssh.Dial (value of type func(network string, addr string, config *ssh.ClientConfig) (*ssh.Client, error)) as sshDialer value in struct literal
./prog.go:49:18: cannot use sftp.NewClient (value of type func(conn *ssh.Client, opts ...sftp.ClientOption) (*sftp.Client, error)) as sftpNewClient value in struct literal
</code></pre>
<p>I'm seeing errors as follows, which makes sense, but just interested in finding a way for it to work</p>
<p>I know mocking/patching methods are not recommended in Go’s overall testing strategy, but would like to make this from a learning/practice experiment.</p>
<p>Basically I’m trying to modify the prototype of <code>sshDialer</code> and <code>sftpNewClient</code>, to return an interface as the first return value, so that I can create a mock struct (using <code>gomock</code> or <code>testify/mock</code>) to further test my code. Is that achievable. Also would appreciate other approaches based on my code structure.</p>
",https://stackoverflow.com/questions/75901177/replacing-standard-library-functions-with-custom-higher-order-functions-for-unit,['go'],75,False,0,0
Multiple sets of input data for Microsoft Unit Testing Framework for C++,"<p>Using Visual Studio 2019. The <code>MSTest</code> unit testing framework for C# has the <code>DataRow</code> attribute which allows test methods to be automatically called with multiple sets of constant input data. For example:</p>
<pre><code>[TestMethod]
[DataRow(11.99, 4.55)] // One or more sets of constant input test data
[DataRow(50.00, 40.00)]
public void Debit_WithValidAmount_UpdatesBalance_WithConstantData(double balance, double debit)
{
    // ...method called twice with {11.99, 4.55} and {50.00, 40.00}
}
</code></pre>
<p>Is it possible to have multiple sets of constant test input data with Microsoft's <code>Native Unit Test</code> framework, also called the <code>Microsoft Unit Testing Framework for C++</code>?</p>
<p><code>MSTest</code> also allows generator methods to create dynamic input data. For example:</p>
<pre><code>[TestMethod]
[DynamicData(nameof(MyTestData), DynamicDataSourceType.Method)]
public void Debit_WithValidAmount_UpdatesBalance_WithDynamicData(double balance, double debit)
{
    // ...method called twice with {12.99, 1.23} and {55.00, 45.00}
}

private static IEnumerable&lt;object[]&gt; MyTestData()
{
    // Generator method to create dynamic test data
    yield return new object[] { 12.99, 1.23  };
    yield return new object[] { 55.00, 45.00 };
}
</code></pre>
<p>Similar question, is it possible to use generator methods with Microsoft's <code>Native Unit Test</code> framework to create dynamic input data?</p>
",https://stackoverflow.com/questions/75448806/multiple-sets-of-input-data-for-microsoft-unit-testing-framework-for-c,"['c++', 'visual-studio', 'unit-testing', 'microsoft-unit-testing']",50,False,0,0
Why does unit testing an image field using SimpleUploadedFile create multiple images?,"<p>This is the tests.py</p>
<pre><code>class ArticleModelTestCase(TestCase):
    def setUp(self):
        self.article = Article.objects.create(
            title = 'Title test.',
            content = 'Content test.',
            date_posted = timezone.localtime(),
            image = SimpleUploadedFile(
                name = 'test_image.jpg',
                content = b'',
                content_type = 'image/jpeg'
            )
        )

    def test_title(self):
        self.assertEqual(self.article.title, 'Title test.')

    def test_content(self):
        self.assertEqual(self.article.content, 'Content test.')

    def test_image_field(self):
        self.assertEqual(self.article.image.name, 'test_image.jpg')
</code></pre>
<p>and I got this error</p>
<pre class=""lang-none prettyprint-override""><code>&gt; Creating test database for alias 'default'... System check identified
&gt; no issues (0 silenced). .F.
&gt; ====================================================================== FAIL: test_image_field (articles.tests.ArticleModelTestCase)
&gt; ---------------------------------------------------------------------- Traceback (most recent call last):   File
&gt; &quot;/home/xxx/projects/xxxx/backend/articles/tests.py&quot;,
&gt; line 27, in test_image_field
&gt;     self.assertEqual(self.article.image.name, 'test_image.jpg') AssertionError: 'article_images/test_image_7U9qlax.jpg' !=
&gt; 'test_image.jpg'
&gt; - article_images/test_image_7U9qlax.jpg
&gt; + test_image.jpg
&gt; 
&gt; 
&gt; ---------------------------------------------------------------------- Ran 3 tests in 0.004s
&gt; 
&gt; FAILED (failures=1) Destroying test database for alias 'default'...
</code></pre>
<p>What happens is that the <code>SimpleUploadedFile</code> not only created a 'test_image.jpg' but it created 3 files of:</p>
<ol>
<li>test_image.jpg</li>
<li>test_image_CWK5SDf.jpg</li>
<li>test_image_7U9qlax</li>
</ol>
<p>Every time I ran the test, it will always create 3 image files with random words and numbers as the suffix after 'test_image'.</p>
<p>What it should do is to just create 1 image file named 'test_image'.</p>
<p>Why does this happen and how to fix this?</p>
",https://stackoverflow.com/questions/75968202/why-does-unit-testing-an-image-field-using-simpleuploadedfile-create-multiple-im,"['python', 'django', 'unit-testing']",40,True,0,1
Can I do unit testing to code that uses TimeOfDay (package:flutter/material.dart)?,"<p>I'm new to Unit Testing.</p>
<p>I want to test some <strong>DateTime</strong> and <strong>TimeOfDay</strong> calculations, but it looks as if it's not possible to write unit tests that import <strong>package:flutter/material.dart</strong> (which is needed for TimeOfDay).</p>
<p>Is that the case? If so, how can I test my code?</p>
<p>UPDATE:<br />
Well, it seems that my mistake was that I was trig to run the test using:</p>
<blockquote>
<p>dart test test/simple_test.dart</p>
</blockquote>
<p>Instead of:</p>
<blockquote>
<p>flutter test test/simple_test.dart</p>
</blockquote>
",https://stackoverflow.com/questions/76195915/can-i-do-unit-testing-to-code-that-uses-timeofday-packageflutter-material-dart,"['flutter', 'testing']",19,False,0,0
Consequences on Flutter unit testing requiring all model objects to extend equatable,"<p>When testing for object data equality, models need to override both operator==() &amp; hashCode(), and possibly be immutable if equatable was used.</p>
<p>What would be the consequences in general in term of memory optimization &amp; instantiation time?
Should I consider the idea of creating separate models for testing, leaving the real models intact?</p>
<p>Currently I'm overriding the operator==() &amp; hashCode() methods when needed for every real model.
But I fear this will leave a negative impact on the app performance.</p>
<p>Please share your experience with unit testing in Dart/Flutter.</p>
",https://stackoverflow.com/questions/76218294/consequences-on-flutter-unit-testing-requiring-all-model-objects-to-extend-equat,"['flutter', 'dart', 'unit-testing', 'model', 'pojo']",22,False,0,0
Base class observable(variable) remains undefined in spec file - Angular unit testing,"<p>I have a componentA that inherits(extends) another one i.e componentB. The problem is unit tests of componentA are breaking because an observable defined in componentB remains undefined in spec.ts.</p>
<p>Relevant part of ComponentB(Base class)</p>
<p><code>this.storeObservable = this.store.select(selectCandidateState);</code></p>
<p>Accessing this in ComponentA,</p>
<pre><code>this.storeObservable.subscribe((candidateState) =&gt; {
   this.candidateSkills = candidateState.skills;
   this.unsavedChanges = false;
  });
</code></pre>
<p>Now the unit test of componentA are breaking with this message:</p>
<p>TypeError: Cannot read property 'subscribe' of undefined,</p>
<p>while pointing to <code>this.storeObservable.subscribe</code></p>
<p>ComponentA</p>
<pre><code>export class ComponentA extends ComponentB implements OnInit, OnDestroy 
ngOnInit() {
     super.ngOnInit();

this.storeObservable.subscribe((candidateState) =&gt; {
  this.candidateSkills = candidateState.skills;
  this.unsavedChanges = false;
});
</code></pre>
<p>The unit tests</p>
<pre><code>    let shallow: Shallow&lt;ComponentA&gt;;

  beforeEach(() =&gt; {
    const actions$ = new Observable();
    const services = [Store];
    const mockedServices = [ConfigCzarServiceMock({ test: 'property' })];
    shallow = createShallowComponent(
      ComponentA,
      ProfileModule,
      [componentB],
      [],
      services,
      mockedServices,
     );


&gt; All the tests break with above error. TypeError: Cannot read property
&gt; 'subscribe' of undefined,

</code></pre>
",https://stackoverflow.com/questions/75096268/base-class-observablevariable-remains-undefined-in-spec-file-angular-unit-te,"['javascript', 'angular', 'unit-testing', 'jestjs', 'jasmine']",55,False,0,0
Android Unit Testing: calling function that uses viewModelScope causes a race condition,"<p>I have been trying to create unit tests on my viewModel, but every time I attempt to call a function that launches a coroutine with viewModelScope, it always ends up with a race condition.</p>
<p>example viewModel function:</p>
<pre><code>fun doSomething () {
    viewModelScope.launch {
        runATask()
        flag = true
    }
}
</code></pre>
<p>the test I would make for this:</p>
<pre><code>class viewModelTest {
    val testDispatcher = UnconfinedTestDispatcher()

    val viewModel = testViewModel()

    @ExperimentalCoroutinesApi
    @get:Rule
    var mainCoroutineRule = MainCoroutineRule(testDispatcher)

    @Test
    fun test_view_model () = runTest {
        viewModel.doSomething()

        assert(viewModel.flag == true)
    }
}
</code></pre>
<p>this would cause the viewModel function to start, but it does not complete once the test gets to the assertion.</p>
<p>I have tried following the android migration documentation for using runtest, using the MainCoroutineRule to set the main dispatcher to our UnconfinedTestDispatcher, and tried to launch the function call and join it. This race condition has occured on our instrumented tests and unit tests running robolectric.</p>
<p>I feel like I have tried every solution on StackOverflow that addresses this, and none of them have worked. Any help on this would be greatly appreciated.</p>
<p>Thanks in advance!!</p>
",https://stackoverflow.com/questions/75632335/android-unit-testing-calling-function-that-uses-viewmodelscope-causes-a-race-co,"['android', 'kotlin', 'kotlin-coroutines', 'android-testing', 'robolectric']",102,False,0,0
Unit testing a service that accepts an Fn closure as a callback,"<p>I have the following service that registers callbacks to execute at a certain epoch, identified by an <code>i64</code>. The service has a vector of callbacks (that are bounded by the <code>Send + Fn() -&gt; ()</code> traits). Each callback can be executed multiple times (hence <code>Fn</code> instead of <code>FnOnce</code> or <code>FnMut</code>). The <code>Send</code> trait is needed because the callbacks will be registered by other threads, and this service will run in the background.</p>
<p>So far so good, but I'd like to test that the callbacks are executed the way they should be (i.e. the <code>i64</code> epoch ticking in some direction which may (or may not) cause the callback to be executed). The problem is that I cannot seem to be able to think of a way to achieve this. I'm coming from Golang in which it is quite easy to inject a mock callback and assert whether it was called since such limitations are not imposed by the compiler, however when I employ the same methods in Rust, I end up with an <code>FnMut</code> instead of an <code>Fn</code>.</p>
<pre class=""lang-rust prettyprint-override""><code>use std::sync::{Arc, Mutex};
use std::collections::HashMap;

struct Service&lt;T: Send + Fn() -&gt; ()&gt; {
    triggers: Arc&lt;Mutex&lt;HashMap&lt;i64, Vec&lt;Box&lt;T&gt;&gt;&gt;&gt;&gt;,
}

impl&lt;T: Send + Fn() -&gt; ()&gt; Service&lt;T&gt; {
    pub fn build() -&gt; Self {
        Service {
            triggers: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    pub fn poll(&amp;'static self) {
        let hs = Arc::clone(&amp;self.triggers);
        tokio::spawn(async move {
            loop {
                // do some stuff and get `val`
                if let Some(v) = hs.lock().unwrap().get(&amp;val) {
                    for cb in v.iter() {
                        cb();
                    }
                }
            }
        });
        ()
    }

    pub fn register_callback(&amp;self, val: i64, cb: Box&lt;T&gt;) -&gt; () {
        self.triggers
            .lock()
            .unwrap()
            .entry(val)
            .or_insert(Vec::new())
            .push(cb);
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn test_poll() {
        let c = Service::build();
        let mut called = false;
        let cb = || called = true;
        let h: i64 = 10;
        c.register_callback(h, Box::new(cb));
        assert_eq!(called, false);
    }
}
</code></pre>
<p>Any ideas on how would this sort of behavior could be tested in Rust? The only thing I can think of is perhaps some <code>channel</code> that would pass a local value to the test and relinquish ownership over it?</p>
",https://stackoverflow.com/questions/75257211/unit-testing-a-service-that-accepts-an-fn-closure-as-a-callback,"['unit-testing', 'rust', 'tdd']",58,True,0,1
Angular Unit testing event handle keypress is not returning the right value,"<p>I trying to do a unit testing for angular in jasmine test framework for an event of key event. I want to make the index become 0 when the value is less than 0.</p>
<pre><code>      if ($event.code === 'ArrowUp') {
          if (this.currentIndex &lt; 0) {
              this.currentIndex = 0;
          } else if (this.currentIndex &gt; 0) {
              this.currentIndex--;
          }
</code></pre>
<pre><code>    it('should return 0 when value is less than 0', () =&gt; {
      const event = new KeyboardEvent('ArrowUp', { code: 'ArrowUp' });
      component['currentIndex'] = -5;
      component.handleKeyboardEvents(event);
      expect(component['currentIndex']).toBe(0);
    });
</code></pre>
<p>it doesnt seem like the value was reassign</p>
",https://stackoverflow.com/questions/75015048/angular-unit-testing-event-handle-keypress-is-not-returning-the-right-value,"['angular', 'karma-jasmine', 'karma-runner']",27,False,0,0
Azure DevOps Services REST API 5.1 - get unit testing (VSTest) and sonarqued,"<p>I'm creating a script in ISE powershell to get information from the projects in azure devops. Some apis that I already use in my script are the following:</p>
<ol>
<li>ApiUri = &quot;$projectUri/_apis/tfvc/branches?$apiVersion&quot;</li>
<li>ApiUri =
&quot;$projectUri/_apis/distributedtask/deploymentgroups?$apiVersion-preview&quot;</li>
<li>ApiUri = &quot;$projectUri/_apis/pipelines?$apiVersion-preview&quot;</li>
<li>ApiUri = &quot;$projectUri/_apis/git/repositories?$apiVersion&quot;</li>
<li>ApiReleasePipelinesUri =
&quot;$projectUri/_apis/release/definitions?$apiVersion&quot;</li>
</ol>
<p>An example of what I'm getting with the above apis is:</p>
<p><a href=""https://i.stack.imgur.com/ZXsQU.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ZXsQU.jpg"" alt=""enter image description here"" /></a></p>
<p>In the value, if it is 1 or more, the information of that process goes.</p>
<p><strong>Now I want to extract the information about the unit testing (Visual studio test) and sonarqued.</strong></p>
<p>I would like to have something like this for the case of sonarqued and unittesting. 0 if there was never such an implementation and 1 if unit testing and sonarqued were applied.</p>
<p>I can't find something similar to what I need, if someone could guide me or know how to extract that information it would help me</p>
<p>Used this task for unit tests:
<a href=""https://i.stack.imgur.com/oTMfk.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/oTMfk.jpg"" alt=""enter image description here"" /></a></p>
<p>Used this task to sonarqued:
<a href=""https://i.stack.imgur.com/yEeex.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/yEeex.jpg"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/75137494/azure-devops-services-rest-api-5-1-get-unit-testing-vstest-and-sonarqued,"['azure-pipelines', 'azure-devops-rest-api', 'azure-api-apps']",84,True,0,1
Should call a function when if condition satisfies in angular unit testing,"<p>I have function which is being called only when my subscribe returns a result. But when I am writing test cases that function is being called everytime without condition check. So how to check when subscribe returns a successful response, then only <strong>displayfunction</strong> should be called?</p>
<pre><code>spyOn(component, 'displayfunction');

const mockdata2: any = require('mockdata2.json');
const Object1 = new Objects();
Object1.name = 'abc';
Object1.age = 21;

//s1 ans s2 are 2 strings

spyOn(as, 'addfunction').and.callFake((s1: string, s2: string, Object1: any) =&gt; {
  return new Observable((observer) =&gt; {
    observer.next(mockdata2);
  });
});

expect(component.displayfunction).toHaveBeenCalledTimes(1);
</code></pre>
",https://stackoverflow.com/questions/75004900/should-call-a-function-when-if-condition-satisfies-in-angular-unit-testing,['angular'],21,False,0,0
Call to a member function validated() on null (Unit testing Laravel 9),"<p>I am writing test for some controller method that will validate request data and create document by 3rd party API. Then it should return response with <code>201</code> status code. I am using mocking to mock my service class that is creating document. Here is my controller:</p>
<pre><code>public function margin(MarginRequest $request){
    $data = $request-&gt;validated();

    $fileId = $this-&gt;documentService-&gt;createDocument(auth()-&gt;user()-&gt;id, SignableDocumentAbstract::MARGIN_CERTIFICATE, new MarginDocument(), $data);

    return response()-&gt;json([
        'code' =&gt; 201,
        'message' =&gt; 'Margin agreement generated successfully',
        'data' =&gt; [
            'uuid' =&gt; $fileId
        ]
    ], 201);
}
</code></pre>
<p>And my test:</p>
<pre><code>public function test_public_margin()
{
    $marginData = (new MarginFaker())-&gt;fake();

    Auth::shouldReceive('user')-&gt;once()-&gt;andReturn((object)['id' =&gt; 999999]);

    $this-&gt;mock(DocumentService::class, function (MockInterface $mock) {
        $mock-&gt;shouldReceive('createDocument')
            -&gt;once()
            -&gt;andReturn(Str::random());
    });

    $request = MarginRequest::create('/api/public/documents/margin', 'POST', $marginData);

    $response = app(PublicController::class)-&gt;margin($request);

    $this-&gt;assertEquals(201, $response-&gt;getStatusCode());
}
</code></pre>
<p>Everything look OK but when I run my test it throws error that</p>
<p><code>Call to a member function validated() on null</code></p>
<p>It is given in <code>$data = $request-&gt;validated();</code> line of controller. But I can't understand why my <code>$request</code> is recognized as null. Even if I dump request object by <code>dump($request)</code> I can see that it is object and holds all required fields inside.</p>
<p>Then what can be the reason, why I can't call <code>validated()</code> method while testing?</p>
",https://stackoverflow.com/questions/75131452/call-to-a-member-function-validated-on-null-unit-testing-laravel-9,"['php', 'laravel', 'unit-testing', 'mocking', 'phpunit']",326,True,0,1
Visual Studio Live Unit Testing doesn&#39;t have option to &quot;enable debug symbol&quot;,"<p>I'm using Visual Studio 2022 17.4.0 to run the Live Unit Testing window using xUnit v2.4.2 tests with the xunit.runner.visualstudio v2.4.5.</p>
<p>When looking at the following documentation, it claims that I should have a checkmark thats allows me to run these tests with debug symbols.  However, this is completely missing from my options.</p>
<p><a href=""https://learn.microsoft.com/en-us/visualstudio/test/live-unit-testing?view=vs-2022"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/visualstudio/test/live-unit-testing?view=vs-2022</a></p>
<p>Here's what it <em>should</em> look like:
<a href=""https://i.stack.imgur.com/gvL66.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/gvL66.png"" alt=""enter image description here"" /></a></p>
<p>And here's why mine actually looks like:
<a href=""https://i.stack.imgur.com/UQj7i.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/UQj7i.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/75164810/visual-studio-live-unit-testing-doesnt-have-option-to-enable-debug-symbol,"['visual-studio', 'xunit', 'live-unit-tests']",51,False,0,0
Unit Testing DLL project on Windows using Google Test in VS 2022,"<p>I am trying to write unit tests for a larger, old project using GTest. The project compiles as a dll. Here is what the setup looks like: There are several projects inside the solution, and I am trying to add a Test Project to unit test on of the several projects.</p>
<p>As a proof of concept, I created a HelloWorld project, and a HelloWorldTest project in a different solution. To emulate my larger project, I changed the Configuration Type from <code>.exe</code> to <code>.dll</code> and ran into some errors. But these errors were resolved exporting classes/functions using <a href=""https://stackoverflow.com/a/59569755/4420229""><code>__declspec(dllexport)</code></a> along with including <code>.lib</code> in the project, and I am able to build and run the exe of the HelloWorldTest project.</p>
<p>I am trying to follow the same approach for my larger project by painstakingly adding EXPORT statements before classes/functions. However, I run into errors when I include required header files in the Test Project since the header file has other include statements which the Test Project does not understand about. For example, if I <code>include &quot;..\larger_project\custom_math.h&quot;</code> but <code>custom_math.h</code> has something like <code>include &quot;..\..\algo\somefile.h&quot;</code>. (I've seen posts about referencing one project to another and have already done the same for my project.)</p>
<ol>
<li>How do I resolve the issue of chained header file includes? I believe if I can resolve this, I should be able to create objects and start testing in my Test Project.</li>
<li>is there a better way to do this than adding EXPORT statements before every class/function?</li>
</ol>
",https://stackoverflow.com/questions/75420730/unit-testing-dll-project-on-windows-using-google-test-in-vs-2022,"['c++', 'dll', 'visual-studio-2022']",55,False,0,0
SwiftUI Unit Testing a Custom Button Style Fails When ButtonStyle Accesses @Environment,"<p>I am building a Swift Package and attempting to unit test a custom <code>ButtonStyle</code> that assigns specific colors to the button based on <code>default</code>, <code>isPressed</code>, and <code>isEnabled</code> properties.</p>
<p>In the test I create a <code>Button</code> object, run the <code>.buttonStyle()</code> function on it, then run the <code>.disabled(Bool)</code> function to try to set the <code>@Environment</code> to force the custom <code>ButtonStyle</code> to respond how I like. The style works as expected in Previews but I cannot seem to establish the <code>@Environment</code> for testing.</p>
<p><strong>Custom ButtonStyle Code</strong></p>
<pre><code>import SwiftUI

public struct MyButtonStyle: ButtonStyle {

    @Environment(\.isEnabled) var isEnabled
    var properties: MyButtonProperties

    func getForegroundColor(pressed: Bool = false) -&gt; Color {
        if !isEnabled {
            return properties.disabledForegroundColor
        }
        if pressed {
            return properties.pressedForegroundColor
        }
        return properties.defaultForegroundColor
    }

    func getBackgroundColor(pressed: Bool = false) -&gt; Color {
        if !isEnabled {
            return properties.disabledBackgroundColor
        }
        if pressed {
            return properties.pressedBackgroundColor
        }
        return properties.defaultBackgroundColor
    }

    public func makeBody(configuration: Configuration) -&gt; some View {
        configuration.label
            .foregroundColor(getForegroundColor(pressed: configuration.isPressed))
            .background(getBackgroundColor(pressed: configuration.isPressed))
    }
 }

</code></pre>
<p><strong>Test Code</strong></p>
<pre><code>import XCTest
import SwiftUI
import ViewInspector
@testable import MyComponentLibrary

final class MyButtonStyleTests: XCTestCase {

    let properties = MyButtonProperties(
        defaultBackgroundColor: Color.orange,
        defaultForegroundColor: Color.white,
        pressedBackgroundColor: Color.blue,
        pressedForegroundColor: Color.black,
        disabledBackgroundColor: Color.gray,
        disabledForegroundColor: Color.red
    )

    func testDisabledButtonShowsCorrectColors() throws {        
        let button = Button(action: {}, label: {Text(&quot;Hello&quot;)})
            .buttonStyle(MyButtonStyle(properties: properties))
            .disabled(true)
        let style = try button.inspect().button().buttonStyle()

        XCTAssertTrue(style is MyButtonStyle)

        let testStyle = style as! MyButtonStyle
        let testObj = try testStyle.inspect(isPressed: false)
        let backgroundColor = try testObj.background(0).color().value()
        let foregroundColor = try testObj.foregroundColor()

        XCTAssertEqual(backgroundColor, properties.disabledBackgroundColor)
        XCTAssertEqual(foregroundColor, properties.disabledForegroundColor)
    }

}
</code></pre>
<p>The first assert <code>XCTAssertTrue()</code> passes. So the custom <code>ButtonStyle</code> is managing the <code>View</code>. The last two asserts <code>XCTAssertEqual()</code> fail since the <code>background</code> and <code>foregroundColor</code> values are set to the default colors. This is due the <code>@Environment()</code> responding to getting the <code>isEnabled</code> key path with the following warning. <code>Accessing Environment&lt;Bool&gt;'s value outside of being installed on a View. This will always read the default value and will not update.</code> Therefore when running the test the <code>isEnabled</code> is always true. When inspecting <code>isEnabled</code> during the test its value is <code>SwiftUI.Environment&lt;Bool&gt;.Content &lt;invalid&gt; (0x0)</code>.</p>
<p>This may be due to running this in a test environment and not in an application but I am not certain of that.</p>
<p>Is there a way to wrap my <code>Button</code> object in an <code>Environment</code> that would allow me to test the <code>ButtonStyle</code> the way I would like?</p>
",https://stackoverflow.com/questions/75940387/swiftui-unit-testing-a-custom-button-style-fails-when-buttonstyle-accesses-envi,"['unit-testing', 'swiftui', 'swiftui-button']",45,False,0,0
Unit testing a HTTP handler that returns a stream of multiple files,"<h1>HTTP handler</h1>
<p>I have a HTTP handler like this:</p>
<pre class=""lang-golang prettyprint-override""><code>func RouteHandler(c echo.Context) error {
    outs := make([]io.Reader, 5)
    for i := range outs {
        outs[i] = // ... comes from a logic.
    }

    return c.Stream(http.StatusOK, &quot;application/binary&quot;, io.MultiReader(outs...))
}
</code></pre>
<h1>Unit test</h1>
<p>I intend to write a unit test for HTTP handler and investigate the returned stream of multiple files.</p>
<p>I have these helper type and function for my unit test:</p>
<pre class=""lang-golang prettyprint-override""><code>type Handler func(echo.Context) error

// Send request to a handler. Get back response body.
func Send(req *http.Request, handler Handler) ([]byte, error) {
    w := httptest.NewRecorder()
    e := echo.New()
    c := e.NewContext(req, w)
    // Call the handler.
    err := handler(c)
    if err != nil {
        return nil, err
    }
    res := w.Result()
    defer res.Body.Close()
    return ioutil.ReadAll(res.Body)
}
</code></pre>
<p>Then, I use the above type and function to send a request to my HTTP handler from within my unit test:</p>
<pre class=""lang-golang prettyprint-override""><code>// From within my unit test:

// Initialize request...

var data []byte
data, err := Send(request, RouteHandler)

// How to separate the multiple files returned here?
// How to work with the returned data?
</code></pre>
<h1>Work with returned stream of files</h1>
<p>How can I separate multiple files returned by the HTTP handler? How can I work with the stream of data returned by HTTP handler?</p>
",https://stackoverflow.com/questions/75428800/unit-testing-a-http-handler-that-returns-a-stream-of-multiple-files,"['unit-testing', 'go', 'go-echo']",59,True,0,1
Unit testing a method that checks if the argument equals a certain value?,"<p>I have a method that checks if the argument equals a certain value. Let's assume it checks if the value equals 25.</p>
<pre><code>public bool CheckIs25(int input)
{
   return input==25;
}
</code></pre>
<p>First I wrote a unit test to check if the input is 25 the output must be true (using Xunit):</p>
<pre><code>[Fact]
public void CheckIs25_WhenIs25_MustReturnTrue()
{
   var result = testee.CheckIs25(25);

   Assert.True(result)
}
</code></pre>
<p>Now, how can I test that if the input is NOT 25 the output must be false? I could use a couple of numbers which are not 25 and check if the output is false:</p>
<pre><code>[Theory]
[InlineData(0)]
[InlineData(24)]
[InlineData(26)]
public void CheckIs25_WhenNot25_MustReturnFalse(int input)
{
   var result = testee.CheckIs25(input);

   Assert.False(result);
}
</code></pre>
<p>There are a huge number of possible input values, and I can not test all of them.
So I can not test if the output is really only true when the input is 25.
If someone mistakenly changed the method like so:</p>
<pre><code>public bool CheckIs25(int input)
{
   return input==25||input==12345;
}
</code></pre>
<p>Now the method also returns true if the input is 12345.
My unit tests would not fail and the faulty change would not be noticed.</p>
<p>I thought if someone makes a change which alters the behavior of the method, then there must be a failing unit test. This is not the case here.
Could I change my method or the unit tests in any way that a bad change to the code would be result in a failing test?
Or is my notion of unit testing wrong?</p>
",https://stackoverflow.com/questions/75810862/unit-testing-a-method-that-checks-if-the-argument-equals-a-certain-value,"['c#', 'unit-testing', 'tdd', 'xunit']",75,True,2,1
Angular Unit - testing (Jasmine karma) : Failed: Cannot read properties of undefined (reading &#39;getComplete),"<p>I called getComplete method in component.spec.ts file which is defined in google.directive.ts file.
component.ts:--&gt;</p>
<pre><code> ngAfterViewInit(): void {
    ...
    this.googleComplete.getComplete(this.addresstext);
    console.log('address is:--' , this.addresstext);
</code></pre>
<p>*googleComplete:--&gt; ComponentPage.googleComplete: GoogleCompleteDirective</p>
<p>component.spec.ts:-&gt;</p>
<pre><code>it('called getComplete method', waitForAsync(inject([GoogleCompleteDirective],
    ( googleCompleteDirective: GoogleCompleteDirective ) =&gt; {
    spyOn(component, 'ngAfterViewInit').and.callThrough();
    spyOn(googleCompleteDirective, 'getComplete').and.callThrough();
    component.ngAfterViewInit();
    expect(component.ngAfterViewInit).toHaveBeenCalled();
</code></pre>
<p>google.directive.ts:-&gt;</p>
<pre><code>getComplete(addresstext: ElementRef) {
//code here....
....
}

</code></pre>
<p>directive.ts:-</p>
<pre><code>getAutocomplete(addresstext: ElementRef) {
    const autocomplete = new google.maps.places.Autocomplete(addresstext.nativeElement,
      {
        componentRestrictions: { country: 'US' },
        fields: ['address_components', 'geometry'],
        types: ['address']
      });
</code></pre>
<p>after testing this code, got Error:-&gt;
&quot; Failed: google is not defined</p>
<p>ReferenceError: google is not defined&quot;</p>
<p>I also used  providers:
[ GoogleCompleteDirective,{ provide: ElementRef, useValue: {} }, ]
in provider for elementref and imported getCompleteDirective</p>
<p>Please suggest me the ways to fix this?</p>
<p>It should pass test case but getting Error:-&gt;
&quot; Failed: google is not defined</p>
<p>ReferenceError: google is not defined&quot;</p>
",https://stackoverflow.com/questions/74985240/angular-unit-testing-jasmine-karma-failed-cannot-read-properties-of-undef,"['javascript', 'angular', 'google-maps', 'karma-jasmine']",232,False,1,0
Calling a subscribe method and passing value to private variable in unit testing,"<p>In my ts file inside subscribe its passing a boolean and that is by default <strong>true</strong>, Can I set it to <strong>false</strong> into this boolean variable in angular test cases</p>
<p><strong>ts file</strong></p>
<pre><code>private On: boolean = true;
private Subscriptionobj: Subscription;
public ToggleSubject: Subject&lt;boolean&gt;;
this.ToggleSubject= new Subject&lt;boolean&gt;();

this.Subscriptionobj= this.ToggleSubject.subscribe((IsOn: boolean) =&gt; {
  this.On = IsOn;
});
</code></pre>
<p><strong>spec.ts</strong></p>
<pre><code>component.ToggleSubject.subscribe
((IsOn: boolean) =&gt; {
  component.On = IsOn;
});
</code></pre>
",https://stackoverflow.com/questions/75059636/calling-a-subscribe-method-and-passing-value-to-private-variable-in-unit-testing,"['angular', 'unit-testing']",40,False,0,0
How to perform a transitivity mocking of classes/objects in python unit testing,"<p>I am new to unittesting in python and was trying to mock a object explained like below:</p>
<p>i have three scripts:</p>
<ul>
<li>test1.py (Class : test1)</li>
<li>test2.py (Class : test2)</li>
<li>test3.py (Class : test3)</li>
</ul>
<p>test2.py is creating object of test3.py
test1.py is creating object of test2.py</p>
<p>I want to mock test3 inside test1, so that when it creates object of test2 it consider mocking object of test3.</p>
<p>test3.py:</p>
<pre><code>class test3():

    def __init__(self):
        print(&quot;Created object os myclass&quot;)
        self.name = &quot;rahul&quot;
</code></pre>
<p>test2.py:</p>
<pre><code>from test3 import test3

class test2():

    def __init__(self):
        self.sirName = &quot;Rohilla&quot;
        self.test3object = test3()
</code></pre>
<p>test1.py:</p>
<pre><code>from unittest import mock
from test3 import test3
from test2 import test2

class test1():

    @mock.patch('test3.test3') # -&gt; here i tried __name__+'.test3' but that didn't work
    def fun2(self, myclass):
        mockObject = mock.MagicMock()
        mockObject = {}
        myclass.return_value = mockObject
        test2Object = test2() # -&gt; here test2Object doesn't have mockobject

main1 = test1()

main1.fun2()
</code></pre>
<p>My problem is test2Object doesn't contain mockedobject for test3. can someone suggest me any other way?</p>
",https://stackoverflow.com/questions/75366292/how-to-perform-a-transitivity-mocking-of-classes-objects-in-python-unit-testing,"['python', 'unit-testing', 'mocking', 'python-mock']",26,False,0,0
SQLModel in Fastapi using __table_args__ is unable to create tables for unit testing,"<p>My Model is as follows, this model is defined in a file called tool_model.py, Hence the creation using <code>tool_model.SQLModel.metadata.create_all(engine)</code></p>
<pre><code>class Tool(SQLModel, table=True):
    __tablename__='tools'
    __table_args__ = {'schema': 'rna'}


    id: Optional[int] = Field(default=None, primary_key=True)
    tool_name: str = Field(sa_column=Column(&quot;tool_name&quot;, VARCHAR(500), nullable=False))
    tool_description: str = Field(
        sa_column=Column(&quot;tool_description&quot;, VARCHAR(1000), nullable=False)
    )
</code></pre>
<p>This seems to be working fine, but when I try to create unit test for the same and try to create the models in fixture</p>
<p>conftest.py</p>
<pre><code>@pytest.fixture(name=&quot;session&quot;,scope=&quot;module&quot;)
def session_fixture():
    engine = create_engine(
        &quot;sqlite:///./test.db&quot;, connect_args={&quot;check_same_thread&quot;: False}, poolclass=StaticPool
    )
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    tool_model.SQLModel.metadata.create_all(engine)
</code></pre>
<p>it is giving me the following error</p>
<pre><code>E sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unknown database &quot;rna&quot;
E [SQL: PRAGMA &quot;rna&quot;.table_info(&quot;tools&quot;)]
E (Background on this error at: https://sqlalche.me/e/14/e3q8)
</code></pre>
",https://stackoverflow.com/questions/75035010/sqlmodel-in-fastapi-using-table-args-is-unable-to-create-tables-for-unit-tes,"['sqlalchemy', 'pytest', 'fastapi', 'sqlmodel']",20,False,0,0
Nest Js Jest Unit Testing: Providing a mock implementation not used from controller,"<p>I have already a mock class implemented as a part of my previous work, which I want to provide as a part of my Jest Unit Testing.</p>
<p>Let me explain in code, that's better:</p>
<p>My Controller code:</p>
<pre class=""lang-js prettyprint-override""><code>export class VpcController {
  constructor(private readonly vpcService: VpcService) {}
  @Get
    list() {
    return this.vpcService.list();
  }
}
</code></pre>
<p>My controller Jest Unit Test:</p>
<pre class=""lang-js prettyprint-override""><code>class VpcServiceMockFactory {
  private list() {
    return jest.fn().mockResolvedValue([TEMPLATE_VPC]);
  }

  getMock() {
    const repoService: RepositoryService = new RepositoryService();
    const vpsServiceMock: VpcServiceMock = new VpcServiceMock(repoService);
    vpsServiceMock.create(TEMPLATE_VPC.name);

    // This works
    // return {
    //   list: this.list(),
    // }

    // This does not work
    return {
      list: vpsServiceMock.list(),
      get: vpsServiceMock.get(TEMPLATE_VPC.id),
      // create: vpsServiceMock.create('new-vpc'),
      // update: vpsServiceMock.update(TEMPLATE_VPC.id, 'updated-name'),
      // delete: vpsServiceMock.delete(TEMPLATE_VPC.id),
    }
  }
}
describe('VpcControllerTest', () =&gt; {
  let controller: VpcController;
  let spyService: VpcService;

  beforeEach(async () =&gt; {
    // Mock Services
    const MockVpcServiceProvider = {
      provide: VpcService,
      useFactory: () =&gt; new VpcServiceMockFactory().getMock()
    }

    // Class-unter-test instantiation
    const module: TestingModule = await Test.createTestingModule({
      controllers: [VpcController],
      providers: [VpcService, MockVpcServiceProvider],
    }).compile()

    // Get the instance handlers
    controller = module.get&lt;VpcController&gt;(VpcController);
    spyService = module.get&lt;VpcService&gt;(VpcService);
  });

  it('Get collection of VPCs', async () =&gt; {
    // Execute the method
    const result = await controller.list();

    // Assertion
    expect(spyService.list).toHaveBeenCalled();
    expect(result.length).toBe(1);
    expect(result[0].name).toBe('zopa');
  });
}
</code></pre>
<p>My VpcServiceMock class:</p>
<pre class=""lang-js prettyprint-override""><code>export class VpcServiceMock {
  constructor(private repository: RepositoryService) {}
  list() {
    return this.repository.list&lt;VpcModel&gt;(VPC);
  }
}
</code></pre>
<p>My RepositoryService class:</p>
<pre class=""lang-js prettyprint-override""><code>  async list&lt;T&gt;(type: VPC): Promise&lt;T[]&gt; {
    return &lt;T[]&gt;this.aSimpleJsonObject[type];
  }

</code></pre>
<p>However when I am running it, it is showing this error:</p>
<pre><code>  ● VpcControllerTest › Test-2: Get collection of VPCs                                                                                                             
                                                                                                                                                                   
    TypeError: this.vpcService.list is not a function

      38 |   @ApiForbiddenResponse({ description: 'Unauthorized Request' })
      39 |   list() {
    &gt; 40 |     return this.vpcService.list();
         |                            ^
      41 |   }
      42 |
      43 |   @Get(':id')

      at VpcController.list (src/vpc/vpc.controller.ts:40:28)
      at Object.&lt;anonymous&gt; (src/vpc/vpc.controller.spec.ts:87:37)

</code></pre>
<p>So the only way I can make it work:</p>
<p>If I provide a mock implementation in the Jest Unit test's <code>VpcServiceMockFactory</code> class (like I showed in the commented out code there as <code>// This works</code>).</p>
<p>Definitely I am missing something here, which I am not able to figure out.</p>
",https://stackoverflow.com/questions/75168621/nest-js-jest-unit-testing-providing-a-mock-implementation-not-used-from-control,"['jestjs', 'nest', 'ts-jest']",258,False,-1,1
Angular Unit testing with MatDialog - Error: &lt;spyOn&gt; : open has already been spied upon,"<p>I create a html file with button. After onClickEvent poll appears and next, after click on button &quot;submit&quot; dialog window closes and I would like to call next methods.</p>
<p>TS.file:</p>
<pre><code>openDialogWindow() {
const dialogRef = this.dialogWindow.open(PollComponent, {
  width: '400px',
  height: '400px',
  data: getData()
});

dialogRef.afterClosed().subscribe(result =&gt; {
  if (result.status == 'VALID') {
    answerForm = result;
    this.callNextFunction();
  }
});
</code></pre>
<p>}</p>
<p>and then I created unit test in spec.ts file:</p>
<pre><code>it('should call dialogwindow and after submit call methods', () =&gt; {
service.callNextFunction.and.returnValue(of({value: 0}));

const result = new FormGroup({}, )
result.setValidators(null);
spyOn(component.dialogWindow, 'open')
  .and
  .returnValue({
    afterClosed: () =&gt; of(true)
  } as MatDialogRef&lt;typeof component&gt;);
  
fixture.detectChanges();
expect(component.dialogWindow.afterAllClosed).toContain(result);
expect(service.callNextFunction).toHaveBeenCalled();
expect(component.otherForm.recommendedValue.control.value).toEqual('123');
</code></pre>
<p>});</p>
<p>but when I test it I am getting error:</p>
<pre><code>Error: &lt;spyOn&gt; : open has already been spied upon
Usage: spyOn(&lt;object&gt;, &lt;methodName&gt;)
</code></pre>
<p>can it be caused by create:</p>
<pre><code>matDialogSpy = createSpyObj&lt;MatDialog&gt;('MatDialog', ['open']);
</code></pre>
<p>in beforeEach?
I use matDialogSpy  in other unit test for check if dialog window will open after click on button:</p>
<pre><code>it('should open dialog when button has been clicked', fakeAsync(() =&gt; {
clickOnSlsButtonByLabel('Open dialog', fixture);

expect(matDialogSpy.open).toHaveBeenCalledTimes(1);
expect(matDialogSpy.open).toHaveBeenCalledWith(
  PollComponent,
  {
    width: '400px',
    height: '400px',
    data: data...
  }
);
</code></pre>
<p>}));</p>
",https://stackoverflow.com/questions/75590830/angular-unit-testing-with-matdialog-error-spyon-open-has-already-been-spi,"['angular', 'typescript', 'unit-testing']",89,False,0,1
Error: Expected one matching request for criteria &quot;Match URL: in angular unit testing?,"<p>I am creating the test case for the component but i got above error in the cmd after ng test.i have tried each and everything but nothing solution worked for me check below code snippet in which i have shared the function which need to be tested</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""false"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>//function to be tested
listDataViaKey(event: any, data: any, tabName: string) {
    let url:string
    switch (tabName) {
      case 'flight':
        url = TESTURL.getInformationById + data.Guid;
        this.flightInfoSubsription = this.httpService.get(url)
          .subscribe((resp:any) =&gt; {
            this.flightsInfo = resp.apiData[0].ApiData;
            this.editScreen = true;
          });
        break;
      case 'bus':
        url = TESTURL.getBusInfomationById + data._id;
        this.aircraftSubscription = this.httpService.get(url)
          .subscribe((resp: any) =&gt; {
            this.busInfo = resp.apiData[0].ApiData;
            this.editAircraftScreen =true;
          })
        break;
    }
  }
  
  //Unit testing code
  it('should call listViewClick for flight', () =&gt; {
    const data = {Guid:'121'};
    const res = { apiData: [{ ApiData: { type: 'test3'}}]};
    component.listViewClick('',data,'flight');
    const req = httpMock.expectOne(APPURL.getInformationById + data.Guid);
    expect(component.editAircraftScreen).toBeTruthy();
  });
  </code></pre>
</div>
</div>
</p>
<p>can anybody help me that how to fix above error?</p>
",https://stackoverflow.com/questions/76208901/error-expected-one-matching-request-for-criteria-match-url-in-angular-unit-te,"['angular12', 'angular-unit-test']",8,False,0,0
is there any way to mock time.LoadLocation() in golang for unit testing purpose?,"<pre><code>zone := injection.GetGlobalConfigs().DefaultTimezone

loc, err := time.LoadLocation(zone)
</code></pre>
<p>I have to test a method which internally calls these methods i need to write unit-test for the method for error case that is time.LoadLocation(zone) returns error. is there any implementations to do these?</p>
<p>Expecting suggestions</p>
",https://stackoverflow.com/questions/75982687/is-there-any-way-to-mock-time-loadlocation-in-golang-for-unit-testing-purpose,"['unit-testing', 'go', 'mocking']",85,False,-2,1
Algorithm or a tool to compare two spectrogram outputs for unit testing purposes,"<p>I am looking for a good algorithm or a tool to compare two spectrogram outputs for unit testing. I can visually confirm the outputs are similar but I would like to automate this process. The basic stats of the outputs, such as min/max/avg/median are kind of the same but this would not catch true differences.</p>
",https://stackoverflow.com/questions/75393470/algorithm-or-a-tool-to-compare-two-spectrogram-outputs-for-unit-testing-purposes,"['unit-testing', 'compare', 'spectrogram']",5,False,0,0
Unit testing with camel causing InvalidDefinitionException Java 8 date/time &#39;java.time.LocalDate&#39; not supportend,"<p>I'm trying to test a camel route that makes use of Marshal EIP with Jackson however when I try to convert a LocalDate I get an InvalidDefinitionException. I already added the module &quot;com.fasterxml.jackson.datatype:jackson-datatype-jsr310&quot; to my dependencies and registered it without any success. Any suggestion what could be wrong? Also use property <code>camel.dataformat.jackson.auto-discover-object-mapper=true</code> but it doesn't work in tests</p>
<p>Route</p>
<pre><code>@Component
public class MyRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from(&quot;direct:MyRoute&quot;)
            .routeId(&quot;MyRoute&quot;)
            .marshal()
            .json(JsonLibrary.Jackson)
    }
}
</code></pre>
<p>Test</p>
<pre><code>@SpringBootTest()
@CamelSpringBootTest
@EnableRouteCoverage
public class MyRouteTest {
    @Autowired private CamelContext camelContext;

    @Autowired private ProducerTemplate producerTemplate;

    @Test
    public void testMyRoute() throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        Exchange ex = new DefaultExchange(camelContext);
        Map&lt;String, Object&gt; map = new LinkedHashMap&lt;&gt;();
        map.put(&quot;name&quot;, &quot;Rick&quot;);
        map.put(&quot;birth-date&quot;, LocalDate.of(2023, 3, 27));
        exchange.getMessage().setBody(map);
        Exchange result = producerTemplate.send(&quot;direct:MyRoute&quot;, exchange);
        // Asserts
    }
}
</code></pre>
<p>dependencies</p>
<pre><code>configurations {
    testImplementation.extendsFrom compileOnly
}

buildscript {
    ext {
        springBootVersion = '3.0.2'
        camelVersion = '4.0.0-M1'
    }
}

dependencies{
    compileOnly group: 'org.springframework.boot', name: 'spring-boot-dependencies', version: springBootVersion
    compileOnly group: 'org.apache.camel.springboot', name: 'camel-spring-boot-starter', version: camelVersion
    compileOnly group: 'org.apache.camel.springboot', name: 'camel-jackson-starter', version: camelVersion
    compileOnly group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.14.2'
    testImplementation group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: springBootVersion
    testImplementation group: 'org.apache.camel', name: 'camel-test-spring-junit5', version: camelVersion
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}
</code></pre>
",https://stackoverflow.com/questions/75857492/unit-testing-with-camel-causing-invaliddefinitionexception-java-8-date-time-jav,"['java', 'jackson', 'apache-camel']",104,True,0,1
how to set value for android.util.Pair variable in android studio java unit testing,"<p>I am working on unit testing and I have to test a method which is return a &quot;MutableLiveData&lt;Pair&lt;String, Boolean&gt;&gt;&quot; .So make a Pair variable and set value . But when I debug the test case, I notice that Pair varible is null</p>
<pre><code>Pair&lt;String,Boolean&gt; pair = new Pair&lt;&gt;(&quot;dsn&quot;,true);
</code></pre>
<p>please don't suggest android.support.v4.util.Pair instead of android.util.Pair,it  doesn't work for me.</p>
",https://stackoverflow.com/questions/75820731/how-to-set-value-for-android-util-pair-variable-in-android-studio-java-unit-test,"['java', 'android-studio', 'junit4']",47,False,0,0
Why am I getting a &quot;Not Implemented&quot; error when unit testing firebase security rules?,"<p>I am writing firebase storage security rules, and unit testing them with &quot;@firebase/rules-unit-testing&quot;. When running the tests, I get the following error:</p>
<pre><code>Not Implemented

      at node_modules/@firebase/rules-unit-testing/src/impl/rules.ts:64:11
      at step (node_modules/@firebase/rules-unit-testing/dist/index.cjs.js:74:23)
      at Object.next (node_modules/@firebase/rules-unit-testing/dist/index.cjs.js:55:53)
      at fulfilled (node_modules/@firebase/rules-unit-testing/dist/index.cjs.js:45:58)
      at tryCallOne (node_modules/promise/lib/core.js:37:12)
      at node_modules/promise/lib/core.js:123:15
      at flush (node_modules/asap/raw.js:50:29)
</code></pre>
<p>The only unit test I have currently is supposed to confirm that users cannot delete files.</p>
<p>Here is my code:</p>
<pre class=""lang-js prettyprint-override""><code>import {
  assertFails,
  assertSucceeds,
  initializeTestEnvironment,
  RulesTestEnvironment,
} from &quot;@firebase/rules-unit-testing&quot;;
import {
  deleteObject,
  ref,
  uploadBytes,
} from &quot;firebase/storage&quot;;
import * as fs from &quot;fs&quot;;
const PROJECT_ID = &quot;iurn-973d0&quot;;
let testEnv: RulesTestEnvironment;

describe(&quot;Firebase storage security rules&quot;, () =&gt; {
  beforeAll(async () =&gt; {
    testEnv = await initializeTestEnvironment({
      projectId: PROJECT_ID,
      firestore: {
        rules: fs.readFileSync(__dirname + &quot;/../storage.rules&quot;, &quot;utf-8&quot;),
        host: &quot;127.0.0.1&quot;,
        port: 9199,
      },
    });
  });
  beforeEach(async () =&gt; {
    if(!testEnv) return
    testEnv.clearStorage();
  });

  it(&quot;DOES NOT allow deletion&quot;, async () =&gt; {
    if(!testEnv) return
    const storage = testEnv.authenticatedContext(&quot;user123&quot;).storage();
    await testEnv.withSecurityRulesDisabled(async (context) =&gt; {
      await uploadBytes(ref(context.storage(), &quot;hi.jpg&quot;), require(&quot;../assets/images/placeholder.png&quot;))
    })
    expect(assertFails(deleteObject(ref(storage, &quot;hi.jpg&quot;)))).resolves.toBeTruthy()
  })

  afterAll(async () =&gt; {
    if(!testEnv) return
    testEnv.cleanup();
  });
});
</code></pre>
",https://stackoverflow.com/questions/75441714/why-am-i-getting-a-not-implemented-error-when-unit-testing-firebase-security-r,"['firebase', 'unit-testing', 'jestjs', 'firebase-storage', 'firebase-security']",102,False,4,0
Simplifying code for placing ships in Battleship game in Python and conducting Unit Testing,"<p>I am currently working on a class project to build the game Battleship in Python.  Another user here graciously helped me understand the coding for my board, and now I have come to the step to randomly enter the ships ('S') into positions on the board.  For this project, each ship, 'S' is limited to one space on the board.  I have developed the code:</p>
<pre><code>randomRow = random.randint(0, grid_size - 1)
randomCol = random.randint(0, grid_size - 1)  
myBoard[randomRow][randomCol] = 'S'
</code></pre>
<p>and entered these 3 lines five times to get the five ships needed for my game, however I feel like there must be a cleaner way to enter this information, perhaps with a while loop?  In addition to this, my teacher has asked us to confirm that if a ship, 'S', has been placed, no other ship may be entered in the same spot.  If I enter the code above five times, I always get five different spots, but I am guessing if I use a while loop, or something else to place the ships, I will need an additional argument to be sure each ship is placed on a different spot, and am stuck in figuring out how to do this.</p>
<p>Lastly, we have been asked to write two Unit Tests for this step.  One which will check that the appropriate number of ships (5) have been placed, and one which will check that the other spaces are blank (in my code, denoted by '.' for open water).  I am very ignorant when it comes to Unit Testing, and was wondering if anyone could share good resources for beginners on what a Unit Test is, how to implement one, etc.  Examples are very helpful to me as well.</p>
<p>For context, here is the full code for this program I have thus far:</p>
<pre><code>import random

# Legend:
# 1. &quot;.&quot; = water
# 2. &quot;S&quot; = ship position
# 3. &quot;O&quot; = water that was shot with bullet, a miss because it hit no ship
# 4. &quot;X&quot; = ship sunk!

#global variable for grid size
grid_size = 10
#global variable for grid
myBoard = [['.']*grid_size for i in range(grid_size)]
# display the grid (2d array)

def main():
    # Call drawBoard function with myBoard
    drawBoard(myBoard)
    user_guess(myBoard)

def drawBoard(myBoard):
    # Print header
    print(end=&quot;  &quot;)
    for i in range(grid_size):
        print(i, end=&quot; &quot;)
    print()

    # Print rows
    for i in range(grid_size):
        print(i, end=&quot; &quot;)
        for j in range(grid_size):
            print(myBoard[i][j], end=&quot; &quot;) # change grid to myBoard
        print()
      
# Place ships
randomRow = random.randint(0, grid_size - 1)
randomCol = random.randint(0, grid_size - 1)  
myBoard[randomRow][randomCol] = 'S'

randomRow = random.randint(0, grid_size - 1)
randomCol = random.randint(0, grid_size - 1)  
myBoard[randomRow][randomCol] = 'S'

randomRow = random.randint(0, grid_size - 1)
randomCol = random.randint(0, grid_size - 1)  
myBoard[randomRow][randomCol] = 'S'

randomRow = random.randint(0, grid_size - 1)
randomCol = random.randint(0, grid_size - 1)  
myBoard[randomRow][randomCol] = 'S'

randomRow = random.randint(0, grid_size - 1)
randomCol = random.randint(0, grid_size - 1)  
myBoard[randomRow][randomCol] = 'S'

# Call main function
main()
</code></pre>
<p>While trying to figure out how to combine my code above with a while loop, I found an example on Youtube, and tried to adopt it to my program, along the lines of:</p>
<pre><code>def create_ships(myBoard):
    for ship in range(5):
        while myBoard[ship_row][ship_column] == &quot;S&quot;:
            ship_row, ship_column = get_ship_location()
        myBoard[ship_row][ship_column] = &quot;S&quot;

</code></pre>
<p>But was unsure of where to place the previous three lines of code in relation to this function.  I tried placing it inside the function, but then when I ran the code, my ships did not print.  I am at a loss for how to combine these two elements.  Should I include a statement while ship &lt; 5, do something?  Any advice would be greatly appreciated.  Thank you!</p>
",https://stackoverflow.com/questions/75934801/simplifying-code-for-placing-ships-in-battleship-game-in-python-and-conducting-u,"['python-3.x', 'unit-testing', 'while-loop', 'simplify']",148,True,1,2
Why does mock has not reset in Jest for aws sdk v3 unit testing?,"<p>I am trying to unit test lambda function. I am using <a href=""https://aws.amazon.com/blogs/developer/mocking-modular-aws-sdk-for-javascript-v3-in-unit-tests/"" rel=""nofollow noreferrer"">aws-sdk-client-mock</a> library for mocking.</p>
<p>I am trying to test 5xx status code in my lambda. In order to test it I want to remove mock so that credential error (<code>CredentialsProviderError: Could not load credentials from any providers</code>)occurs ( which is obvious ). But since mock of first <code>describe</code> is still active I am not able to test it. How do I reset the mock for different describe test cases</p>
<p><strong>The only way I intend to work if I comment on the first describe block i.e don't use the mock at all.</strong></p>
<pre><code>import { APIGatewayProxyResult } from 'aws-lambda';
import { main } from &quot;../../lib/src/lambda/approval-handler&quot;;
import { mockClient } from &quot;aws-sdk-client-mock&quot;;
import {
    CodePipelineClient
} from &quot;@aws-sdk/client-codepipeline&quot;;
import { event, queryStringParameters } from &quot;../utils/lambda-event&quot;


describe(&quot;Successful Approve or Deny&quot;, () =&gt; {. //this works

    const pipelineClientMock = mockClient(CodePipelineClient);

    beforeEach(() =&gt; {
        pipelineClientMock.reset();
    });

    it(&quot;returns a 301 response with a redirect location if all required query parameters are provided&quot;, async () =&gt; {

        pipelineClientMock.resolves({})

        const result: APIGatewayProxyResult = await main(event);
        expect(result.statusCode).toEqual(301);
    });

})


describe(&quot;When Approval or Deny is not sent successfully&quot;, () =&gt; { //this fails because mock is still active

    it(&quot;returns a 502 error response if any of the required query parameters are missing&quot;, async () =&gt; {

        const result: APIGatewayProxyResult = await main(event);
        expect(result.statusCode).toEqual(502);
    });
});
</code></pre>
",https://stackoverflow.com/questions/75945593/why-does-mock-has-not-reset-in-jest-for-aws-sdk-v3-unit-testing,"['javascript', 'typescript', 'amazon-web-services', 'aws-lambda', 'jestjs']",236,True,1,1
Unit Testing Entity Framework Core DBContext using a Production Model (Context.Database.EnsureCreated) that contains views,"<p>I have a series of tests that are currently using the recommended practice for testing query logic here: <a href=""https://learn.microsoft.com/en-us/ef/core/testing/testing-with-the-database"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/ef/core/testing/testing-with-the-database</a>.  This has been working wonderfully but I've encountered a snag.  We have an existing database used by other products that has a view, this view handles a lot of boiler plate and I leave it in another teams hands to ensure it works correctly.  But One of my pieces of logic depends on it so I wanted to mock that view up similar to how I would any existing table, with some known &quot;good&quot; data to complete out my query testing.</p>
<p>Were I using an InMemory context Microsoft's suggestion would be to do something similar to:</p>
<pre><code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity&lt;ViewItem&gt;(entity =&gt;
    {
        if (!Database.IsInMemory())
        {
            entity.HasNoKey();
            entity.ToView(&quot;vTestView&quot;);
        }
        else
        {
            entity.HasKey(e =&gt; e.Name);
        }
    });
}
</code></pre>
<p>However as I am not using an InMemory database does anyone have any suggestion about best practices for mocking a DBContext view for testing purposes.
Example Fixture</p>
<pre><code>public TestDatabaseFixture()
    {
        lock (_lock)
        {
            if (!_databaseInitialized)
            {
                using (var context = CreateContext())
                {
                    context.Database.EnsureDeleted();
                    context.Database.EnsureCreated();

                    //populate database
                    PopulateTableOne(context);
                    PopulateTableTwo(context);
                    //Want to populate view with dummy data
                    PopulateViewOne(context)

                    context.SaveChanges();
                }

                _databaseInitialized = true;
            }
        }
    }

    public MyContext CreateContext()
        =&gt; new MyContext(
            new DbContextOptionsBuilder&lt;MyContext&gt;()
                .UseSqlServer(GetConnectionString())
                .Options);
</code></pre>
<p>Some other info:
Unit Testing Database is SQL Server Developer</p>
<p>So far my only idea is to explicitly check the connection string for a value during OnModelCreating to do something similar to the IsInMemory check (not tried if that actually works)</p>
",https://stackoverflow.com/questions/76156523/unit-testing-entity-framework-core-dbcontext-using-a-production-model-context-d,"['c#', 'entity-framework', 'unit-testing', '.net-core']",60,False,0,0
How do I use Jest and the Testing Library for unit testing in JavaScript?,"<p>I use Jest and dom testing library and I DON'T USE REACT.</p>
<p>Also I use webpack in my project. I keep on geting the same problem:</p>
<pre><code>expect(element).toBeInTheDocument()
element could not be found in the document
</code></pre>
<p>How can I test if a button is in the document? And how can I correctly test the modules of the project if I use static HTML with no scripts? Should I manually add the scripts? I do it for the first time, please help me</p>
<p>My test file:</p>
<pre><code>import { getByRole } from '@testing-library/dom';
import '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';

function getExampleDOM() {
  const div = document.createElement('div');
  div.innerHTML = `
      &lt;div class=&quot;screen&quot;&gt;
        &lt;h1 class=&quot;game__title&quot;&gt;GAME 2048&lt;/h1&gt;
        &lt;button type=&quot;button&quot; class=&quot;btn btn-start&quot;&gt;Start&lt;/button&gt;
      &lt;/div&gt;
      &lt;div class=&quot;screen&quot;&gt;
        &lt;h2 class=&quot;game__title&quot;&gt;Choose board size&lt;/h2&gt;
        &lt;ul class=&quot;size-list&quot;&gt;
          &lt;li&gt;
            &lt;button type=&quot;button&quot; class=&quot;btn btn-size&quot; data-size=&quot;3&quot;&gt;3 x 3&lt;/button&gt;
          &lt;/li&gt;
          &lt;li&gt;
            &lt;button type=&quot;button&quot; class=&quot;btn btn-size&quot; data-size=&quot;4&quot;&gt;4 x 4 (classic)&lt;/button&gt;
          &lt;/li&gt;
          &lt;li&gt;
            &lt;button type=&quot;button&quot; class=&quot;btn btn-size&quot; data-size=&quot;5&quot;&gt;5 x 5&lt;/button&gt;
          &lt;/li&gt;
        &lt;/ul&gt;
      &lt;/div&gt;
      &lt;div class=&quot;game__wrapper&quot;&gt;
        &lt;h2 class=&quot;game__score-title&quot;&gt;Your score:&lt;span class=&quot;game__score&quot;&gt;0&lt;/span&gt;&lt;/h2&gt;
        &lt;div class=&quot;game-board&quot;&gt;&lt;/div&gt;
      &lt;/div&gt;
  `;
  return div;
}

describe('startGame', () =&gt; {
  test('renders all necessary elements', () =&gt; {
    const container = getExampleDOM();
    const startBtn = getByRole(container, 'button', { name: /start/i });
    expect(startBtn).toBeInTheDocument();
  });
});

</code></pre>
<p>my package.json:</p>
<pre><code>{
  &quot;name&quot;: &quot;2048&quot;,
  &quot;version&quot;: &quot;1.0.0&quot;,
  &quot;repository&quot;: {
    &quot;url&quot;: &quot;https://github.com/EkaterinaMuz/GAME2048.git&quot;
  },
  &quot;description&quot;: &quot;&quot;,
  &quot;scripts&quot;: {
    &quot;test&quot;: &quot;jest --w&quot;,
    &quot;build&quot;: &quot;webpack --mode development&quot;,
    &quot;start&quot;: &quot;webpack-dev-server --mode development --open&quot;,
    &quot;predeploy&quot;: &quot;npm run build&quot;,
    &quot;deploy&quot;: &quot;gh-pages -d dist&quot;
  },
  &quot;keywords&quot;: [],
  &quot;author&quot;: &quot;&quot;,
  &quot;license&quot;: &quot;ISC&quot;,
  &quot;devDependencies&quot;: {
    &quot;@babel/eslint-parser&quot;: &quot;^7.21.8&quot;,
    &quot;@babel/polyfill&quot;: &quot;^7.12.1&quot;,
    &quot;@babel/preset-env&quot;: &quot;^7.21.5&quot;,
    &quot;@testing-library/user-event&quot;: &quot;^14.4.3&quot;,
    &quot;babel-loader&quot;: &quot;^9.1.2&quot;,
    &quot;clean-webpack-plugin&quot;: &quot;^4.0.0&quot;,
    &quot;css-loader&quot;: &quot;^6.7.4&quot;,
    &quot;eslint&quot;: &quot;^8.2.0&quot;,
    &quot;eslint-config-airbnb-base&quot;: &quot;^15.0.0&quot;,
    &quot;eslint-config-prettier&quot;: &quot;^8.8.0&quot;,
    &quot;eslint-plugin-import&quot;: &quot;^2.27.5&quot;,
    &quot;eslint-plugin-jest-dom&quot;: &quot;^4.0.3&quot;,
    &quot;eslint-plugin-prettier&quot;: &quot;^4.2.1&quot;,
    &quot;eslint-plugin-testing-library&quot;: &quot;^5.11.0&quot;,
    &quot;eslint-webpack-plugin&quot;: &quot;^4.0.1&quot;,
    &quot;file-loader&quot;: &quot;^6.2.0&quot;,
    &quot;gh-pages&quot;: &quot;^5.0.0&quot;,
    &quot;html-webpack-plugin&quot;: &quot;^5.5.1&quot;,
    &quot;jest&quot;: &quot;^29.5.0&quot;,
    &quot;jest-webpack&quot;: &quot;^0.5.1&quot;,
    &quot;style-loader&quot;: &quot;^3.3.3&quot;,
    &quot;webpack&quot;: &quot;^5.83.1&quot;,
    &quot;webpack-cli&quot;: &quot;^5.1.1&quot;,
    &quot;webpack-dev-server&quot;: &quot;^4.15.0&quot;
  },
  &quot;dependencies&quot;: {
    &quot;@testing-library/jest-dom&quot;: &quot;^5.16.5&quot;,
    &quot;hammerjs&quot;: &quot;^2.0.8&quot;,
    &quot;jest-environment-jsdom&quot;: &quot;^29.5.0&quot;
  }
}

</code></pre>
<p>Also I added Jest config</p>
<pre><code>const config = {
  testEnvironment: 'jsdom',
  testEnvironmentOptions: {
    html: '&lt;html lang=&quot;zh-cmn-Hant&quot;&gt;&lt;/html&gt;',
    url: 'https://jestjs.io/',
    userAgent: 'Agent/007',
  },
};

module.exports = config;

</code></pre>
<p>And also I have webpack in the project:</p>
<pre><code>const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// const ESLintPlugin = require('eslint-webpack-plugin');

module.exports = {
  mode: 'development',
  context: path.resolve(__dirname, 'src'),
  entry: ['@babel/polyfill', './scripts/index.js'],
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    assetModuleFilename: 'assets/[name][ext][query]',
  },
  devServer: {
    port: 3000,
  },
  plugins: [
    new HTMLWebpackPlugin({
      template: './index.html',
    }),
    new CleanWebpackPlugin(),
    // new ESLintPlugin({
    //   fix: true,
    // }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      // {
      //   test: /\.(png|jpg)$/,
      //   type: 'asset/resource',
      // },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
          },
        },
      },
    ],
  },
};

</code></pre>
<p>////////////////////////////////////</p>
",https://stackoverflow.com/questions/76354976/how-do-i-use-jest-and-the-testing-library-for-unit-testing-in-javascript,"['javascript', 'unit-testing', 'jestjs', 'testing-library']",24,False,0,0
How to get AAD user token for unit testing based on logged in user?,"<p>I have a service that needs to call a downstream service using AAD user token that I am trying to unit test.
I am logged into the Windows machine. Is it possible within xUnit to acquire a token based on logged in user on the machine or logged in user in Visual Studio?</p>
<p>I have tried code given below and it gives exception MsalClientException “WS-Trust endpoint not found in metadata document.”</p>
<p><a href=""https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/active-directory/develop/scenario-desktop-acquire-token-integrated-windows-authentication.md#net"" rel=""nofollow noreferrer"">https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/active-directory/develop/scenario-desktop-acquire-token-integrated-windows-authentication.md#net</a></p>
",https://stackoverflow.com/questions/76047152/how-to-get-aad-user-token-for-unit-testing-based-on-logged-in-user,['azure-ad-msal'],30,False,0,0
Why does the unit testing of a shiny app return no passing or failure?,"<p>I have an R shiny app with two modules. I want to test the <code>dataselect-and-table_module</code>module using <code>testthat</code> package. The problem is that when I test the module, it returns not a success status nor a failed one. It returns just below results:</p>
<pre><code>-- Warning (Line 2): the right rows of data are selected  ----------------------
The select input &quot;speciesName&quot; contains a large number of options; consider using server-side selectize for massively improved performance. See the Details section of the ?selectizeInput help topic.
Backtrace:
  1. shiny::testServer(...)
 22. session$setInputs(speciesNametype = &quot;Scientific Name&quot;, speciesName = &quot;Aix galericulata&quot;)
 23. self$setInputs(!!!mapNames(ns, rlang::dots_list(..., .homonyms = &quot;error&quot;)))
 24. private$flush()
 25. shiny:::flushReact()
 26. .getReactiveEnvironment()$flush()
 27. ctx$executeFlushCallbacks()
 28. base::lapply(...)
 29. shiny:::FUN(X[[i]], ...)
 30. shiny:::flushCallback()
     ...
 61. shiny:::do()
 70. base::Reduce(...)
 71. shiny:::f(init, x[[i]])
 73. shiny:::func(v$value)
 86. shiny:::valueFunc()
 87. shiny:::`&lt;observer:observeEvent(input$speciesNametype)&gt;`(...)
 88. observe()
 89. shiny::updateSelectizeInput(...)
 90. shiny::updateSelectInput(session, inputId, label, choices, selected)
 91. shiny:::selectOptions(choices, selected, inputId, FALSE)
</code></pre>
<p>I tried to create a minimal example of my app and I created it but unfortunately, when I use <code>dput()</code> function for data, the test passes successfully and it returns a test passed message!</p>
<p>So I have to put my test code and my app code in two conditions:</p>
<p>1-Using <code>dput()</code> function for reproducing data that passes the test</p>
<p>and,</p>
<p>2-Using the original data. When I use this CSV file, the test returns nothing.</p>
<p>I know you can not reproduce the problem but I thought to ask my question hopefully someone knows the issue by looking at the codes. I appreciate any help.</p>
<p>This is the <code>app.R</code>:</p>
<pre><code># Call packages
library(shiny)
library(tidyverse)
library(DT)
library(data.table)
library(shiny)
library(ggplot2)
library(plotly)
library(reshape2)

# App
myApp &lt;- function(...) {
  
# Call modules
source('R/dataselect-and-table_module.R')
source('R/plot_module.R')
ui&lt;- fluidPage(
            dataselect_ui(&quot;dataselect&amp;table&quot;),
            plot_ui(&quot;timeline&quot;)
)
                  
server &lt;- function(session,input, output) { 

  dataselect_outputs &lt;- dataselect_server(&quot;dataselect&amp;table&quot;)
  plot_server(&quot;timeline&quot;,speciesName2 = dataselect_outputs$speciesName2
                  ,finalDf2= dataselect_outputs$finalDf2)
}

shinyApp(ui = ui, server = server,...)
}
</code></pre>
<p><strong>1-Using <code>dput()</code> function for reproducing data that passes the test</strong></p>
<p>The <code>dataselect-and-table_module.R</code>:</p>
<pre><code># Dataselect and table module
dataselect_ui&lt;- function(id) {
  ns&lt;-NS(id)
  tagList(

    
    selectInput(ns(&quot;speciesNametype&quot;),
                &quot;Select a name type&quot;,
                choices=c(&quot;Vernacular Name&quot;,&quot;Scientific Name&quot;,&quot;choose&quot;),selected = &quot;choose&quot;),
    
    selectInput(ns(&quot;speciesName&quot;),
                &quot;Select a species name&quot;,
                choices=&quot;&quot;,selected = &quot;&quot;,selectize=TRUE),
    
    DT::DTOutput(ns(&quot;tab&quot;))
  )
}


dataselect_server&lt;- function(id) {
  moduleServer(id, function(input, output, session) {
    
    # Import data
    df&lt;-structure(list(country = c(&quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, 
    &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, 
    &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;), 
    scientificName = c(&quot;Aix galericulata&quot;, &quot;Abraxas sylvata&quot;, 
    &quot;Abraxas sylvata&quot;, &quot;Aix galericulata&quot;, &quot;Aix galericulata&quot;, 
    &quot;Aix galericulata&quot;, &quot;Aix galericulata&quot;, &quot;Aix galericulata&quot;, 
    &quot;Aix galericulata&quot;, &quot;Aix galericulata&quot;, &quot;Aix galericulata&quot;, 
    &quot;Abraxas sylvata&quot;, &quot;Abraxas sylvata&quot;, &quot;Aix galericulata&quot;, 
    &quot;Abraxas sylvata&quot;, &quot;Aix galericulata&quot;, &quot;Aix galericulata&quot;
    ), vernacularName = c(&quot;Mandarin Duck&quot;, &quot;Clouded Magpie&quot;, 
    &quot;Clouded Magpie&quot;, &quot;Mandarin Duck&quot;, &quot;Mandarin Duck&quot;, &quot;Mandarin Duck&quot;, 
    &quot;Mandarin Duck&quot;, &quot;Mandarin Duck&quot;, &quot;Mandarin Duck&quot;, &quot;Mandarin Duck&quot;, 
    &quot;Mandarin Duck&quot;, &quot;Clouded Magpie&quot;, &quot;Clouded Magpie&quot;, &quot;Mandarin Duck&quot;, 
    &quot;Clouded Magpie&quot;, &quot;Mandarin Duck&quot;, &quot;Mandarin Duck&quot;), eventDate = c(&quot;2015-03-11&quot;, 
    &quot;2011-08-04&quot;, &quot;2011-06-04&quot;, &quot;2019-12-26&quot;, &quot;2019-12-26&quot;, &quot;2019-10-31&quot;, 
    &quot;2019-05-08&quot;, &quot;2019-05-09&quot;, &quot;2019-04-27&quot;, &quot;2019-04-06&quot;, &quot;2018-07-11&quot;, 
    &quot;2018-05-26&quot;, &quot;2018-05-26&quot;, &quot;2017-12-26&quot;, &quot;2009-06-19&quot;, &quot;2015-10-22&quot;, 
    &quot;2015-03-25&quot;), eventTime = c(&quot;23:16&quot;, &quot;&quot;, &quot;&quot;, &quot;12:13&quot;, &quot;12:17&quot;, 
    &quot;14:54&quot;, &quot;18:30&quot;, &quot;11:35&quot;, &quot;17:42&quot;, &quot;10:43&quot;, &quot;&quot;, &quot;11:26&quot;, 
    &quot;11:34&quot;, &quot;11:39&quot;, &quot;&quot;, &quot;11:35&quot;, &quot;&quot;), longitudeDecimal = c(21.0356, 
     22.4148130417, 22.5681712904, 21.0350456237793, 21.0350494384766, 
     21.031685, 21.02606356, 21.0299701690674, 21.0350360870361, 
     21.03162158532, 21.03544235, 19.2465686798096, 19.2464962005615, 
     21.06793027, 19.59746361, 19.9347, 21.0313155502), latitudeDecimal = c(52.2138, 
     53.1927451137, 53.3849176394, 52.209789276123, 52.2097434997559, 
     52.226701, 52.2213975, 52.2470512390137, 52.2153434753418, 
     52.2127014708867, 52.215017, 50.6236457824707, 50.6240653991699, 
     52.24251119, 49.50832413, 50.0478, 52.2151995436), individualCount = c(1L, 
     1L, 1L, 10L, 41L, 20L, 10L, 1L, 10L, 3L, 1L, 1L, 1L, 8L, 
     1L, 1L, 20L)), row.names = c(1L, 11527L, 12407L, 16005L, 
     16006L, 16045L, 19163L, 19830L, 20050L, 21002L, 22155L, 24666L, 
     24737L, 27988L, 28060L, 43210L, 48415L), class = &quot;data.frame&quot;)
    
    colnames(df)&lt;-c(&quot;Country&quot;,&quot;Scientific Name&quot;, &quot;Vernacular Name&quot;,&quot;Event Date&quot;,&quot;Event 
    Time&quot;,&quot;Longitude Decimal&quot;,&quot;Latitude Decimal&quot;,&quot;Individual Count&quot;)
    rownames(df) &lt;- NULL
    df&lt;-df[-1]
    
    # Put columns Vernacular Name and Scientific Name of df in one column called &quot;Name Type&quot; using melt()function
    # This format of data is needed for the choices argument of updateSelectizeInput()
    df2&lt;-reshape2::melt(df,id=c(&quot;Event Date&quot;,&quot;Event Time&quot;,&quot;Longitude Decimal&quot;,&quot;Latitude Decimal&quot;,&quot;Individual Count&quot;))
    colnames(df2)&lt;-c(&quot;Event Date&quot;,&quot;Event Time&quot;,&quot;Longitude Decimal&quot;,&quot;Latitude Decimal&quot;,&quot;Individual Count&quot;,&quot;Name Type&quot;,&quot;Species Names&quot;)
    
    # Update the second selectInput depending on the first one
    observeEvent(
                input$speciesNametype,
                updateSelectizeInput(session, &quot;speciesName&quot;, &quot;Select a species name&quot;, 
                                    choices = unique(df2$`Species Names`[df2$`Name Type`==input$speciesNametype]),selected = &quot;&quot;))
    
    
    # finalDf() is the data used to plot the table, map, and timeline
    finalDf&lt;-reactive({
      if(input$speciesName==&quot;choose&quot;){
        return(NULL)
        
      }
      if(input$speciesName==&quot;&quot;){
        return(NULL)
        
      }
      if(input$speciesNametype==&quot;choose&quot;){
        return(NULL)
        
      } 
      # if the first selectInput is set to Vernacular Name, select rows from df that their Vernacular Name column is 
      # equal to the second selectInput value
      else if(input$speciesNametype==&quot;Vernacular Name&quot;){
        finalDf&lt;-df[which(df$`Vernacular Name`==input$speciesName) ,]
        
      }
      # if the first selectInput is set to Scientific Name, select rows from df that their Scientific Name column is 
      # equal to the second selectInput value
      else if(input$speciesNametype==&quot;Scientific Name&quot;){
        finalDf&lt;-df[which(df$`Scientific Name`==input$speciesName) ,]
        
      } 
      return(finalDf)
    })
    
    # Plot table
    output$tab&lt;-DT::renderDT({
      req(input$speciesName)
      datatable(finalDf(),
                filter = 'top', 
                options = list(pageLength = 5, autoWidth = TRUE),
                rownames= FALSE)
    })
    return(
      list(&quot;finalDf2&quot; = finalDf, &quot;speciesName2&quot; = reactive(input$speciesName))
    )
  })
}

</code></pre>
<p>The <code>test.R</code>:</p>
<pre><code>library(testthat)
library(shiny)
library(shinytest)
library(readr)
test_that(&quot;the right rows of data are selected &quot;, {
  testServer(dataselect_server, {
    session$setInputs(speciesNametype =&quot;Scientific Name&quot;, speciesName=&quot;Aix galericulata&quot;)
    dfex &lt;-structure(list(country = c(&quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, 
    &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, 
    &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;, &quot;Poland&quot;), 
    scientificName = c(&quot;Aix galericulata&quot;, &quot;Abraxas sylvata&quot;, 
    &quot;Abraxas sylvata&quot;, &quot;Aix galericulata&quot;, &quot;Aix galericulata&quot;, 
    &quot;Aix galericulata&quot;, &quot;Aix galericulata&quot;, &quot;Aix galericulata&quot;, 
    &quot;Aix galericulata&quot;, &quot;Aix galericulata&quot;, &quot;Aix galericulata&quot;, 
    &quot;Abraxas sylvata&quot;, &quot;Abraxas sylvata&quot;, &quot;Aix galericulata&quot;, 
    &quot;Abraxas sylvata&quot;, &quot;Aix galericulata&quot;, &quot;Aix galericulata&quot;
    ), vernacularName = c(&quot;Mandarin Duck&quot;, &quot;Clouded Magpie&quot;, 
    &quot;Clouded Magpie&quot;, &quot;Mandarin Duck&quot;, &quot;Mandarin Duck&quot;, &quot;Mandarin Duck&quot;, 
    &quot;Mandarin Duck&quot;, &quot;Mandarin Duck&quot;, &quot;Mandarin Duck&quot;, &quot;Mandarin Duck&quot;, 
    &quot;Mandarin Duck&quot;, &quot;Clouded Magpie&quot;, &quot;Clouded Magpie&quot;, &quot;Mandarin Duck&quot;, 
    &quot;Clouded Magpie&quot;, &quot;Mandarin Duck&quot;, &quot;Mandarin Duck&quot;), eventDate = c(&quot;2015-03-11&quot;, 
    &quot;2011-08-04&quot;, &quot;2011-06-04&quot;, &quot;2019-12-26&quot;, &quot;2019-12-26&quot;, &quot;2019-10-31&quot;, 
    &quot;2019-05-08&quot;, &quot;2019-05-09&quot;, &quot;2019-04-27&quot;, &quot;2019-04-06&quot;, &quot;2018-07-11&quot;, 
    &quot;2018-05-26&quot;, &quot;2018-05-26&quot;, &quot;2017-12-26&quot;, &quot;2009-06-19&quot;, &quot;2015-10-22&quot;, 
    &quot;2015-03-25&quot;), eventTime = c(&quot;23:16&quot;, &quot;&quot;, &quot;&quot;, &quot;12:13&quot;, &quot;12:17&quot;, 
    &quot;14:54&quot;, &quot;18:30&quot;, &quot;11:35&quot;, &quot;17:42&quot;, &quot;10:43&quot;, &quot;&quot;, &quot;11:26&quot;, 
    &quot;11:34&quot;, &quot;11:39&quot;, &quot;&quot;, &quot;11:35&quot;, &quot;&quot;), longitudeDecimal = c(21.0356, 
    22.4148130417, 22.5681712904, 21.0350456237793, 21.0350494384766, 
    21.031685, 21.02606356, 21.0299701690674, 21.0350360870361, 
    21.03162158532, 21.03544235, 19.2465686798096, 19.2464962005615, 
    21.06793027, 19.59746361, 19.9347, 21.0313155502), latitudeDecimal = c(52.2138, 
    53.1927451137, 53.3849176394, 52.209789276123, 52.2097434997559, 
    52.226701, 52.2213975, 52.2470512390137, 52.2153434753418, 
    52.2127014708867, 52.215017, 50.6236457824707, 50.6240653991699, 
    52.24251119, 49.50832413, 50.0478, 52.2151995436), individualCount = c(1L, 
    1L, 1L, 10L, 41L, 20L, 10L, 1L, 10L, 3L, 1L, 1L, 1L, 8L, 
    1L, 1L, 20L)), row.names = c(1L, 11527L, 12407L, 16005L, 
    16006L, 16045L, 19163L, 19830L, 20050L, 21002L, 22155L, 24666L, 
    24737L, 27988L, 28060L, 43210L, 48415L), class = &quot;data.frame&quot;)
    colnames(dfex)&lt;-c(&quot;Country&quot;,&quot;Scientific Name&quot;, &quot;Vernacular Name&quot;,&quot;Event Date&quot;,&quot;Event Time&quot;,&quot;Longitude Decimal&quot;,&quot;Latitude Decimal&quot;,&quot;Individual Count&quot;)
    dfex&lt;-dfex[-1]
    rownames(dfex) &lt;- NULL
    dfex&lt;-dfex[dfex$`Scientific Name`==&quot;Aix galericulata&quot;,]
    expect_true(identical(finalDf(), dfex))
  })
})
</code></pre>
<p><strong>2-Using the original data. When I use this CSV file, the test returns nothing.</strong></p>
<p>The <code>dataselect-and-table_module.R</code>:</p>
<pre><code># Dataselect and table module
dataselect_ui&lt;- function(id) {
  ns&lt;-NS(id)
  tagList(

    
    selectInput(ns(&quot;speciesNametype&quot;),
                &quot;Select a name type&quot;,
                choices=c(&quot;Vernacular Name&quot;,&quot;Scientific Name&quot;,&quot;choose&quot;),selected = &quot;choose&quot;),
    
    selectInput(ns(&quot;speciesName&quot;),
                &quot;Select a species name&quot;,
                choices=&quot;&quot;,selected = &quot;&quot;,selectize=TRUE),
    
    DT::DTOutput(ns(&quot;tab&quot;))
  )
}


dataselect_server&lt;- function(id) {
  moduleServer(id, function(input, output, session) {
    
    # Import data
    df&lt;- dfex &lt;-read.csv(&quot;R/www/polData.csv&quot;)
    colnames(df)&lt;-c(&quot;Country&quot;,&quot;Scientific Name&quot;, &quot;Vernacular Name&quot;,&quot;Event Date&quot;,&quot;Event Time&quot;,&quot;Longitude Decimal&quot;,&quot;Latitude Decimal&quot;,&quot;Individual Count&quot;)
    rownames(df) &lt;- NULL
    df&lt;-df[-1]
    
    # Put columns Vernacular Name and Scientific Name of df in one column called &quot;Name Type&quot; using melt()function
    # This format of data is needed for the choices argument of updateSelectizeInput()
    df2&lt;-reshape2::melt(df,id=c(&quot;Event Date&quot;,&quot;Event Time&quot;,&quot;Longitude Decimal&quot;,&quot;Latitude Decimal&quot;,&quot;Individual Count&quot;))
    colnames(df2)&lt;-c(&quot;Event Date&quot;,&quot;Event Time&quot;,&quot;Longitude Decimal&quot;,&quot;Latitude Decimal&quot;,&quot;Individual Count&quot;,&quot;Name Type&quot;,&quot;Species Names&quot;)
    
    # Update the second selectInput depending on the first one
    observeEvent(
                input$speciesNametype,
                updateSelectizeInput(session, &quot;speciesName&quot;, &quot;Select a species name&quot;, 
                                    choices = unique(df2$`Species Names`[df2$`Name Type`==input$speciesNametype]),selected = &quot;&quot;))
    
    
    # finalDf() is the data used to plot the table, map, and timeline
    finalDf&lt;-reactive({
      if(input$speciesName==&quot;choose&quot;){
        return(NULL)
        
      }
      if(input$speciesName==&quot;&quot;){
        return(NULL)
        
      }
      if(input$speciesNametype==&quot;choose&quot;){
        return(NULL)
        
      } 
      # if the first selectInput is set to Vernacular Name, select rows from df that their Vernacular Name column is 
      # equal to the second selectInput value
      else if(input$speciesNametype==&quot;Vernacular Name&quot;){
        finalDf&lt;-df[which(df$`Vernacular Name`==input$speciesName) ,]
        
      }
      # if the first selectInput is set to Scientific Name, select rows from df that their Scientific Name column is 
      # equal to the second selectInput value
      else if(input$speciesNametype==&quot;Scientific Name&quot;){
        finalDf&lt;-df[which(df$`Scientific Name`==input$speciesName) ,]
        
      } 
      return(finalDf)
    })
    
    # Plot table
    output$tab&lt;-DT::renderDT({
      req(input$speciesName)
      datatable(finalDf(),
                filter = 'top', 
                options = list(pageLength = 5, autoWidth = TRUE),
                rownames= FALSE)
    })
    return(
      list(&quot;finalDf2&quot; = finalDf, &quot;speciesName2&quot; = reactive(input$speciesName))
    )
  })
}
</code></pre>
<p>The <code>test.R</code>:</p>
<pre><code>library(testthat)
library(shiny)
library(shinytest)
library(readr)
test_that(&quot;the right rows of data are selected &quot;, {
  testServer(dataselect_server, {
    session$setInputs(speciesNametype =&quot;Scientific Name&quot;, speciesName=&quot;Aix galericulata&quot;)
    dfex &lt;-read.csv(&quot;R/www/polData.csv&quot;)
    colnames(dfex)&lt;-c(&quot;Country&quot;,&quot;Scientific Name&quot;, &quot;Vernacular Name&quot;,&quot;Event Date&quot;,&quot;Event Time&quot;,&quot;Longitude Decimal&quot;,&quot;Latitude Decimal&quot;,&quot;Individual Count&quot;)
    dfex&lt;-dfex[-1]
    rownames(dfex) &lt;- NULL
    dfex&lt;-dfex[dfex$`Scientific Name`==&quot;Aix galericulata&quot;,]
    expect_true(identical(finalDf(), dfex))
  })
})
</code></pre>
",https://stackoverflow.com/questions/75223072/why-does-the-unit-testing-of-a-shiny-app-return-no-passing-or-failure,"['r', 'unit-testing', 'shiny', 'shinyapps']",74,False,0,0
"Python import works either in unit testing, or in package environment, but not both","<p>This problem has been eating away at me for a while. For some reason, the way I import my modules works only either for testing or for library usage. Both times the error is a Module not found error. Say I have the following Python repo:</p>
<pre><code>- src
  - example
    - dir
      - internal.py
      - __init__.py
    - main.py
    - __init__.py
- test
  - test_main.py
  - __init__.py
- setup.cfg
- setup.py
</code></pre>
<p>Within <code>setup.cfg</code>, I have:</p>
<pre><code>[metadata]
name = wf
version = 1.0.0

[options]
include_package_data = True
packages = find:

[options.packages.find]
where=src
</code></pre>
<p>I don't want the user to import from <code>src</code>, but instead import from <code>example</code>. After all, nobody imports from <code>src</code>, and this is the conventional structure, right?</p>
<p>However, now I've been encountering 2 types of errors, depending on my choice:</p>
<h2>Choice 1</h2>
<p>For python files in <code>src</code> and <code>test</code>, all imports are of the form <code>from src.example.... import ...</code>. In this case, unit tests work without issues, in particular <code>python -m unittest discover test</code>. However, if I create a virtual environment in a separate directory, and pip install this directory and run</p>
<pre><code># script.py
from example.main import ...
# code that calls functions in main that import from internal.py
</code></pre>
<p>I encounter <code>ModuleNotFoundError: no module named 'dir'</code>. Only if I remove the <code>src</code> from imports do I avoid this issue.</p>
<h2>Choice 2</h2>
<p>I'm guessing the error is because of how I defined the setup in my <code>cfg</code> file, so I remove <code>src</code> from <code>src.example.... import ...</code> within the example directory. But now, my unit tests fail! This time, the error is <code>ModuleNotFoundError: No module named 'dir'</code>.</p>
<hr />
<p>I've looked into some other options.</p>
<ul>
<li>Relative imports: I've heard relative imports are fragile, so I avoid them in favor of absolute imports, which IDEs like PyCharm support very easily.</li>
<li>Sys add path: I've heard that people have complained about how this is a wordy solution, and it is not agnostic, and I agree since I plan to scale up testing, so I would like to avoid it too if possible. I'm referring to <a href=""https://stackoverflow.com/questions/4761041/python-import-src-modules-when-running-tests"">this</a> post. I'm also aware of the 'nose' suggestion underneath, but do we really need a 3rd party for this?</li>
</ul>
<p>This has to be a commonly encountered issue... if someone knows where the fix lies, or if there is some template example Python repository which addresses these concerns, I'd be very thankful!</p>
",https://stackoverflow.com/questions/75443254/python-import-works-either-in-unit-testing-or-in-package-environment-but-not-b,"['python', 'import']",74,False,0,0
How to unit testing by mock methods in for a Vue component using ViTest?,"<p>Unit test vue component by mocking methods using vitest.</p>
<p><em>MyComponent.vue</em></p>
<pre><code>&lt;script setup&gt;
import { ref } from &quot;vue&quot;;

const isSelectAll = ref(true);
const selectAllModel = ref(false);

const onChange = () =&gt; {
    isSelectAll.value = true;
    selectAllModel.value = false;
};
const onVisibleChange = () =&gt; {
  // do something than call
  onChange();
};
&lt;/script&gt;
</code></pre>
<p>I want to unit test method <code>onVisibleChange</code> by mocking <code>onChange</code> and check that <code>onChange</code> has been called.</p>
<p><em>MyComponent.spec.js</em></p>
<pre><code>import { mount } from 'vitest';
import { ref } from 'vue';
import MyComponent from './MyComponent.vue';

describe('MyComponent', () =&gt; {
  const wrapper = shallowMount(MyComponent);
  const spy = vi.spyOn(wrapper.vm, 'onChange');
  wrapper.vm.onVisibleChange();
  expect(spy).toHaveBeenCalled();
  expect(wrapper.vm.onChange).toHaveBeenCalled();
  // Both the expect gives error: AssertionError: expected &quot;onChange&quot; to be called at least once

  //Also tried
  const mock = vi.fn();
  wrapper.vm.onChange = mock;
  wrapper.vm.onVisibleChange();
  expect(mock).toHaveBeenCalled();   // AssertionError: expected &quot;spy&quot; to be called at least once
  expect(wrapper.vm.onChange).toHaveBeenCalled();  // TypeError: [Function onChange] is not a spy or a call to a spy!

})

</code></pre>
",https://stackoverflow.com/questions/76364573/how-to-unit-testing-by-mock-methods-in-for-a-vue-component-using-vitest,"['vue.js', 'vuejs3', 'tdd', 'vue-test-utils', 'vitest']",41,False,0,0
How to verify OceanBase Community Edition Patch through Unit Testing before submitting pull request?,"<p>I am working on contributing code to the OceanBase community edition and have created a patch. I am using the latest version of the OceanBase community edition and am working in a CentOS environment. I have prepared the code for unit testing and would like to verify my patch before submitting a pull request on GitHub.</p>
<p>Are there any pre-build scripts or shell commands available for running unit tests? Or, should I go through the CMake process first?</p>
<p>I want to ensure that everything runs smoothly during the unit test phase before submitting my patch. Thank you for your help.</p>
",https://stackoverflow.com/questions/76125776/how-to-verify-oceanbase-community-edition-patch-through-unit-testing-before-subm,"['github', 'cmake', 'pull-request', 'oceanbase']",15,False,0,0
Why am I getting a &quot;Not Implemented&quot; error when unit testing firebase security rules?,"<p>I am writing firebase storage security rules, and unit testing them with &quot;@firebase/rules-unit-testing&quot;. When running the tests, I get the following error:</p>
<pre><code>Not Implemented

      at node_modules/@firebase/rules-unit-testing/src/impl/rules.ts:64:11
      at step (node_modules/@firebase/rules-unit-testing/dist/index.cjs.js:74:23)
      at Object.next (node_modules/@firebase/rules-unit-testing/dist/index.cjs.js:55:53)
      at fulfilled (node_modules/@firebase/rules-unit-testing/dist/index.cjs.js:45:58)
      at tryCallOne (node_modules/promise/lib/core.js:37:12)
      at node_modules/promise/lib/core.js:123:15
      at flush (node_modules/asap/raw.js:50:29)
</code></pre>
<p>The only unit test I have currently is supposed to confirm that users cannot delete files.</p>
<p>Here is my code:</p>
<pre class=""lang-js prettyprint-override""><code>import {
  assertFails,
  assertSucceeds,
  initializeTestEnvironment,
  RulesTestEnvironment,
} from &quot;@firebase/rules-unit-testing&quot;;
import {
  deleteObject,
  ref,
  uploadBytes,
} from &quot;firebase/storage&quot;;
import * as fs from &quot;fs&quot;;
const PROJECT_ID = &quot;iurn-973d0&quot;;
let testEnv: RulesTestEnvironment;

describe(&quot;Firebase storage security rules&quot;, () =&gt; {
  beforeAll(async () =&gt; {
    testEnv = await initializeTestEnvironment({
      projectId: PROJECT_ID,
      firestore: {
        rules: fs.readFileSync(__dirname + &quot;/../storage.rules&quot;, &quot;utf-8&quot;),
        host: &quot;127.0.0.1&quot;,
        port: 9199,
      },
    });
  });
  beforeEach(async () =&gt; {
    if(!testEnv) return
    testEnv.clearStorage();
  });

  it(&quot;DOES NOT allow deletion&quot;, async () =&gt; {
    if(!testEnv) return
    const storage = testEnv.authenticatedContext(&quot;user123&quot;).storage();
    await testEnv.withSecurityRulesDisabled(async (context) =&gt; {
      await uploadBytes(ref(context.storage(), &quot;hi.jpg&quot;), require(&quot;../assets/images/placeholder.png&quot;))
    })
    expect(assertFails(deleteObject(ref(storage, &quot;hi.jpg&quot;)))).resolves.toBeTruthy()
  })

  afterAll(async () =&gt; {
    if(!testEnv) return
    testEnv.cleanup();
  });
});
</code></pre>
",https://stackoverflow.com/questions/75441714/why-am-i-getting-a-not-implemented-error-when-unit-testing-firebase-security-r,"['firebase', 'unit-testing', 'jestjs', 'firebase-storage', 'firebase-security']",102,False,4,0
How to unit testing for json file is loaded in django views.py,"<p>I want to unit testing for json file is opened in <code>views.py</code> in django</p>
<pre><code>def get_json_data():
    json_data = json.load(open(JSON_DIRECTORY+'my.json'))
    return json_data
</code></pre>
<p>Please help me how to unit testing for <code>json</code> file is loaded or not</p>
<pre><code>def test_read_file_data(self):

    def read_file_data(filename, path):
        os.chdir(path)
        with open(filename,  encoding=&quot;utf8&quot;) as data_file:
            json_data = json.load(data_file)
        return json_data

    sample_json = {

    }
    sample_json = json.dumps(sample_json, ensure_ascii=False)
    path = my file path
    filename = real file
    self.assertEqual(read_file_data(filename, path), sample_json)
</code></pre>
<p>In <code>json</code> there is <code>null</code> as well so I do not know how to deal with the <code>null</code></p>
",https://stackoverflow.com/questions/75808038/how-to-unit-testing-for-json-file-is-loaded-in-django-views-py,"['python', 'django', 'unit-testing']",44,False,0,1
Get function for searching is not giving the search result but returning all the elements while unit testing,"<p>I have a function called GetAuthors which takes an expression for checking if given string is in authors names. I have problems while unit testing. The function supposed to find names that contains the given string but I realized it always returns everything in the list. I tested with G letter it supposed to fail but it passes. I have only found examples with no parameters for get functions unit testing. I am new to unit testing in web api. I share the code below.</p>
<p>Test function:</p>
<pre><code>[Test]
    public async Task AuthorHandler_GetAuthors_ReturnsAuthors()
    {
        var handler = new GetAuthorsHandler(_authorRepositoryMock.Object, _mapper);
        var authors = new List&lt;Author&gt; { 
            new Author{Id = 2, Name = &quot;Orhan&quot;, Surname = &quot;Pamuk&quot;},
            new Author{Id = 3, Name = &quot;Patti&quot;, Surname = &quot;Smith&quot;},
            new Author{Id = 1, Name = &quot;J.R.R.&quot;, Surname = &quot;Tolkien&quot;}

        };
        
        string str = &quot;G&quot;;
        str=str.Trim().ToUpper();
        _authorRepositoryMock.Setup(r =&gt; r.GetAuthors(It.IsAny&lt;Expression&lt;Func&lt;Author, bool&gt;&gt;&gt;()))
            .ReturnsAsync(authors);

        //Act
        var result = await handler.Handle(new GetAuthorsQuery(str), CancellationToken.None);
        
        //Assert
        Assert.AreNotEqual(0, result.Count());

    }
</code></pre>
<p>GetAuthors function in repository:</p>
<pre><code>public async Task&lt;IEnumerable&lt;Author&gt;&gt; GetAuthors(Expression&lt;Func&lt;Author, bool&gt;&gt; pred = null)
    {
        if (pred == null) return await _context.Authors.Include(a =&gt; a.Book).ToListAsync();
        else return await _context.Authors.Where(pred).Include(b =&gt; b.Book).ToListAsync();
    }
</code></pre>
<p>Handler:</p>
<pre><code>   public async Task&lt;IEnumerable&lt;AuthorDto&gt;&gt; Handle(GetAuthorsQuery request, CancellationToken cancellationToken)
    {
        IEnumerable&lt;Author&gt; authors;
        if (request.Str != null)
        {
            request.Str = request.Str.Trim().ToUpper();
            authors = await _authorRepository.GetAuthors(x =&gt; x.Name.Trim().ToUpper().Contains(request.Str));
        }
        else { authors = await _authorRepository.GetAuthors(null); }
        
        if (authors == null) return null;
        return _mapper.Map&lt;List&lt;AuthorDto&gt;&gt;(authors);
    }
</code></pre>
",https://stackoverflow.com/questions/75917347/get-function-for-searching-is-not-giving-the-search-result-but-returning-all-the,"['c#', 'unit-testing', 'asp.net-core-webapi', 'nunit', 'web-api-testing']",32,True,0,1
Java Unit Testing Http Get test user auto generate,"<p>I write function in rest to automatically generate user with admin role. Here's the function:</p>
<p>UserController.java</p>
<pre class=""lang-java prettyprint-override""><code>@RestController
@RequestMapping(&quot;users&quot;)
public class UserController {

    @Autowired
    private UserRepository userRepo;
    @Autowired
    private TokenRepository tokenRepo;
    
    @GetMapping(&quot;admin&quot;)
    public String getAdmin () {
        JSONObject report = new JSONObject();
        String dataAdmin = userRepo.findByUsername(&quot;admin&quot;);
        if(dataAdmin == null) {
            User myadmin = new User();
            myadmin.setUsername(&quot;admin&quot;);
            myadmin.setFirstname(&quot;admin&quot;);
            myadmin.setLastname(&quot;admin&quot;);
            myadmin.setEmail(&quot;admin@admin&quot;);
            myadmin.setRole(&quot;admin&quot;);
            userRepo.save(myadmin);
            report.put(&quot;message&quot;, &quot;admin generated&quot;);
        } else {
            report.put(&quot;message&quot;, &quot;admin only generated once&quot;);
        }
        return report.toString();
    }
</code></pre>
<p>I am trying to follow the instruction from here <a href=""https://www.springboottutorial.com/unit-testing-for-spring-boot-rest-services"" rel=""nofollow noreferrer"">https://www.springboottutorial.com/unit-testing-for-spring-boot-rest-services</a>.
In <em>Unit Testing Http Get Operation</em> section. I am getting several problem and also trying the different solution until I meet this <a href=""https://stackoverflow.com/questions/63008254/unit-testing-a-get-request-in-a-spring-project"">Unit testing a Get request in a spring project</a> from stackoverflow.
below is the testing script I've make so far.</p>
<pre class=""lang-java prettyprint-override""><code>package blablaaa.order;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import blablaaa.order.controller.UserController;
import blablaaa.order.dao.UserRepository;
import blablaaa.order.model.User;

//@ExtendWith(SpringExtension.class)
//@SpringBootTest
@WebMvcTest(value = UserController.class)
class OrderApplicationTests {
//  
    @Autowired
    private MockMvc mockMvc;
    
    @MockBean
    private UserRepository userRepo;

    @Test
    void contextLoads() throws Exception{

        User myadmin = new User();
        myadmin.setUsername(&quot;admin&quot;);
        myadmin.setFirstname(&quot;admin&quot;);
        myadmin.setLastname(&quot;admin&quot;);
        myadmin.setEmail(&quot;admin@admin&quot;);
        myadmin.setRole(&quot;admin&quot;);
        
        List&lt;User&gt; myUser = new ArrayList&lt;&gt;();
        myUser.add(myadmin);
        RequestBuilder rb = MockMvcRequestBuilders.get(&quot;/users/admin&quot;).accept(MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc.perform(rb).andReturn();
        JSONObject expect = new JSONObject();
        expect.put(&quot;message&quot;, &quot;admin generated&quot;);
//      System.out.println(result.toString());
        System.out.println(expect.toString());
//      Assertions.assertTrue(result.toString().contains(expect.toString()));
    }

}
</code></pre>
<p>I dont know, how the testing should be written. any keyword related to this?</p>
<p>[update]<br />
Here's my main:</p>
<pre class=""lang-java prettyprint-override""><code>// OrderApplication.java
@SpringBootApplication
@EnableMongoRepositories(&quot;blablaaa.order.dao&quot;)
public class OrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }

}
</code></pre>
<p>Here's my program error log</p>
<pre><code>Description:

Field tokenRepo in blablaaa.order.controller.UserController required a bean named 'mongoTemplate' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean named 'mongoTemplate' in your configuration.
</code></pre>
",https://stackoverflow.com/questions/75173863/java-unit-testing-http-get-test-user-auto-generate,"['java', 'spring', 'unit-testing']",58,True,0,2
Fastapi Testclient not able to send POST request using form-data,"<p>Currently I am doing Unit Testing in Fastapi using <code>from fastapi.testclient import TestClient</code></p>
<pre><code>def test_login_api_returns_token(session,client):
    form_data = {
        &quot;username&quot;: &quot;mike@gmail.com&quot;,
        &quot;password&quot;: &quot;mike&quot;
    }
    response = client.post(  
        &quot;/api/login&quot;, 
        data=form_data,
        headers={&quot;content-type&quot;: &quot;multipart/form-data&quot;}
        # headers={&quot;content-type&quot;: &quot;application/x-www-form-urlencoded&quot;}
    )
    result = response.json()
    assert response.status_code == 200
</code></pre>
<p>I am supposed to get token as response which I am getting when I run the fastapi application but not able to proceed with Unit Testing with the same.</p>
<p>Example of postman request for the same</p>
<p><a href=""https://i.stack.imgur.com/Be7rj.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Be7rj.png"" alt=""enter image description here"" /></a></p>
<p>How do I make sure form-data is being sent from TestClient?</p>
<p>api/login.py</p>
<pre><code>@router.post(&quot;/login&quot;)
async def user_login(form_data: OAuth2PasswordRequestForm = Depends(), session: Session = Depends(get_session)):
    user = authenticated_user(form_data.username, form_data.password, session)
    user = user[0]
    if not user:
        raise token_exception()
    token_expires = timedelta(minutes=120)
    token = create_access_token(username=user.username, user_id=user.id, expires_delta=token_expires)
    token_exp = jwt.decode(token, SECRET, algorithms=[ALGORITHM])
    return {
        &quot;status_code&quot;: status.HTTP_200_OK,
        &quot;data&quot;:{
            &quot;username&quot;: user.username,
            &quot;token&quot;: token,
            &quot;expiry&quot;: token_exp['exp'],
            &quot;user_id&quot;: user.id
        }
    }
</code></pre>
<p><a href=""https://i.stack.imgur.com/Be7rj.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Be7rj.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/75042410/fastapi-testclient-not-able-to-send-post-request-using-form-data,"['unit-testing', 'http-post', 'fastapi', 'starlette', 'httpx']",650,True,2,1
Unit Testing Error when i use JsonRequired Attribute in Dto Class,"<p>My unit testing is failed when i change Required field to <code>JsonRequired</code>
my Dto Class</p>
<p>class name = customerDto</p>
<pre><code>[JsonRequired]
public int ID {get; set;}
[JsonRequired]
public int Name{get; set;}
</code></pre>
<p>When use Required Attribute it was passed.</p>
<p>My Test Code</p>
<pre><code>var data = new customerDto {ID = ValidID};
byte[] byteArray = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
httpContext.Request.Body = new MemoryStream(byteArray);
</code></pre>
<p>in above line debug will stop. i need to fix this.</p>
<p>My unit testing failed when i use JsonRequired Attribute. But it will successfully debug when i use Required attribute</p>
",https://stackoverflow.com/questions/75280518/unit-testing-error-when-i-use-jsonrequired-attribute-in-dto-class,"['c#', 'json.net']",52,True,1,1
Unit Testing in Python:: Failure :::,"<p>I am running unit testing in python. Here is the code for test script.</p>
<pre><code>import json


def test_create_flat(client):
    data = {
        &quot;title&quot;: &quot;SDE super&quot;,
        &quot;company&quot;: &quot;doogle&quot;,
        &quot;company_url&quot;: &quot;www.doogle.com&quot;,
        &quot;location&quot;: &quot;USA,NY&quot;,
        &quot;description&quot;: &quot;python&quot;,
        &quot;date_posted&quot;: &quot;2022-03-20&quot;
        }
    response = client.post(&quot;/flats/create-flat/&quot;,json.dumps(data))
    assert response.status_code == 200 
    assert response.json()[&quot;company&quot;] == &quot;doogle&quot;
    assert response.json()[&quot;description&quot;] == &quot;python&quot;

def test_read_flat(client):     #new test
    data = {
        &quot;title&quot;: &quot;SDE super&quot;,
        &quot;company&quot;: &quot;doogle&quot;,
        &quot;company_url&quot;: &quot;www.doogle.com&quot;,
        &quot;location&quot;: &quot;USA,NY&quot;,
        &quot;description&quot;: &quot;python&quot;,
        &quot;date_posted&quot;: &quot;2022-03-20&quot;
        }
    response = client.post(&quot;/flats/create-flat/&quot;,json.dumps(data))

    response = client.get(&quot;/flats/get/1/&quot;)
    assert response.status_code == 200
    assert response.json()['title'] == &quot;SDE super&quot;
</code></pre>
<p>Here is the result. I couldn't find the reason for the failure on test_read_flat function.</p>
<p>Terminal
-&gt; pytest</p>
<pre><code>================================================ test session starts ================================================
platform darwin -- Python 3.8.8, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: /Users/ok/Desktop/javasc/backend
plugins: mock-1.13.0, anyio-3.6.2, cov-3.0.0
collected 3 items                                                                                                   

tests/test_routes/test_flats.py .F                                                                            [ 66%]
tests/test_routes/test_users.py .                                                                             [100%]

===================================================== FAILURES ======================================================
__________________________________________________ test_read_flat ___________________________________________________

client = &lt;starlette.testclient.TestClient object at 0x7f89f8f0c8e0&gt;

    def test_read_flat(client):     #new test
        data = {
            &quot;title&quot;: &quot;SDE super&quot;,
            &quot;company&quot;: &quot;doogle&quot;,
            &quot;company_url&quot;: &quot;www.doogle.com&quot;,
            &quot;location&quot;: &quot;USA,NY&quot;,
            &quot;description&quot;: &quot;python&quot;,
            &quot;date_posted&quot;: &quot;2022-03-20&quot;
            }
        response = client.post(&quot;/flats/create-flat/&quot;,json.dumps(data))
    
        response = client.get(&quot;/flats/get/1/&quot;)
&gt;       assert response.status_code == 200
E       assert 404 == 200
E        +  where 404 = &lt;Response [404]&gt;.status_code

tests/test_routes/test_flats.py:30: AssertionError
============================================== short test summary info ==============================================
FAILED tests/test_routes/test_flats.py::test_read_flat - assert 404 == 200
============================================ 1 failed, 2 passed in 0.80s ============================================
(base) ok@Oks-MacBook-Air backend % 
</code></pre>
<p>All three test should have passed. I am new to unit testing I tried and checked all the lines one by one but couldn't see the problem</p>
",https://stackoverflow.com/questions/75406081/unit-testing-in-python-failure,"['python', 'unit-testing']",37,False,0,0
Verify spock mock is called in specific order w/ specific params,"<p>Say I have a method I am unit testing</p>
<pre><code>class MyClass {
    private Foo foo;

    public void myMethod(String arg1, String arg2) {
        foo.bar(arg1);
        foo.bar(arg2);
    }
}
</code></pre>
<p>and the test</p>
<pre><code>def &quot;Playlist with stale channel should get updated upon refresh&quot;() {
    when: &quot;myMethod is called with 'a','b'&quot;
    MyClass myClass = new MyClass();
    myClass.myMethod('a', 'b');

    then: &quot;expect that foo('a') is called before foo('b') is called&quot;
    /* 
        How can I do this? I only know how to check that it was called twice.
    */
   2 * foo.bar(_) &gt;&gt; null 

    /*
        How could I make an assertion like &quot;foo.bar was called twice, first with 'a' as
          the argument, then again with 'b' as the argument?
    */
}
</code></pre>
",https://stackoverflow.com/questions/75667811/verify-spock-mock-is-called-in-specific-order-w-specific-params,"['java', 'unit-testing', 'groovy', 'spock']",27,True,1,1
How to aggregate Unit testing and Integration test coverage result,"<pre><code>gradle-check:
  ...
  script:
    - ./gradlew check --console=plain ${GRADLE_CHECK_OPTS}
  after_script:
    - mkdir build/reports/tests/ut/
    - mv build/reports/tests/test/* build/reports/tests/ut/
  artifacts:
    when: always
    expire_in: 1 week
    reports:
      junit: build/test-results/test/**/TEST-*.xml
    paths:
      - build/reports/jacocoHtml/
      - build/reports/tests/ut/

integration-test:
  ...
  script:
    - ./gradlew test -Dtest.profile=integration --tests &quot;com.test.integrationtest.*&quot;
    - cat build/reports/jacocoHtml/index.html
  coverage: '/Total.*?([0-9]{1,3})%/'
  after_script:
    - mkdir build/reports/tests/it/
    - mv build/reports/tests/test/* build/reports/tests/it/
  artifacts:
    when: always
    expire_in: 1 week
    reports:
      junit: build/test-results/test/**/TEST-*.xml
    paths:
      - build/reports/jacocoHtml/
      - build/reports/tests/it/

pages:
  stage: pages
  dependencies:
    - gradle-check
    - integration-test
  script:
    - mkdir -p public
    - mv build/reports/tests/ut/ public/
    - mv build/reports/tests/it/ public/
    - mv build/reports/jacocoHtml/ public/
  artifacts:
    paths:
      - public
    expire_in: 100 yrs
  when: always
  ....
</code></pre>
<p>I wanted aggregation between Unit Testing &amp; Integration Testing coverage,
I can see only unit testing coverage is generated in gitlab pipeline,<br />
And integration test coverage is not getting generated in pipeline.</p>
<p>gradle.build file below</p>
<pre><code>def jacocoTestExclude = [
        'com/test/constants/**',
        'com/test/model/**',
]
jacocoTestReport {
    reports {
        xml.enabled false
        csv.enabled false
        html.enabled true
        html.destination file(&quot;${buildDir}/reports/jacocoHtml&quot;)
    }
    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it, exclude: jacocoTestExclude
            )
        }))
    }
}

jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = 0.0
            }

            failOnViolation true
        }
    }

    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it, exclude: 'jacocoExclude'
            )
        }))
    }
}

jacoco {
    toolVersion = &quot;0.8.7&quot;
}

test {
    testLogging {
        showStandardStreams = true
        exceptionFormat = 'full'
    }
    if (System.properties['test.profile'] != 'integration') {
        exclude '**/*integrationtest*'
    }
}

check.dependsOn jacocoTestCoverageVerification
jacocoTestCoverageVerification.dependsOn jacocoTestReport
</code></pre>
<p>Since integration test class is not required to run with unit test I have excluded that in test().
jacocoTestCoverageVerification doesn't have any exclusion, some dummy string it is</p>
",https://stackoverflow.com/questions/76109843/how-to-aggregate-unit-testing-and-integration-test-coverage-result,"['gitlab-ci', 'code-coverage', 'jacoco', 'test-coverage']",74,False,0,0
Uncaught &#39;Warning: An update to %s inside a test was not wrapped in act(...).\n&#39; +,"<p>Upgrade node and npm version from 14 and 6 to 16.18.1 and 8 and above. After that upgrade, most of the unit testing is failing in the react-carbon framework. Errors appear here-</p>
<p><a href=""https://i.stack.imgur.com/4RYfg.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/4RYfg.png"" alt=""enter image description here"" /></a></p>
<p>But all the unit testing already wrapped with the act</p>
<pre><code>let container=null;

beforeEach(() =&gt; {
  container = document.createElement('div');
  document.body.appendChild(container);
});

afterEach(cleanup);

describe('&lt;TermsOfUse /&gt; component', () =&gt; {
  test('its snapshot matches', async () =&gt; {
    await act(async () =&gt; {
      const { container } = render(
        &lt;MockedProvider mocks={[]} addTypename={false}&gt;
          &lt;TermsOfUse /&gt;
        &lt;/MockedProvider&gt;
      );
      expect(container).toBeDefined();
      expect(container.firstChild).toMatchSnapshot();
    });
  });
  test('it passes an axe accesibility check', async () =&gt; {
    await act(async () =&gt; {
      render(
        &lt;MockedProvider &gt;
          &lt;TermsOfUse /&gt;
        &lt;/MockedProvider&gt;, container
      );
    });
    const results = await axe(container);
    expect(results).toHaveNoViolations();
  });
});
</code></pre>
<p>I tried in a different ways as well in a different file -</p>
<pre><code>describe('&lt;HelpSupport /&gt; component', () =&gt; {
  test('its snapshot matches', async () =&gt; {
    await act(async () =&gt; {
      const { container } = render(
        &lt;MockedProvider mocks={[]} addTypename={false}&gt;
          &lt;HelpSupport /&gt;
        &lt;/MockedProvider&gt;
      );
      expect(container).toBeDefined();
      expect(container.firstChild).toMatchSnapshot();
    });
  });
  test('it passes an axe accesibility check', async () =&gt; {
    await act(async () =&gt; {
      const { container } = render(
        &lt;MockedProvider mocks={[]} addTypename={false}&gt;
          &lt;HelpSupport /&gt;
        &lt;/MockedProvider&gt;
      );
      const results = await axe(container);
      expect(results).toHaveNoViolations();
    });
  });
  it('on click tab', async () =&gt; {
    await act(async () =&gt; {
      HTMLAnchorElement.prototype.click = jest.fn();
      const { getByText } = render(
        &lt;MockedProvider mocks={[]} addTypename={false}&gt;
          &lt;HelpSupport /&gt;
        &lt;/MockedProvider&gt;
      );
      await waitFor(() =&gt; {
        const secondTab = getByText('Accounts &amp; Invoices');
        fireEvent.click(secondTab);
      });
    });
  });
</code></pre>
<p>import it from</p>
<p><a href=""https://i.stack.imgur.com/b0gby.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/b0gby.png"" alt=""enter image description here"" /></a></p>
<p>I checked many articles, but not useful so far.</p>
",https://stackoverflow.com/questions/76355200/uncaught-warning-an-update-to-s-inside-a-test-was-not-wrapped-in-act-n,"['unit-testing', 'jestjs', 'react-testing-library', 'react-dom', 'babel-jest']",10,False,-1,0
How to unit test functions that make calls to database using mysql2?,"<p>I am currently starting a new project using Typescript and this is my first time with unit testing.</p>
<p>I have written simple functions to initiate connection and get data from database using mysql2 package</p>
<p>The following are examples of my functions.</p>
<p>Connect function:</p>
<pre><code>export async function connect(connectionOptions: ConnectionOptions): Promise&lt;Connection&gt; {
  const connection = await createConnection(connectionOptions);

  return connection;
}
</code></pre>
<p>Get data function:</p>
<pre><code>export async function getData(connection: Connection, table: string, fields?: string[]) {
  let selectedFields = fields?.toString();

  if (!fields) selectedFields = '*';

  const query = `SELECT ${selectedFields} FROM ${table};`

  const data = await connection.execute(query);

  return data;
}
</code></pre>
<p>I have tried out simple tests which test the output of functions that return strings.</p>
<p>I'm not sure how can I test these functions and I can't seem to find a unified answer or a methodology to think and apply unit testing for such a case.</p>
<p>So my questions are:</p>
<ul>
<li>What is the best way to unit test my functions?</li>
<li>Is there a process or a way which I should follow when I try to implement unit testing?</li>
</ul>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/75518437/how-to-unit-test-functions-that-make-calls-to-database-using-mysql2,"['mysql', 'typescript', 'unit-testing', 'mysql2']",29,False,0,0
unit-testing boost interprocess client,"<p>I have to unit-test a client of a shared memory map constructed using the boost interprocess. It is really awkward to create shared memory blocks for unit-testing. Normally I would use some static memory to simulate shared memory behavior during unit-tests.</p>
<p>I do not see such a possibility in the boost interprocess. What is the established practice for unit-testing clients of the boos interprocess?</p>
",https://stackoverflow.com/questions/76316303/unit-testing-boost-interprocess-client,"['unit-testing', 'boost-interprocess']",5,False,0,0
Firestore Connection Dropped Error in React Unit Test,"<p>I'm using Firestore as my backend for my React app. I'm implementing unit testing, but it throws me an error as such:</p>
<pre><code>@firebase/firestore: Firestore (9.14.0): Connection GRPC stream error. Code: 14 Message: 14 UNAVAILABLE: Connection dropped
</code></pre>
<p>After that, it logs me another error:</p>
<pre><code>@firebase/firestore: Firestore (9.14.0): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=unavailable]: 14 UNAVAILABLE: Connection dropped
    This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend
</code></pre>
<p>My guess is that I'm unable to call to the database when unit testing.</p>
<p>Is there a way I can work around this error? Or do I have to make a mock for it? If yes, is there a reference I can refer to regarding this?</p>
",https://stackoverflow.com/questions/75005986/firestore-connection-dropped-error-in-react-unit-test,"['reactjs', 'firebase', 'google-cloud-firestore']",38,False,0,0
How should you write unit test for an native andorid app that strongly communicate with android bitmap and view related task?,"<p>Suppose there's an app that works with photos. The bitmap related task, editing them, rendering and view related tasks are main concerns of the app.</p>
<p>Now what I want is to write unit testing for the whole app and getting into it for the first time. As there are so many terms like London approach(Mock) or detroit approach (Not to mock) or use Instrumental testing instead of Unit testing which one should you choose.</p>
",https://stackoverflow.com/questions/75066625/how-should-you-write-unit-test-for-an-native-andorid-app-that-strongly-communica,"['android', 'kotlin', 'unit-testing', 'tdd']",20,False,0,0
VSTO Outlook Addin Unit Testing with xUnit,"<p>I was having some trouble getting unit testing with xUnit to work in Visual Studio (2019) for my VSTO Outlook addin project.  I had reviewed the following SO questions and answers:</p>
<p><a href=""https://stackoverflow.com/questions/45121396/vsto-unit-testing-office-addin-in-c-sharp-net-via-requestcomaddinautomationserv?r=SearchResults"">VSTO Unit Testing Office AddIn in C# .NET via RequestComAddInAutomationService</a></p>
<p><a href=""https://stackoverflow.com/questions/50743180/unit-testing-excel-addin-using-vsto?r=SearchResults"">Unit testing Excel addin using VSTO</a></p>
<p><a href=""https://stackoverflow.com/questions/30906070/unit-testing-vsto-projects?r=SearchResults"">Unit Testing VSTO projects</a></p>
<p>However, in the end it turned out that I had simply not properly created the xUnit test project.</p>
<p><strong>Unlike the questions/solutions listed above, I did NOT need to use RequestComAddinAutomationService, nor have to setup any classes with COM Interop attributes or set &quot;Register for COM interop&quot; to get my tests running.</strong></p>
<p>My xUnit project is capable of both launching Outlook (just like debugging does), and accessing my classes and methods created inside of my addin project.   I'm not sure why I am able to get xUnit working with my Outlook VSTO addin without the COM interop stuff (see Note 2) -- but it works, so I thought I would share a step-by-step description of how I got it working in my Answer below.</p>
<p>Note 1:
I created a new question/answer for this, since none of the questions above involved an Outlook VSTO addin, but rather were for Excel and Powerpoint.</p>
<p>Note 2:
Perhaps the COM interop code is not needed because this is an Outlook addin versus Excel or Powerpoint as in the questions listed above?  Or perhaps because I am using xUnit, while I believe the testing framework in most of the questions above is MS Native Unit Testing?</p>
",https://stackoverflow.com/questions/75739113/vsto-outlook-addin-unit-testing-with-xunit,"['c#', 'unit-testing', 'outlook', 'vsto', 'xunit']",61,True,1,1
Visual Studio Live Unit Testing doesn&#39;t have option to &quot;enable debug symbol&quot;,"<p>I'm using Visual Studio 2022 17.4.0 to run the Live Unit Testing window using xUnit v2.4.2 tests with the xunit.runner.visualstudio v2.4.5.</p>
<p>When looking at the following documentation, it claims that I should have a checkmark thats allows me to run these tests with debug symbols.  However, this is completely missing from my options.</p>
<p><a href=""https://learn.microsoft.com/en-us/visualstudio/test/live-unit-testing?view=vs-2022"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/visualstudio/test/live-unit-testing?view=vs-2022</a></p>
<p>Here's what it <em>should</em> look like:
<a href=""https://i.stack.imgur.com/gvL66.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/gvL66.png"" alt=""enter image description here"" /></a></p>
<p>And here's why mine actually looks like:
<a href=""https://i.stack.imgur.com/UQj7i.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/UQj7i.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/75164810/visual-studio-live-unit-testing-doesnt-have-option-to-enable-debug-symbol,"['visual-studio', 'xunit', 'live-unit-tests']",51,False,0,0
How to unit test static methods with custom object as return type using JUnit 5,"<pre class=""lang-java prettyprint-override""><code>public class Demo{
    public static CustomObject processMethod(String str1, String str2){
        //do something
        Demo1.processMethod1(str1,str2);
        Demo2.processMethod2(str1,str2);
        return custom Object;
    }
}

public class Demo1{
    public static void processMethod1(String str1, String str2){}
}

public class Demo2{
    public static void processMethod2(String str1, String str2){}
}
</code></pre>
<p>I am new to unit testing. While creating a test for class Demo processMethod, how to skip the execution of processMethod1 and processMethod2?</p>
",https://stackoverflow.com/questions/75873664/how-to-unit-test-static-methods-with-custom-object-as-return-type-using-junit-5,"['java', 'unit-testing', 'junit', 'mocking', 'junit5']",102,True,2,2
ruby 0.20058343942960624257135598502550788022255447223e2 How to convert to 20,"<p>I encountered this error during unit testing, and I tried using to_i. But this is wrong, how should we solve it</p>
<pre><code>        --- expected
        +++ actual
        @@ -1 +1 @@
        -0.20058343942960624257135598502550788022255447223e2
        +20

</code></pre>
",https://stackoverflow.com/questions/75874191/ruby-0-20058343942960624257135598502550788022255447223e2-how-to-convert-to-20,"['ruby-on-rails', 'ruby']",58,True,-1,1
Unit testing can&#39;t find button and it equal to null,"<p>I am trying to do an unit testing for a reuseable component, the reuseable componet have an input and output. But It seem to can't find the button class. and also if there is a way, is thhere a way to not use fixture.</p>
<p>the error =TypeError: Cannot read properties of null</p>
<pre><code>describe('SelectorComponent', () =&gt; {
  let component: SelectorComponent;
  let fixture: ComponentFixture&lt;SelectorComponent&gt;;

  beforeEach(async () =&gt; {
    component = new SelectorComponent();
  });

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(SelectorComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });


  it('should select a dimension when clicked', () =&gt; {
    let selectors: Selector[] = [{
      id: '1', 
      name: 'Child ',
      parent: 'Parent ',
      sortOrder: 1,
      icon: 'brain',
      selected: true, 
      children: []
    }];
    spyOn(component, 'selectSelector');
    component.selectors = selectors;
    let btn = fixture.debugElement.query(By.css('.selectors'));
    btn.triggerEventHandler('click', null); 
    fixture.detectChanges();

    fixture.whenStable().then(() =&gt; {
      expect(component.selectorSelected.emit).toHaveBeenCalled();
    });
  });
});

</code></pre>
<pre><code>@Input() public selectors!: Selector[];
  @Output() public selectoSelected = new EventEmitter&lt;Dimension&gt;();

  constructor() { }

  selectselectors(selector: Selector) {
    this.selectoSelected.emit(selector);
  }
</code></pre>
<pre><code>&lt;button
    class=&quot;selector&quot;
    (click)=&quot;selectselectors(selectors)&quot;
    *ngFor=&quot;let selector of selectors&quot;
&gt;
    &lt;div class=&quot;name&quot;&gt;{{ selector.name }}&lt;/div&gt;
&lt;/button&gt;
</code></pre>
<p>Thank you in advance, I am new with Unit testing</p>
<p>I have try without fixture alsso, but it didnt seem to work, it keep sayying button is null</p>
",https://stackoverflow.com/questions/75001059/unit-testing-cant-find-button-and-it-equal-to-null,"['angular', 'karma-jasmine']",110,False,0,1
Unit Tests assertionFailure,"<p>I'm unit testing:</p>
<pre><code>func testParseFakeDeeplinkSuccess() {
    let fakeDeeplink = &quot;fakeDeeplink&quot;
    let url = touchManager?.handleTouch([&quot;deeplink&quot;: fakeDeeplink as NSSecureCoding])
    XCTAssertNotNil(url)
}
</code></pre>
<p>which will result in &quot;assertionFailure(&quot;3DTouch not trackable&quot;)&quot;</p>
<pre><code>    func handleTouch(_ userInfo: [String: NSSecureCoding]?) -&gt; URL? {
    if let shortcut = userInfo?[&quot;deeplink&quot;] as? String,
       let url = URL(string: shortcut) {

        switch shortcut {
        default:
            assertionFailure(&quot;3DTouch not trackable&quot;)
        }

        return url
    }

    return nil
}
</code></pre>
<p>What can I use in my unit tests to tests this properly?</p>
",https://stackoverflow.com/questions/76118750/unit-tests-assertionfailure,"['swift', 'unit-testing', 'xctest']",69,True,0,1
test function is not recognized as a global function,"<p>I followed a JavaScript unit testing tutorial at acadamind.com in that tutorial instructor used Vitest for demonstrations and the reason they mentioned using Vitest instead of Jest was Jest needed some extra configuration to work with the latest JavaScript syntax.</p>
<p>After doing my own research about unit testing I realized industry demand unit testing skills with the Jest. So I followed another tutorial for learning unit testing with Jest and React Testing Library (RTL).</p>
<p>I created a brand new TypeScript project with Create React App (CRA) and followed the instructions in that tutorial and everything went well. The instructor mentioned that Jest and RTL are supported out of the box with CRA.</p>
<p>After studying unit testing I tried to apply that knowledge and write some tests with my application, which was created some time back, and recently we updated it to React Scripts 5.  In that application, I check <code>node_modules</code> folder, and Jest is there as a dependency. But I have noticed that the following packages are not listed in the <code>package.json</code> file in my project, so I installed them:</p>
<pre><code>@testing-library/jest-dom&quot;: &quot;^5.16.5&quot;,
@testing-library/react&quot;: &quot;^13.4.0&quot;,
@testing-library/user-event&quot;: &quot;^14.4.3&quot;,
@types/jest&quot;: &quot;^29.4.0&quot;,
</code></pre>
<p>After that, I noticed my new project has this file in the <code>src</code> folder so I have copy pasted this file as well.</p>
<p><strong>setupTest.ts</strong></p>
<pre><code>// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
</code></pre>
<p>When I tried to run when I tried to write my first unit test I noticed that VS Code doesn't recognize this <code>test</code> function as a global function and indicates an error and then I try to run the test script and I am getting this error</p>
<pre><code> Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default &quot;node_modules&quot; folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your &quot;node_modules&quot; files transformed, you can specify a custom &quot;transformIgnorePatterns&quot; in your config.
     • If you need a custom transformation specify a &quot;transform&quot; option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the &quot;moduleNameMapper&quot; config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /home/pathum/Documents/tagd/node_modules/axios/index.js:1
    ({&quot;Object.&lt;anonymous&gt;&quot;:function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    &gt; 1 | import axios from 'axios';
        | ^
      2 | // config
      3 | import { HOST_API } from '../config';
      4 |

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.&lt;anonymous&gt; (src/utils/axios.ts:1:1)
      at Object.&lt;anonymous&gt; (src/hooks/useRefresh.tsx:2:1)
      at Object.&lt;anonymous&gt; (src/hooks/useAxiosPrivate.tsx:3:1)
      at Object.&lt;anonymous&gt; (src/pages/contracts/contract-form/new-contact-person.tsx:12:1)
      at Object.&lt;anonymous&gt; (src/pages/contracts/contract-form/parties.tsx:15:1)
      at Object.&lt;anonymous&gt; (src/pages/contracts/contract-form/contract-form.tsx:9:1)
      at Object.&lt;anonymous&gt; (src/pages/contracts/contract-form/contract-form.test.tsx:2:1)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.398 s
Ran all test suites related to changed files.

Watch Usage: Press w to show more.
</code></pre>
<p>Seems I need to do some configurations for Jest to work properly in the application. How do I fix this?</p>
",https://stackoverflow.com/questions/75255018/test-function-is-not-recognized-as-a-global-function,"['javascript', 'reactjs', 'jestjs', 'react-testing-library']",128,False,-1,1
How to write test case for if else with htmlelement in karma jasmine test case?,"<pre><code>**Component code:**
@HostListener('document:click', ['$event', '$event.target'])
onClick(event: MouseEvent, targetElement: HTMLElement): void| boolean {
try {
  this.shareService.addBreadCrumb('Host listener other than helpbox...');
  if (targetElement.className === 'fa fa-question-circle-o' || targetElement.className === 'info-icon') {
    return false;
  }
  this.isHelpboxVisible = null;
} catch (e) {
  Sentry.captureException(e);
}
</code></pre>
<p>}</p>
<p>I want to code cover the following part:</p>
<pre><code>if (targetElement.className === 'fa fa-question-circle-o' || targetElement.className === 'info-icon') {
    return false;
  }
</code></pre>
<p>Please suggest how can I proceed. What I have tried ( I am new to unit testing):</p>
<pre><code>it('should return false for specific classname', () =&gt; {
document.dispatchEvent(new MouseEvent('click'));
fixture.debugElement.query(By.css('.fa fa-question-circle-o.info-icon'));
const result = component.onClick(new MouseEvent('click'), 'test' as any);
expect(result).toBe(false);
});
</code></pre>
",https://stackoverflow.com/questions/76219205/how-to-write-test-case-for-if-else-with-htmlelement-in-karma-jasmine-test-case,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'karma-runner']",19,True,0,1
Which is the most recommended way to pursue integration and system tests por Azure Synapse pipelines?,"<p>Good afternoon!</p>
<p>Me and my team wish to design and pursue unit testing (integration and system too) on our Azure Synapse pipeline. It works properly, fortunately, and it consists of a Copy Data and a Stored Procedure that creates a view. However, we seek to carry on with the mentioned testing and maybe automate this testing eventually.</p>
<p>Are there any courses of action you could recommend us?</p>
<p>Thanks a lot!</p>
<p>Regards,</p>
<p>Mateo</p>
<p>We expect to run integration, system and unit testing for our current pipeline and for future ones.</p>
",https://stackoverflow.com/questions/75139487/which-is-the-most-recommended-way-to-pursue-integration-and-system-tests-por-azu,"['azure', 'azure-devops', 'azure-data-factory', 'azure-synapse']",89,False,0,0
How to write unit test case for fastapi for mysql,"<p><strong>app.py</strong></p>
<pre><code>def get_db(request: Request):
    return request.state.db

@router.get(&quot;/data&quot;)
async def endpoint(
    db:Session = Depends(get_db),
):
    try:
        data =  await crud.get_all_data(db=db)
        return data
</code></pre>
<p><strong>test_main.py</strong></p>
<pre><code>def test_read():
    response = client.get(&quot;/data&quot;)
    assert response.status_code == 200
    assert response.json() 
</code></pre>
<p><strong>Error</strong></p>
<pre><code>test_main.py::test_read - AttributeError: 'State' object has no attribute 'db'  
</code></pre>
<p>how to write <strong>test_main.py</strong> file code to pass <strong>db:session</strong> and pass this test,,
new to fast api unit testing concept.
Thanks foe correcting me.</p>
",https://stackoverflow.com/questions/75150359/how-to-write-unit-test-case-for-fastapi-for-mysql,"['python', 'unit-testing', 'pytest', 'fastapi', 'httpx']",80,False,0,0
How to mock next/router for unit testing with vitest?,"<p>When trying to write simple tests for out Next.js app that uses <code>useRouter()</code> hook, <code>vitest</code> starts throwing errors.</p>
<p>Looking for ways to mock next/router for unit testing with vitest.</p>
",https://stackoverflow.com/questions/75831875/how-to-mock-next-router-for-unit-testing-with-vitest,"['javascript', 'node.js', 'unit-testing', 'next.js', 'vitest']",345,True,0,1
Unit tests for Interceptor addPathPatterens,"<p>We have a requirement to write some unit tests for IdInterceptorConfig implementation using mock or other framework support.</p>
<pre><code>@Configuration
public class IdInterceptorConfig implements WebMvcConfigurer {

     @Autowired
     private final IdInterceptor idInterceptor;

     //Unit tests for this code snippet
     @Override
     public void addInterceptors(InterceptorRegistry registry) {
          registry.addWebRequestInterceptor(idInterceptor).addPathPatterens(&quot;/**&quot;);
     }
}

@Component
public class IdInterceptor implements HandlerInterceptor, WebRequestInterceptor {

     @Override
     public void preHandle(WebRequest request) throws Exception {
          ...
     }

     //@Override methods
     ... 
}

</code></pre>
<p>Can someone please share a sample code snippet for unit testing.</p>
",https://stackoverflow.com/questions/75749013/unit-tests-for-interceptor-addpathpatterens,"['spring', 'spring-boot', 'unit-testing', 'spring-mvc', 'interceptor']",20,False,0,0
Test FastAPI with Big Query client in backend,"<p>I'm writing a REST API in FastAPI where I have to use Big Query for fetching data. I have problems with creating unit tests for positive scenarios where everything goes fine. I'm a beginner in API unit testing and I don't know how to mock Big Query Client.</p>
<p>Below please find the simplified code showing the overall idea of what I want to achieve. Ask me if you need more details and I will edit the post.</p>
<p><code>main.py</code></p>
<pre><code>from google.cloud import bigquery
from fastapi import FastAPI, Depends

app = FastAPI()


def get_bq_client():
    with bigquery.Client() as client:
        return client


def prepare_query(val1):
    query = f&quot;&quot;&quot;
         SELECT name, item_id, price
         FROM `bigquery-my-data.products`
         WHERE item_id = {val1}
     &quot;&quot;&quot;

    return query


@app.get(&quot;/v1/items/{item_id}&quot;)
async def get_price(item_id: int,
                    bq_client: bigquery.client.Client = Depends(get_bq_client)
                    ):
    query = prepare_query(item_id)

    bq_client = bigquery.Client()
    query_job = bq_client.query(query)
    result = query_job.query().to_dataframe()

    return result.to_json()
</code></pre>
<p><code>test_main.py</code></p>
<pre><code>from fastapi.testclient import TestClient
from main import app

client = TestClient(app)


def test_get_price_correct():
    response = client.get(&quot;/v1/items/123&quot;)
    expected = {&quot;name&quot;: &quot;Cola&quot;,
                &quot;item_id&quot;: 123,
                &quot;price&quot;: 1.12}
    pass
</code></pre>
<p>I've found this thread but I failed to adapt it for mocking the client response: <a href=""https://stackoverflow.com/questions/53700181/python-unit-testing-google-bigquery"">Python Unit Testing Google Bigquery</a>.</p>
",https://stackoverflow.com/questions/75864649/test-fastapi-with-big-query-client-in-backend,"['python', 'testing', 'mocking', 'pytest', 'fastapi']",165,True,0,1
Angular Unit - Testing (Jasmin Karma) : Error :Cannot find name &#39;google&#39;,"<p>google.directives.ts:-</p>
<pre><code>  getAutocompletes(addresstext: ElementRef) {
    const autocomplete = new  google.maps.places.Autocomplete(addresstext.nativeElement,
      {
       ...
      });
  google.maps.event.addListener(autocomplete, 'place_changed', () =&gt; 
  {
   ...
  }
</code></pre>
<p>after testing code in jasmin &amp; karma, I got Error :-&gt;
Cannot find name 'google'.</p>
<p>How can I solve this issue for unit testing?
I alreday added &quot;googlemaps&quot; in tsconfig.app.json.</p>
",https://stackoverflow.com/questions/75168369/angular-unit-testing-jasmin-karma-error-cannot-find-name-google,"['angular', 'unit-testing', 'karma-jasmine', 'angular11']",116,True,0,1
Nestjs can&#39;t resolve dependencies of the AppConfigService (Unit Testing),"<p>I am trying to set up Jest Unit Testing to my project, but I'm getting the following errors when trying to Unit Test:</p>
<p><a href=""https://i.stack.imgur.com/GVICh.png"" rel=""nofollow noreferrer"">Erro Message (Screenshot)</a></p>
<p>How do I fix this issue?</p>
",https://stackoverflow.com/questions/75292294/nestjs-cant-resolve-dependencies-of-the-appconfigservice-unit-testing,"['testing', 'nestjs']",28,False,0,2
Where is the code that creates a unit test database in Django?,"<p>For unit testing, Django creates a test database, runs unit tests, then destroys that database.  Where is the code that does that?</p>
<p>I looked in github, and couldn't find anything.</p>
<p>For example, at the beginning of unit testing, I see this message:</p>
<blockquote>
<p>Creating test database for alias 'default'...</p>
</blockquote>
<p>but when I <a href=""https://github.com/django/django/search?q=Creating%20test%20database%20for%20alias"" rel=""nofollow noreferrer"">look in github for &quot;Creating test database for alias&quot;</a>, I find nothing.</p>
<p>Related: how does the testing code connect to that database, given that it's not specified in the DATABASES settings? (That is, &quot;default&quot; is in settings, but the test database &quot;test_default&quot; is not.) Or, where is the code that connects to the test database?</p>
",https://stackoverflow.com/questions/75771847/where-is-the-code-that-creates-a-unit-test-database-in-django,['django'],21,True,1,1
I am using unit testing in laravel hyn-tenancy using sqlite. Using system database in phpunit.xml is working but using sqlite is generating errors,"<p>I am using SQLite for laravel unit testing. I am using hyn-tenancy. I use sqlite for running test cases but it generates an error as SQLSTATE[HY000] [1049] Unknown database 'database/database.SQlite</p>
<pre><code>I use the following code inside phpunit.xml                   
&lt;server name=&quot;DB_CONNECTION&quot; value=&quot;sqlite&quot;  force=&quot;true&quot;/&gt;
&lt;server name=&quot;DB_DATABASE&quot; value=&quot;database/database.sqlite&quot;  force=&quot;true&quot;/&gt;
                
I use the following database connection inside .env.testing
DB_CONNECTION=sqlite
DB_DATABASE=database_name
      
TENANCY_HOST=mysql
TENANCY_DATABASE=database_name
I used sqlite connection inside config/database.php                   
'sqlite' =&gt; [
       'driver' =&gt; 'sqlite',
       'url' =&gt; env('DATABASE_URL'),
       'database' =&gt; env('DB_DATABASE', database_path('database.sqlite')),
       'prefix' =&gt; '',
       'foreign_key_constraints' =&gt; env('DB_FOREIGN_KEYS', true),
       ],
                                  
Testcases are working when I used a system connection inside phpunit.xml:                     
    &lt;server name=&quot;DB_CONNECTION&quot; value=&quot;system&quot;/&gt;
    &lt;server name=&quot;DB_DATABASE&quot; value=&quot;seldio&quot;/&gt;
              
    I made a database.sqlite file inside the database folder to test the database using sqlite as database/database.sqlite.
</code></pre>
",https://stackoverflow.com/questions/75623228/i-am-using-unit-testing-in-laravel-hyn-tenancy-using-sqlite-using-system-databa,"['mysql', 'laravel', 'unit-testing', 'phpmyadmin', 'swagger']",50,False,0,0
Unit test .net 6 console app using IHostApplicationLifeTime,"<p>I have a class (<code>CronClass</code>) that inherits from <code>IHostedService</code> with 2 methods which are <code>StartAsync(CancellationToken)</code> and <code>StopAsync(CancellationToken)</code>.</p>
<p>How do you go about unit testing the <code>StartAsync</code> method to verify that the code was executed, using Moq Library?
For example:</p>
<pre><code>public class CronClass: IHostedService
{
    private readonly IHostedApplicationLifetime applicationLifetime;
    private readonly IService service;
    // IHostedApplicationLifetime/IService are injected DI to via the constructor
    public Task StartAsync(CancellationToken cancellationToken)
    {
        applicationLifeTime.ApplicationStarted.Register(() =&gt;
        {
            Task.Run(async () =&gt;
            {
                log.LogInformation(&quot;Cron Started&quot;);
                await service.Process();
            });
        });
    }
    //...
}
</code></pre>
",https://stackoverflow.com/questions/75468740/unit-test-net-6-console-app-using-ihostapplicationlifetime,"['c#', 'unit-testing', 'console-application', 'moq']",274,True,0,1
"How to write Angular Unit Testcase for below function (localstorage setItem, getItem and how to check the undefined conditions)?","<p>I am new to angular unit testing, and how to write the spec for the below code.</p>
<pre><code>searchAllField() {
    localStorage.setItem('region', this.region);
    if (this.state != undefined) {
        this.stateSubmit = [];
        Object.values(this.state).forEach((element: any) =&gt; {
            this.stateSubmit.push(element.value);
            if (element.label != undefined &amp;&amp; element.label == 'All') {
                this.allStateValues = true;
            }
        });
    }
}
</code></pre>
<p>I tried to write the test cases like below but it shows the error &quot;<strong>SyntaxError: &quot;undefined&quot; is not valid JSON</strong>&quot;</p>
<pre><code>it('Should search the all the field', () =&gt; {
    const fixture = TestBed.createComponent(StateComponent);
    const app = fixture.componentInstance;
    app.searchAllField();
    expect(app).toBeTruthy();
});
</code></pre>
",https://stackoverflow.com/questions/75182892/how-to-write-angular-unit-testcase-for-below-function-localstorage-setitem-get,"['angular', 'unit-testing', 'jasmine']",28,False,0,0
How to set a System.Type property for unit testing?,"<p>I've got a class that has a property of type Type. How can I set this for unit testing?</p>
<p>Example class:</p>
<pre><code>public class School
{
    public string Name { get; set; }
    public Type SchoolType { get; set; }
}
</code></pre>
<p>I can mock the Name but I'm not sure how to mock the SchoolType property.</p>
<p>Example test:</p>
<pre><code>string expectedName = &quot;Richmond&quot;;
var expectedType = ???

var school = new School();
school.Name = expectedName;
school.SchoolType = expectedType;

Assert.AreEqual(expectedName, school.Name);
Assert.AreEqual(?, school.SchoolType);
</code></pre>
",https://stackoverflow.com/questions/75135603/how-to-set-a-system-type-property-for-unit-testing,"['c#', 'unit-testing', 'types']",40,True,1,1
Angular Unit testing : Error: Cannot match any routes,"<p>I Am working on unit testing under my angular 15 app. I am getting the below error while running the test:</p>
<p>Error: Cannot match any routes.URL Segment: 'signin'</p>
<p>Below is the unit test code for my component:</p>
<pre><code> fdescribe('ExtensionListComponent',()=&gt;{
   BeforeEach(() =&gt; {
     TestBed.configureTestingModule({
       imports: [
        RouteTestingModule.withRoutes([{
        path: 'extensions-list',
       component: ExtensionListComponent}]),
       HttpClientTestingModule
       ],
       declarations:[
       ExtensionListComponent
       ],
       providers: [
       TaskService
       ]
  }).compileComponents();
 });
</code></pre>
",https://stackoverflow.com/questions/75170240/angular-unit-testing-error-cannot-match-any-routes,"['angular', 'jasmine', 'angular-test']",47,True,0,1
How to test model class using junit to cover field validations?,"<p>I am writing unit test cases using junit and mockito for my spring boot application. Now, I also want to write test cases for request model class to achieve minimum 90% code coverage as per business requirement.</p>
<p><strong>There are 3 fields in request model class like id, revision and state. Example: If id field in request body is null or empty or length is less then 8 than it should give error like Id should not be null and Id size should be 8.</strong></p>
<p>Request model class code is as below.</p>
<pre><code>@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor

public class Request {

    @NotNull(message = &quot;{request.id.notNull}&quot;)
    @Size(min=8, max=8, message = &quot;{request.id.size}&quot;)
    @Schema(type = &quot;string&quot;, example=&quot;X1234567&quot;)
    private String id;
    
    @NotNull(message = &quot;{request.revision.notNull}&quot;)
    @Schema(type = &quot;integer&quot;, example=&quot;0&quot;)
    private Integer revision;
    
    @NotNull(message = &quot;{request.state.notNull}&quot;)
    @Size(min=2,max=2,  message = &quot;{request.state.size}&quot;)
    @Pattern(regexp=&quot;^(BB|Bb|bB|bb|MM|Mm|mM|mm)$&quot;, message= &quot;{request.state.pattern}&quot;)
    @Schema(type = &quot;string&quot;, example=&quot;BB&quot;, allowableValues = {&quot;BB&quot;,&quot;Bb&quot;, &quot;bB&quot;, &quot;bb&quot;, &quot;MM&quot;, &quot;Mm&quot;, &quot;mM&quot;, &quot;mm&quot;})
    private String state;
    
    @Override
    public String toString() {
        StringBuilder details = new StringBuilder();
        details.append(&quot;Id:&quot;+this.id);
        details.append(&quot; revision:&quot;+this.revision);
        details.append(&quot; state:&quot;+this.state);
        return details.toString();
    }

}
</code></pre>
<p><strong>How to write test case for it or how can validate in unit testing  and also want to cover toString() method in unit testing ?</strong></p>
",https://stackoverflow.com/questions/76173145/how-to-test-model-class-using-junit-to-cover-field-validations,"['spring-boot', 'unit-testing', 'junit', 'mocking', 'junit5']",72,True,0,1
how to test property value after calling void method in c# unit test,"<p>I'm new to Unit Testing. I tried to test property value after calling void method but test fail. For this task I created mock object and setup property value and test successfully while dealing with property. When I call &quot;Calling()&quot; Method its assigning the string value to that property now I want to test that assigned value in unit testing after calling void method.</p>
<p>Thanks in advance any help to save my time today.</p>
<pre><code>public class ClassTest
{
        [Fact]
        public void Demo_Calling_Test()
        {
            var mock=new Mock&lt;IDemo&gt;();
            mock.SetupProperty(x =&gt; x.Name, &quot;test&quot;);
            var result=mock.Object.Name;
            Assert.Equal(&quot;test&quot;, result);
            mock.Setup(x =&gt; x.Calling());
            Assert.Equal(&quot;Calling&quot;, result);
        }
}

public interface IDemo
    {
        string Name { get; set; }
        void Calling(); 
    }

public class Demo : IDemo
    {
        public string Name { get; set; }
        public void Calling()
        {
            Name = &quot;Calling&quot;;
            //Calling
        }
    }
</code></pre>
<p>When I run my test case its working fine up to this line i.e Assert.Equal(&quot;test&quot;,result);, After that i'm getting error, that error message which I copy and paste here.
Message: 
Assert.Equal() Failure
↓ (pos 0)
Expected: Calling
Actual:   test
↑ (pos 0)</p>
",https://stackoverflow.com/questions/75651178/how-to-test-property-value-after-calling-void-method-in-c-unit-test,"['c#', 'unit-testing', 'xunit']",78,False,-2,1
expect(received).toEqual(expected) // deep equality error Jest unit testing,"<p>I am doing unit testing with Jest and got the error in <code>user.controller.spec.ts</code> file. Other files got passed.</p>
<p>Old error:</p>
<pre><code> PASS  src/app.controller.spec.ts (10.482 s)
 PASS  src/users/services/users.service.spec.ts (11.629 s)
 FAIL  src/users/controllers/users.controller.spec.ts (12.239 s)
  ● UsersController › should create a user

    expect(received).toEqual(expected) // deep equality

    - Expected  - 5
    + Received  + 1

    - Object {
    -   &quot;birthDate&quot;: 2000-06-07T00:00:00.000Z,
    -   &quot;email&quot;: &quot;xs@gsuj.lk&quot;,
    -   &quot;name&quot;: &quot;aqs&quot;,
    - }
    + Promise {}

      45 |   it('should create a user' , () =&gt;{
      46 |     const dto ={id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : &quot;xs@gsuj.lk&quot; };
    &gt; 47 |     expect(controller.create(dto)).toEqual({
         |                                    ^
      48 |
      49 |       name:dto.name,
      50 |       birthDate :dto.birthDate,

      at Object.&lt;anonymous&gt; (src/users/controllers/users.controller.spec.ts:47:36)
</code></pre>
<p>Old error got resolved and now getting this new error:</p>
<pre><code> PASS  src/app.controller.spec.ts (10.573 s)
 PASS  src/users/services/users.service.spec.ts (11.867 s)
 FAIL  src/users/controllers/users.controller.spec.ts (12.282 s)
  ● UsersController › should create

    expect(received).toEqual(expected) // deep equality

    Expected: {&quot;birthDate&quot;: 2000-06-07T00:00:00.000Z, &quot;email&quot;: &quot;xs@gsuj.lk&quot;, &quot;id&quot;: 2, &quot;name&quot;: &quot;aqs&quot;}
    Received: &quot;user created successfully&quot;

      62 |     const data = await controller.create(dto);
      63 |
    &gt; 64 |          expect(data).toEqual({
         |                       ^
      65 |           id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : &quot;xs@gsuj.lk&quot;
      66 |          })
      67 |     expect(controller).toBeDefined();

      at src/users/controllers/users.controller.spec.ts:64:23
      at fulfilled (src/users/controllers/users.controller.spec.ts:5:58)

Test Suites: 2 failed, 2 passed, 4 total
Tests:       1 failed, 4 passed, 5 total
</code></pre>
<p>This is <strong>Older</strong> <code>user.controller.spec.ts</code> file:</p>
<pre><code>import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from '../services/users.service';
import { UsersController } from './users.controller';

describe('UsersController', () =&gt; {
  let controller: UsersController; 
  
   const mockUsersService ={
    create: jest.fn(dto =&gt; {
      return {
         
        ...dto
      };
    }),
    update:jest.fn((id,dto) =&gt;({
      id,
      ...dto
    }))
   }

  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UsersController],
      providers:[UsersService],
    })
    .overrideProvider(UsersService)
    .useValue(mockUsersService)
    .compile();

    //get service module from user module
     controller = module.get&lt;UsersController&gt;(UsersController);
  });

  //check if service available
  it('should be defined', () =&gt; {
    expect(controller).toBeDefined();
  });

  // it('hould create a user', () =&gt; {
  //   expect(controller.create({name:'aqs'})).toEqual({

  //   });
  // });

  it('should create a user' , () =&gt;{
    const dto ={id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : &quot;xs@gsuj.lk&quot; };
    expect(controller.create(dto)).toEqual({
      id:dto.id,
      name:dto.name,
      birthDate :dto.birthDate,
      email : dto.email
    });

    expect(mockUsersService.create).toHaveBeenCalledWith(dto);
  });
})
</code></pre>
<p>This is <strong>new</strong> <code>user.controller.spec.ts</code> file:</p>
<pre><code>import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from '../services/users.service';
import { UsersController } from './users.controller';

describe('UsersController', () =&gt; {
  let controller: UsersController; 
  
   const mockUsersService ={
    create: jest.fn(dto =&gt; {
      return {
         
        ...dto
      };
    }),
    update:jest.fn((id,dto) =&gt;({
      id,
      ...dto
    }))
   }

  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UsersController],
      providers:[UsersService],
    })
    .overrideProvider(UsersService)
    .useValue(mockUsersService)
    .compile();

    //get service module from user module
     controller = module.get&lt;UsersController&gt;(UsersController);
  });

  //check if service available
  it('should be defined', () =&gt; {
    expect(controller).toBeDefined();
  });

  // it('hould create a user', () =&gt; {
  //   expect(controller.create({name:'aqs'})).toEqual({

  //   });
  // });

  // it('should create a user' , () =&gt;{
  //   const dto ={id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : &quot;xs@gsuj.lk&quot; };

  //   expect(controller.create(dto)).toEqual({
  //     id:dto.id,
  //     name:dto.name,
  //     birthDate :dto.birthDate,
  //     email : dto.email
  //   });
    
  //   expect(mockUsersService.create).toHaveBeenCalledWith(dto);
  // });

  it('should create', async () =&gt; {

    const dto ={id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : &quot;xs@gsuj.lk&quot; };

    const data = await controller.create(dto);
     
         expect(data).toEqual({ 
          id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : &quot;xs@gsuj.lk&quot; 
         })
    expect(controller).toBeDefined();
  });
})
</code></pre>
<p><code>user.service.spec.ts</code> file:</p>
<pre><code>import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { getRepository } from 'typeorm';
//import { UsersController } from '../controllers/users.controller';
import { UsersService } from './users.service';
import {User} from '../entities/user.entity'

describe('UsersService', () =&gt; {
  let service: UsersService;
//  let providers:UsersController;

const mockUsersRepository ={
  create:jest.fn().mockImplementation(dto =&gt;dto),
  save:jest.fn().mockImplementation(user =&gt; Promise.resolve({id:2, ...user}))

}

  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      providers: [UsersService, {
        provide:getRepositoryToken(User),
        useValue:mockUsersRepository,
      },
    ],
    }).compile();

    service = module.get&lt;UsersService&gt;(UsersService);
  });

  it('should be defined', () =&gt; {
    expect(service).toBeDefined();
  });

  it('should be create a new user record and return that', async () =&gt; {
    expect( await service.create({id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : &quot;xs@gsuj.lk&quot; })).toEqual({
      id:2, 
      name:'aqs',
      birthDate: new Date('2000-06-07'), 
      email : &quot;xs@gsuj.lk&quot; ,
    });
  });
});
</code></pre>
",https://stackoverflow.com/questions/75043375/expectreceived-toequalexpected-deep-equality-error-jest-unit-testing,"['jestjs', 'nestjs', 'deepequals']",1186,False,0,1
is there a way to test data update failure in laravel unit test,"<p>I'm doing the unit testing in Laravel. I wrote a test for the if function (data store). but I want to know how to write test for else part. when data save is failure, an error message return.</p>
<pre><code>    public function store(Request $request)
    {
        $user = $this-&gt;user-&gt;create($request-&gt;all());

        if ($user) {
            return response()-&gt;json([
                'message' =&gt; 'Data saved successfully,
                'data' =&gt; [
                    'user' =&gt; $user
                ]
            ]);
        } else {
            return response()-&gt;json([
                'message' =&gt; 'Data save failed.'
            ], 400);
        }
    }
</code></pre>
",https://stackoverflow.com/questions/75522634/is-there-a-way-to-test-data-update-failure-in-laravel-unit-test,"['php', 'laravel', 'unit-testing', 'laravel-5', 'phpunit']",47,False,0,0
Pytest DID NOT RAISE &lt;class &#39;Exception&#39;&gt;,"<p>When unit testing an except I am getting an error that it did not raise. Not sure where it is going wrong.</p>
<p>The code being tested:</p>
<pre><code>@bp.route(&quot;/contact/&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;])
@login_required
def contact_details():
    if request.form:
        contacts = contact(username=request.form.get(&quot;username&quot;), email=request.form.get(&quot;email&quot;),details=request.form.get(&quot;details&quot;))
        try:
            db.session.add(contacts)
            db.session.commit()
            flash(&quot;Your query has been raised successfully.&quot;)
            return redirect(url_for(&quot;main.home&quot;))
        except:
            flash(&quot;There has been an issue trying to raise a contact ticket.&quot;)
            return render_template(&quot;main/home.html&quot;)
    return render_template(&quot;main/contact.html&quot;)
</code></pre>
<p>Pytest:</p>
<pre><code>def test_contact_ticket_error(client):
    client.post('/register', data={&quot;username&quot;: &quot;tester1&quot;, &quot;password&quot;: &quot;password&quot;}, follow_redirects =True)
    client.post('/', data={&quot;username&quot;: &quot;tester1&quot;, &quot;password&quot;: &quot;password&quot;}, follow_redirects = True)

    with pytest.raises(Exception):
        response = client.post(&quot;/contact/&quot;, data = {&quot;username&quot;:&quot;tester1&quot;,&quot;email&quot;:&quot;tester@gmail.com&quot;,&quot;details&quot;:&quot;testing contact&quot;})
    assert b'There has been an issue trying to raise a contact ticket.' in response.data
    
</code></pre>
<p>Need advise on how to resolve this issue so test passes.</p>
",https://stackoverflow.com/questions/75901521/pytest-did-not-raise-class-exception,"['python', 'flask', 'pytest']",200,False,0,1
Jest encountered an unexpected token + markdown-to-jsx,"<p>I have a problem with unit testing using markdown-to-jsx and react testing libraries in React</p>
<pre><code>Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default &quot;node_modules&quot; folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your &quot;node_modules&quot; files transformed, you can specify a custom &quot;transformIgnorePatterns&quot; in your config.
     • If you need a custom transformation specify a &quot;transform&quot; option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the &quot;moduleNameMapper&quot; config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /Users/albautis/Documents/Demonware/Devzone/Frontend/devzone-frontend/src/dw/devzone-docs/scenes/upcomingFeatures/upcomingFeatures.md:1
    ({&quot;Object.&lt;anonymous&gt;&quot;:function(module,exports,require,__dirname,__filename,jest){&lt;body class=&quot;publish&quot;&gt;
                                                                                      ^

    SyntaxError: Unexpected token '&lt;'
</code></pre>
<p>I already tried adding the Markdown to JSX to the transform ignore patterns, but it still doesn't work</p>
<p>here's my jest.config</p>
<pre><code> transformIgnorePatterns: ['node_modules/(?!markdown-to-jsx/)'],
 moduleNameMapper: {
    '^markdown-to-jsx': '&lt;rootDir&gt;/node_modules/markdown-to-jsx/dist/cjs.js',
  },
</code></pre>
",https://stackoverflow.com/questions/76114583/jest-encountered-an-unexpected-token-markdown-to-jsx,"['reactjs', 'jestjs', 'react-testing-library']",17,False,0,0
Karma start error :Local host refused to connect,"<p>I am new to testing and tried to perform unit testing by using Karma start command. It is starting the Karma server and opening on Chrome browser. But it only shows localhost refused to connect.</p>
<pre><code>Karma.conf.js
module.exports = function(config) {
    config.set({
        browsers: ['Chrome'],
        singleRun: true,
        frameworks: ['jasmine'],
          plugins: [
            'karma-chrome-launcher',
            'karma-jasmine'
          ],
          colors: true,
          autoWatch: true
        
      });
  };
</code></pre>
<p><a href=""https://i.stack.imgur.com/s7ATX.jpg"" rel=""nofollow noreferrer"">Terminal view</a></p>
<p><a href=""https://i.stack.imgur.com/4DND6.jpg"" rel=""nofollow noreferrer"">Browser view</a></p>
",https://stackoverflow.com/questions/75775525/karma-start-error-local-host-refused-to-connect,"['unit-testing', 'jasmine', 'karma-jasmine']",43,False,0,0
Angular Unit testing for Safe Pipe,"<p>I am trying to write a unit testing case without using fixtures. But it keep throwing me an error</p>
<p>I am getting an error of</p>
<pre><code>this.sanitizer.bypassSecurityTrustResourceUrl is not a function
</code></pre>
<pre><code>  constructor(private sanitizer: DomSanitizer) {}

  transform(value: string): SafeResourceUrl {
    return this.sanitizer.bypassSecurityTrustResourceUrl(value);
  }
</code></pre>
<pre><code>  it('should return safe url', () =&gt; {
    const pipe = new SafeUrlPipe(&lt;DomSanitizer&gt;{});
    pipe.transform('val');
    expect(pipe).toBeTruthy();
  });
</code></pre>
<p>I have try too make it undefined or match but it still haven't work</p>
",https://stackoverflow.com/questions/75010760/angular-unit-testing-for-safe-pipe,"['angular', 'karma-jasmine']",98,False,0,1
how to mock Supabase with Flutter for unit testing?,"<p>I'm trying to do unit test with Supabase in Flutter like the code bellow:</p>
<pre><code>import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:supabase_flutter/supabase_flutter.dart';


class TestMClass {
  SupabaseClient client;
  TestMClass({
    required this.client,
  });
  Future&lt;AuthResponse&gt; signinMc() async {
    final respnse = await client.auth
        .signInWithPassword(email: 'example@gmail', password: 'password');
    return respnse;
  }
}

class MockSupabaseClient extends Mock implements SupabaseClient {}

void main() async {
  
  final MockSupabaseClient mockClient = MockSupabaseClient();

  final TestMClass testMCass = TestMClass(client: mockClient);
  setUp(() {});
  group('TestAuthBloc', () {
    test('description', () async {
      final auth = await testMCass.signinMc();
      expect(auth, isA&lt;AuthResponse&gt;());
    });
  });
}
</code></pre>
<p>it throw this error:....</p>
<blockquote>
<p>type 'Null' is not a subtype of type 'GoTrueClient'</p>
</blockquote>
<p>how I can Mock or do unit testing for Supabase functions with Flutter?</p>
",https://stackoverflow.com/questions/75953444/how-to-mock-supabase-with-flutter-for-unit-testing,"['flutter', 'dart', 'unit-testing', 'mocking', 'supabase']",195,False,0,2
Unit testing Rx Catch,"<p>I'm unit testing the following service and the issue is that I'm able to test only the happy path but not the unhappy path. So how do I test them? TestScheduler? <a href=""http://introtorx.com/Content/v1.0.10621.0/16_TestingRx.html"" rel=""nofollow noreferrer"">http://introtorx.com/Content/v1.0.10621.0/16_TestingRx.html</a></p>
<p>These lines are left untested:</p>
<pre class=""lang-cs prettyprint-override""><code>.Catch&lt;string, TimeoutExceptiocn&gt;(_ =&gt; Observable.Return(&quot;Timeout&quot;))
.Catch&lt;string, Exception&gt;(ex =&gt; Observable.Return(ex.Message))
</code></pre>
<p><a href=""https://i.stack.imgur.com/Y1EEy.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Y1EEy.png"" alt=""enter image description here"" /></a></p>
<pre class=""lang-cs prettyprint-override""><code>public interface IProductService
{
    Task&lt;string&gt; GetAsync();
}

public sealed class ProductService : IProductService
{
    private readonly HttpClient _httpClient;

    public ProductService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public Task&lt;string&gt; GetAsync()
    {
        return Observable
            .FromAsync(() =&gt; _httpClient.GetAsync(&quot;http://www.mocky.io/v2/5e307edf3200005d00858b49&quot;))
            .SubscribeOn(TaskPoolScheduler.Default)
            .Retry(5)
            .Timeout(TimeSpan.FromSeconds(5))
            .Do(x =&gt; Console.WriteLine($&quot;Is message successful? {x.IsSuccessStatusCode}&quot;))
            .SelectMany(async responseMessage =&gt;
            {
                var response = await responseMessage.Content.ReadAsStringAsync();
                return response;
            })
            .Catch&lt;string, TimeoutException&gt;(_ =&gt; Observable.Return(&quot;Timeout&quot;))
            .Catch&lt;string, Exception&gt;(ex =&gt; Observable.Return(ex.Message))
            .ToTask();
    }
}
</code></pre>
<pre class=""lang-cs prettyprint-override""><code>public class ProductServiceTests
{
    [Fact]
    public async Task GetAsync_ShouldReturnText_WhenRequestIsSent()
    {
        // Arrange
        var messageHandler = new MockHttpMessageHandler(&quot;Stuff I want to return&quot;, HttpStatusCode.OK);
        var httpClient = new HttpClient(messageHandler);
        var sut = new ProductService(httpClient);

        // Act
        var result = await sut.GetAsync();

        // Assert
        result.Should().Be(&quot;Stuff I want to return&quot;);
    }

    // TODO: Unhappy path
}
</code></pre>
",https://stackoverflow.com/questions/75178879/unit-testing-rx-catch,"['c#', '.net', 'unit-testing', 'system.reactive']",51,False,0,0
Testing Redux reducer fails to pass,"<p>New to unit testing in general and especially in Redux, forgive the dumb question.</p>
<p>I'm trying to test a simple reducer but can't get to make it work.</p>
<p>Reducer:</p>
<pre><code>import { ActionTypes } from &quot;../constants/action-types&quot;;

const initialState = {
  products: [],
};

export const productReducer = (state = initialState, { type, payload }) =&gt; {
  switch (type) {
    case ActionTypes.FETCH_PRODUCTS:
      return { ...state, products: payload };
    case ActionTypes.RESET_PRODUCTS:
      return {};
    default:
      return state;
  }
};
</code></pre>
<p>Test:</p>
<pre><code>import { ActionTypes } from &quot;../../redux/constants/action-types&quot;;
import { productReducer } from &quot;.././../redux/reducers/productReducer&quot;;

describe(&quot;Product reducer&quot;, () =&gt; {
  describe(&quot;fetching products&quot;, () =&gt; {
    it(&quot;adds products&quot;, () =&gt; {
      const action = {
        type: ActionTypes.FETCH_PRODUCTS,
        product: [{ name: &quot;test&quot; }],
      };

      const initialState = undefined;
      const nextState = productReducer(initialState, action);

      expect(nextState).toEqual([{ name: &quot;test&quot; }]);
    });
  });
});
</code></pre>
<p>That's what I get:</p>
<pre><code>expect(received).toEqual(expected) // deep equality

Expected: [{&quot;name&quot;: &quot;test&quot;}]
Received: {&quot;products&quot;: undefined}
</code></pre>
<p>Just don't understand how to test it.</p>
",https://stackoverflow.com/questions/75398425/testing-redux-reducer-fails-to-pass,"['javascript', 'unit-testing', 'redux']",42,True,0,1
Unit Testing Object Box for Flutter App in macOS is failing,"<p>While reading from object box for doing unit testing for flutter app in mac, it is giving error like</p>
<p><code>RangeError (byteOffset): Invalid value: Valid value range is empty: 0</code></p>
<p>It is coming for any call of <code>query.find()</code>. Object box version is 1.6.2</p>
<p>How to get around this ?</p>
<p>Edit code for reproducibility</p>
<pre><code>final query = _box.query(any query).build(); 
final data = query.find(); 
query.close(); 
return data;
</code></pre>
",https://stackoverflow.com/questions/76236329/unit-testing-object-box-for-flutter-app-in-macos-is-failing,"['flutter', 'flutter-objectbox']",20,False,0,0
Unit testing a generic base Controller using Moq and Xunit,"<p>I currently have a base class like this:</p>
<pre><code>public abstract class AbstractControllerBase&lt;T&gt; : Controller where T : AbstractControllerBase&lt;T&gt;
{
    private ILogger&lt;T&gt; _logger;

    protected ILogger&lt;T&gt; Logger =&gt; _logger ??= HttpContext.RequestServices.GetService&lt;ILogger&lt;T&gt;&gt;();

    public AbstractControllerBase()
    { }
}
</code></pre>
<p>and inherited class like this:</p>
<pre><code>public abstract class ControllerBase&lt;T&gt; : AbstractControllerBase&lt;T&gt; where T : ControllerBase&lt;T&gt;
{
    private IRepository _repository;

    protected IRepository Repository
    {
        get
        {
            if (_repository == null &amp;&amp; HttpContext != null)
                _repository = (IRepository)HttpContext.RequestServices.GetService(typeof(IRepository));
            return _repository;
        }
    }

    public ControllerBase()
    { }

    public IActionResult CheckRedirectUrl(string url)
    {
        if (Url.IsLocalUrl(url))
        {
            var redirectResult = Redirect(url);
            return redirectResult;
        }
        else
        {
            return RedirectToAction(&quot;Index&quot;, &quot;Home&quot;);
        }
    }
}
</code></pre>
<p>There are 25 controllers which inherit from ControllerBase. How to init Repository while unit testing. I tried doing this:</p>
<pre><code>if (controller is Website.Controllers.ControllerBase &lt; typeof(controller) &gt;)
{
    ((Website.Controllers.ControllerBase)controller).Repository = repository;
}
</code></pre>
<p>But this requires generic arguments as well. Kindly suggest.</p>
",https://stackoverflow.com/questions/75691839/unit-testing-a-generic-base-controller-using-moq-and-xunit,"['c#', '.net', 'asp.net-core', 'moq', 'xunit.net']",100,False,0,1
How (and should) I verify that an async internal method was called in State Unit Testing?,"<pre><code>   override fun getSomething(): LiveData&lt;List&lt;Content&gt;&gt; {
        fakeDataSource.fetchSomethingAsync()
        return contentDao.getSomething()
    }
</code></pre>
<p>Here we have a repository method to get some data remotely, and in the meantime return some livedata from a Room database. The viewmodel that calls this method in the repository doesn't care that the repository is fetching the data from the network behind the scenes - it just knows that it's getting back some livedata and monitoring it for changes.</p>
<p>Now I have to unit test this method. State based unit testing says that all I care about is the state of the system after the call (while behavior unit testing would absolutely require me to verify the async call). Here the fact that another class (fakeDataSource) is asynchronously changing the state at some later time should be afaik irrelevant to me in the context of the unit test of this particular method(?)</p>
<p>So I return a fake item from my fake dao, and my test looks like:</p>
<pre><code>   @Test
    fun getSomething_returnsLocal() {
        val result: LiveData&lt;List&lt;Content&gt;&gt; = testedContentRepository.getSomething()
        result.value?.let {
            assert(it.isNotEmpty())
        }
    }
</code></pre>
<p>Is this good enough, or should I care in my unit test that there was something else happening here - an async call to the network - and should I be testing it? If the answer to that question is 'yes', is there a way of <strong>unit</strong> testing it without mocking the datasource (given that best practice nowadays is more and more towards fakes over mocks)?</p>
",https://stackoverflow.com/questions/75847745/how-and-should-i-verify-that-an-async-internal-method-was-called-in-state-unit,"['android', 'kotlin', 'unit-testing', 'testing', 'mocking']",20,True,1,1
"unittesting vuejs plugin, &quot;Cannot set properties of null&quot;","<p>Having trouble unit testing a specific vuejs plugin, but I think my problem is more of a general lack of understanding unit testing in the vuejs framework.</p>
<p>The plugin is the <a href=""https://github.com/DongKyuuuu/vue3-recaptcha-v2"" rel=""nofollow noreferrer"">vue3-recaptcha-v2</a> plugin. I have a component App.vue with the following</p>
<pre><code>&lt;script setup&gt;
import { ref } from &quot;vue&quot;
import { VueRecaptcha } from &quot;vue3-recaptcha-v2&quot;
const recaptchaWidget = ref(null)
&lt;/script&gt;

&lt;template&gt;
&lt;vue-recaptcha @widget-id=&quot;recaptchaWidget = $event&quot; /&gt;
&lt;/template&gt;
</code></pre>
<p>The little app works as expected, but I can't develop a unit test harness to test my app. My unit test is this:</p>
<pre><code>import { describe, it } from 'vitest'
import { mount, config } from '@vue/test-utils'
import VueRecaptcha from 'vue3-recaptcha-v2'
import App from '../App.vue'

config.plugins.VueWrapper.install(VueRecaptcha, { siteKey: 'fake-key'})

describe('App test', () =&gt; {
  it('mount properly', () =&gt; {
    mount(App)
  })
})
</code></pre>
<p>A run of <code>npm run test:unit</code></p>
<p>Yields the error:</p>
<pre><code>stderr | src/__tests__/App.test.js &gt; App test &gt; mount properly
[Vue warn]: injection &quot;Symbol(recaptchaSiteKey)&quot; not found.
  at &lt;VueRecaptcha onWidgetId=fn &gt;
  at &lt;App ref=&quot;VTU_COMPONENT&quot; &gt;
  at &lt;VTUROOT&gt;

 ❯ src/__tests__/App.test.js (1)
   ❯ App test (1)
     × mount properly

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯

 FAIL  src/__tests__/App.test.js &gt; App test &gt; mount properly
TypeError: Cannot set properties of null (setting 'onload')
 ❯ node_modules/vue3-recaptcha-v2/dist/vue3-recaptcha-v2.js:1:1342
</code></pre>
<p>I believe the onload reference is because the VueRecaptcha plugin is attempting to set an onload event-handler on the dom which must not yet be setup correctly?  Sorry, I'm lost and have been working on this for several days.  If anyone could point me in the right direction, it would be much appreciated.</p>
<p><strong>Versions</strong></p>
<pre><code>  &quot;dependencies&quot;: {
    &quot;vue&quot;: &quot;^3.2.47&quot;,
    &quot;vue3-recaptcha-v2&quot;: &quot;^1.0.1&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@vitejs/plugin-vue&quot;: &quot;^4.0.0&quot;,
    &quot;@vue/test-utils&quot;: &quot;^2.3.0&quot;,
    &quot;jsdom&quot;: &quot;^21.1.0&quot;,
    &quot;vite&quot;: &quot;^4.1.4&quot;,
    &quot;vitest&quot;: &quot;^0.29.1&quot;
  }
</code></pre>
",https://stackoverflow.com/questions/76123329/unittesting-vuejs-plugin-cannot-set-properties-of-null,"['unit-testing', 'vuejs3', 'vitest']",31,False,0,0
Best practises on writing Glue Jobs (pyspark),"<p>Looking at the example here(<a href=""https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-libraries.html"" rel=""nofollow noreferrer"">https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-libraries.html</a>) this seems to be the way to build a pyspark script, where the class is called to initialise the job and then runs a function outside the class (I am not sure whether this was done to allow unit testing?). Is this normal behaviour, wouldn't it be better to have the function inside the class? I was also wondering whether something such as this (<a href=""https://github.com/aws-samples/aws-glue-jobs-unit-testing/blob/main/src/sample.py"" rel=""nofollow noreferrer"">https://github.com/aws-samples/aws-glue-jobs-unit-testing/blob/main/src/sample.py</a>) is more common practise? I am just looking really best way to build out my scripts in a repeatable format and make it easy to unit test as well?</p>
<pre><code>import sys
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
from awsglue.utils import getResolvedOptions


class GluePythonSampleTest:
    def __init__(self):
        params = []
        if '--JOB_NAME' in sys.argv:
            params.append('JOB_NAME')
        args = getResolvedOptions(sys.argv, params)

        self.context = GlueContext(SparkContext.getOrCreate())
        self.job = Job(self.context)

        if 'JOB_NAME' in args:
            jobname = args['JOB_NAME']
        else:
            jobname = &quot;test&quot;
        self.job.init(jobname, args)

    def run(self):
        dyf = read_json(self.context, &quot;s3://awsglue-datasets/examples/us-legislators/all/persons.json&quot;)
        dyf.printSchema()

        self.job.commit()


def read_json(glue_context, path):
    dynamicframe = glue_context.create_dynamic_frame.from_options(
        connection_type='s3',
        connection_options={
            'paths': [path],
            'recurse': True
        },
        format='json'
    )
    return dynamicframe


if __name__ == '__main__':
    GluePythonSampleTest().run()
</code></pre>
",https://stackoverflow.com/questions/75300607/best-practises-on-writing-glue-jobs-pyspark,"['amazon-web-services', 'pyspark', 'aws-glue']",76,False,0,0
Importing a transpiled package for unit testing,"<p>I have a TypeScript package that is shipped transpiled to JS with rollup. The package uses <code>type: module</code> and rollup produces the following files:</p>
<pre><code>dist/cjs/index.cjs
dist/es6/index.mjs
dist/browser/index.js
dist/types.d.ts
</code></pre>
<p>My unit testing is also in TypeScript so that I can test the typings. I use mocha with all the special configuration:</p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;spec&quot;: &quot;test/*.test.@(cjs|mjs|ts)&quot;,
  &quot;require&quot;: [
    &quot;ts-node/register&quot;
  ],
  &quot;loader&quot;: &quot;ts-node/esm&quot;
}
</code></pre>
<p>The problem is that I cannot easily import this package from the unit testing. I cannot import <code>'..'</code> or use <code>tsconfig-paths</code> since <code>type: module</code> disallows directory imports. If I import <code>../dist/cjs/index.cjs</code> I lose the typings. Does anyone see any way I could import the compiled package with the typings?</p>
<p>Currently the only solution is to drop <code>type: module</code> and use <code>import from '..'</code> - which means I am going back 5 years.</p>
<p>The package is <a href=""https://github.com/mmomtchev/query-mvt"" rel=""nofollow noreferrer"">https://github.com/mmomtchev/query-mvt</a> if anyone is interested. I have currently dropped <code>type: module</code>.</p>
",https://stackoverflow.com/questions/75550544/importing-a-transpiled-package-for-unit-testing,['typescript'],25,False,0,0
Angular Unit testing event handle keypress is not returning the right value,"<p>I trying to do a unit testing for angular in jasmine test framework for an event of key event. I want to make the index become 0 when the value is less than 0.</p>
<pre><code>      if ($event.code === 'ArrowUp') {
          if (this.currentIndex &lt; 0) {
              this.currentIndex = 0;
          } else if (this.currentIndex &gt; 0) {
              this.currentIndex--;
          }
</code></pre>
<pre><code>    it('should return 0 when value is less than 0', () =&gt; {
      const event = new KeyboardEvent('ArrowUp', { code: 'ArrowUp' });
      component['currentIndex'] = -5;
      component.handleKeyboardEvents(event);
      expect(component['currentIndex']).toBe(0);
    });
</code></pre>
<p>it doesnt seem like the value was reassign</p>
",https://stackoverflow.com/questions/75015048/angular-unit-testing-event-handle-keypress-is-not-returning-the-right-value,"['angular', 'karma-jasmine', 'karma-runner']",27,False,0,0
Why am I facing this TypeError in Angular unit testing?,"<pre><code>this.columnDefs.forEach((columnDef) =&gt; {
  columnDef.floatingFilter = this.hasFloatingFilter;
});
this.gridApi.setColumnDefs(this.columnDefs);
</code></pre>
<p>ERROR: 'ERROR', TypeError: this.gridApi.setColumnDefs is not a function
TypeError: this.gridApi.setColumnDefs is not a function</p>
<p>I have declared a variable gridApi of type GridApi from 'ag-grid-community'.
Even though setColumnDefs() is a function. On unit testing, I find the above mentioned error.</p>
",https://stackoverflow.com/questions/76235126/why-am-i-facing-this-typeerror-in-angular-unit-testing,"['angular', 'typescript', 'typeerror', 'ag-grid']",24,False,0,1
How can I use Debug tool for finding ClassCastException during unit test?,"<p>I got this error while unit testing.</p>
<pre><code>class com.example.model.common.shop.manager_cart.CartInfo cannot be cast to class kotlin.Result (com.example.model.common.shop.manager_cart.CartInfo and kotlin.Result are in unnamed module of loader 'app')
java.lang.ClassCastException: class com.example.model.common.shop.manager_cart.CartInfo cannot be cast to class kotlin.Result (com.example.model.common.shop.manager_cart.CartInfo and kotlin.Result are in unnamed module of loader 'app')
    at com.example.store.ui.feature.result.CartUiUpdateManager.updateCartUi(CartUiSyncManager.kt:30)
    at com.example.store.ui.feature.result.CartUiUpdateManager$updateCartUi$1.invokeSuspend(CartUiSyncManager.kt)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTaskKt.resume(DispatchedTask.kt:234)
    at kotlinx.coroutines.DispatchedTaskKt.dispatch(DispatchedTask.kt:166)
    at kotlinx.coroutines.CancellableContinuationImpl.dispatchResume(CancellableContinuationImpl.kt:397)
    at kotlinx.coroutines.CancellableContinuationImpl.resumeImpl(CancellableContinuationImpl.kt:431)
    at kotlinx.coroutines.CancellableContinuationImpl.resumeImpl$default(CancellableContinuationImpl.kt:420)
    at kotlinx.coroutines.CancellableContinuationImpl.resumeUndispatched(CancellableContinuationImpl.kt:518)
    at kotlinx.coroutines.EventLoopImplBase$DelayedResumeTask.run(EventLoop.common.kt:500)
    at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:284)
    at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:85)
    at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:59)
    at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
    at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:38)
    at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
    at com.example.store.CartUiUpdateManagerTest.sending three requests must call onWarn, move request to tempRequestQueue, process and call onSuccess(CartUiUpdateManagerTest.kt:43)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
    at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at jdk.proxy1/jdk.proxy1.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$2.run(TestWorker.java:176)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)

and `updateCartUi(CartUiSyncManager.kt:30)` is `val result = request.invoke()`
</code></pre>
<p>Here's the CartUiUpdateManager class.</p>
<pre><code>class CartUiUpdateManager {
    private var lastRequestHashCode = 0
    val requestQueue: MutableList&lt;suspend () -&gt; Result&lt;CartInfo&gt;&gt; = mutableListOf()
    val tempRequestQueue: MutableList&lt;suspend () -&gt; Result&lt;CartInfo&gt;&gt; = mutableListOf()
    private var isCalling = false
    suspend fun updateCartUi(
        newRequest: suspend () -&gt; Result&lt;CartInfo&gt;,
        onSuccess: suspend (CartInfo) -&gt; Unit,
        onFailure: suspend (Throwable) -&gt; Unit,
        onWarn: suspend (String) -&gt; Unit
    ) {
        if (requestQueue.size == MAX_REQUEST) {
            onWarn.invoke(&quot;Too many requests. Please wait.&quot;)
            tempRequestQueue.add(newRequest)
            return
        }

        requestQueue.add(newRequest)

        while (requestQueue.isNotEmpty()) {
            isCalling = true
            val request = requestQueue.removeFirst()
            lastRequestHashCode = newRequest.hashCode()
            delay(DELAY_BETWEEN_API)

            val response: Result&lt;CartInfo&gt; = request.invoke()

            response.onSuccess {
                if (tempRequestQueue.isNotEmpty()) {
                    requestQueue.add(tempRequestQueue.removeFirst())
                    requestQueue.add(tempRequestQueue.removeFirst())
                } else if (requestQueue.isEmpty() &amp;&amp; lastRequestHashCode == newRequest.hashCode()) {
                    isCalling = false
                    onSuccess.invoke(it)
                }
            }.onFailure {
                if (requestQueue.isEmpty() &amp;&amp; tempRequestQueue.isEmpty()) {
                    isCalling = false
                }
                onFailure.invoke(it)
            }
        }
    }

    companion object {
        const val MAX_REQUEST = 2
        const val DELAY_BETWEEN_API = 70L
    }
}
</code></pre>
<p>And here's my unit test code.</p>
<pre><code>import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import com.example.model.common.shop.manager_cart.CartInfo
import com.example.store.ui.feature.result.CartUiUpdateManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test

class CartUiUpdateManagerTest {
    @get:Rule
    var instantExecutorRule = InstantTaskExecutorRule()

    private lateinit var cartUiUpdateManager: CartUiUpdateManager

    @Before
    fun setUp() {
        Dispatchers.setMain(Dispatchers.Unconfined)
        cartUiUpdateManager = CartUiUpdateManager()
    }

    @After
    fun tearDown() {
        Dispatchers.resetMain()
    }

    @Test
    fun `sending less than 3 request calls must call onSuccess`() = runTest {
        val mockRequest = mockk&lt;suspend () -&gt; Result&lt;CartInfo&gt;&gt;()
        val cartInfo = mockk&lt;CartInfo&gt;(relaxed = true)
        coEvery { mockRequest() } returns Result.success(cartInfo)

        val onSuccess = mockk&lt;suspend (CartInfo) -&gt; Unit&gt;(relaxed = true)
        val onFailure = mockk&lt;suspend (Throwable) -&gt; Unit&gt;(relaxed = true)
        val onWarn = mockk&lt;suspend (String) -&gt; Unit&gt;(relaxed = true)

        cartUiUpdateManager.updateCartUi(
            newRequest = mockRequest,
            onSuccess = onSuccess,
            onFailure = onFailure,
            onWarn = onWarn
        )
        cartUiUpdateManager.updateCartUi(
            newRequest = mockRequest,
            onSuccess = onSuccess,
            onFailure = onFailure,
            onWarn = onWarn
        )

        coVerify(exactly = 2) { onSuccess(cartInfo) }
        coVerify(exactly = 0) { onFailure(any()) }
        coVerify(exactly = 0) { onWarn(any()) }
    }

    @Test
    fun `sending three requests must call onWarn, move request to tempRequestQueue, process and call onSuccess`() = runBlocking {
        val mockRequest = mockk&lt;suspend () -&gt; Result&lt;CartInfo&gt;&gt;()
        val cartInfo = mockk&lt;CartInfo&gt;(relaxed = true)
        val successResult = Result.success(cartInfo)

        coEvery { mockRequest() } returns successResult

        val onSuccess = mockk&lt;suspend (CartInfo) -&gt; Unit&gt;(relaxed = true)
        val onFailure = mockk&lt;suspend (Throwable) -&gt; Unit&gt;(relaxed = true)
        val onWarn = mockk&lt;suspend (String) -&gt; Unit&gt;(relaxed = true)

        cartUiUpdateManager.updateCartUi(
            newRequest = mockRequest,
            onSuccess = onSuccess,
            onFailure = onFailure,
            onWarn = onWarn
        )
        cartUiUpdateManager.updateCartUi(
            newRequest = mockRequest,
            onSuccess = onSuccess,
            onFailure = onFailure,
            onWarn = onWarn
        )
        cartUiUpdateManager.updateCartUi(
            newRequest = mockRequest,
            onSuccess = onSuccess,
            onFailure = onFailure,
            onWarn = onWarn
        )

        coVerify(exactly = 1) { onWarn(&quot;Too many requests. Please wait.&quot;) }
        Assert.assertEquals(1, cartUiUpdateManager.tempRequestQueue.size)

        // Simulate the first two requests being processed successfully
        cartUiUpdateManager.requestQueue.clear()
        cartUiUpdateManager.tempRequestQueue.removeFirst()

        coVerify(exactly = 3) { onSuccess(cartInfo) }
        coVerify(exactly = 0) { onFailure(any()) }
    }
}
</code></pre>
<p>The problematic part is <code>val response: Result&lt;CartInfo&gt; = request.invoke()</code>. I don't know why it needs casting.</p>
<p>How can I debug and fix this issue so that those unit tests work fine?</p>
",https://stackoverflow.com/questions/76042069/how-can-i-use-debug-tool-for-finding-classcastexception-during-unit-test,"['android', 'kotlin', 'junit', 'mockk']",45,False,0,0
SpringBoot- convert SYS_REF_CURSOR into java List is not working,"<p><strong>pom.xml</strong></p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
  &lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;2.5.6&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;
  &lt;groupId&gt;com.xx.rt.report&lt;/groupId&gt;
  &lt;artifactId&gt;rt-report-service&lt;/artifactId&gt;
  &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
  &lt;name&gt;rt-report-service&lt;/name&gt;
  &lt;description&gt;Data check report&lt;/description&gt;
  &lt;properties&gt;
        &lt;java.version&gt;11&lt;/java.version&gt;
        &lt;spring-cloud.version&gt;2020.0.4&lt;/spring-cloud.version&gt;
        &lt;jacoco.version&gt;0.8.6&lt;/jacoco.version&gt;
        &lt;sonar.java.coveragePlugin&gt;jacoco&lt;/sonar.java.coveragePlugin&gt;
        &lt;sonar.dynamicAnalysis&gt;reuseReports&lt;/sonar.dynamicAnalysis&gt;
        &lt;sonar.jacoco.reportPath&gt;${project.basedir}/../target/jacoco.exec&lt;/sonar.jacoco.reportPath&gt;
        &lt;sonar.language&gt;java&lt;/sonar.language&gt;
    &lt;/properties&gt;
  &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.springfox&lt;/groupId&gt;
            &lt;artifactId&gt;springfox-swagger2&lt;/artifactId&gt;
            &lt;version&gt;2.9.2&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.springfox&lt;/groupId&gt;
            &lt;artifactId&gt;springfox-swagger-ui&lt;/artifactId&gt;
            &lt;version&gt;2.9.2&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-bootstrap&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-config&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
            &lt;artifactId&gt;lombok&lt;/artifactId&gt;
            &lt;optional&gt;true&lt;/optional&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-zipkin&lt;/artifactId&gt;
            &lt;version&gt;2.2.8.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-sleuth&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-client&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-feign&lt;/artifactId&gt;
            &lt;version&gt;1.4.7.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.oracle.database.jdbc&lt;/groupId&gt;
            &lt;artifactId&gt;ojdbc8&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-stream&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-stream-binder-rabbit&lt;/artifactId&gt;
        &lt;/dependency&gt; 
        &lt;dependency&gt;
            &lt;groupId&gt;javax.activation&lt;/groupId&gt;
            &lt;artifactId&gt;activation&lt;/artifactId&gt;
            &lt;version&gt;1.1.1&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;
            &lt;artifactId&gt;commons-collections4&lt;/artifactId&gt;
            &lt;version&gt;4.3&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;
            &lt;artifactId&gt;commons-compress&lt;/artifactId&gt;
            &lt;version&gt;1.18&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;commons-logging&lt;/groupId&gt;
            &lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
            &lt;version&gt;1.2&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;
            &lt;artifactId&gt;commons-math3&lt;/artifactId&gt;
            &lt;version&gt;3.6.1&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.github.virtuald&lt;/groupId&gt;
            &lt;artifactId&gt;curvesapi&lt;/artifactId&gt;
            &lt;version&gt;1.06&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.poi&lt;/groupId&gt;
            &lt;artifactId&gt;poi&lt;/artifactId&gt;
            &lt;version&gt;4.1.0&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.poi&lt;/groupId&gt;
            &lt;artifactId&gt;poi-excelant&lt;/artifactId&gt;
            &lt;version&gt;4.1.0&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.poi&lt;/groupId&gt;
            &lt;artifactId&gt;poi-scratchpad&lt;/artifactId&gt;
            &lt;version&gt;4.1.0&lt;/version&gt;
        &lt;/dependency&gt;
  &lt;/dependencies&gt;
  &lt;dependencyManagement&gt;
        &lt;dependencies&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
                &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;
                &lt;version&gt;${spring-cloud.version}&lt;/version&gt;
                &lt;type&gt;pom&lt;/type&gt;
                &lt;scope&gt;import&lt;/scope&gt;
            &lt;/dependency&gt;
        &lt;/dependencies&gt;
    &lt;/dependencyManagement&gt;
&lt;/project&gt;
</code></pre>
<p><strong>OpenFindingRepository.java</strong></p>
<pre><code>@Repository
public interface OpenFindingRepository extends CrudRepository&lt;OpenFindingDTO, Serializable&gt; {
    @Procedure(name=&quot;getOpenFindings&quot;)
    List&lt;OpenFindingDTO&gt; getOpenFindings(@Param(&quot;INPUT_DATE&quot;) String dataDate);
}
</code></pre>
<p><strong>OpenFindingDTO.java</strong></p>
<pre><code>@NamedStoredProcedureQueries({
@NamedStoredProcedureQuery(name = &quot;getOpenFindings&quot;,
    procedureName = &quot;OPEN_CODE_FINDINGS&quot;,
    resultClasses = OpenFindingDTO.class,
    parameters = {
            @StoredProcedureParameter(mode = ParameterMode.IN, name = &quot;INPUT_DATE&quot;, type = String.class),
            @StoredProcedureParameter(mode = ParameterMode.REF_CURSOR, name = &quot;C_OUTPUT&quot;, type = void.class)
    })})
@Entity
public class OpenFindingDTO {
    @Id @GeneratedValue
    @Column(name=Constants.FINDING_ID_PK)
    private String findingID;
    @Column(name=Constants.REVIEW_ID_PK)
    private String reviewID;
    @Column(name=Constants.REVIEW_ID_STR)
    private String reviewIDStr;
    public String getFindingID() {
        return findingID;
    }
    public void setFindingID(String findingID) {
        this.findingID = findingID;
    }
    public String getReviewID() {
        return reviewID;
    }
    public void setReviewID(String reviewID) {
        this.reviewID = reviewID;
    }
    public String getReviewIDStr() {
        return reviewIDStr;
    }
    public void setReviewIDStr(String reviewIDStr) {
        this.reviewIDStr = reviewIDStr;
    }
}
</code></pre>
<p><strong>BBMReportServiceImpl.java</strong></p>
<pre><code>@Service
@Slf4j
public class BBMReportServiceImpl implements BBMReportService {
    @Autowired
    ToolUtility toolUtil;
    @Autowired
    ALMReportDAO almReportDAO;
    @Autowired
    OpenFindingRepository openFindingRepository;
    public Object createFile() {
        Object obj=null;
        try {
            XSSFWorkbook workBook = toolUtil.createFile();
            List&lt;OpenFindingDTO&gt; openFindingList = openFindingRepository.getOpenFindings(Constants.INPUT_DATE);
        } catch (SecurityException | IOException e) {
            e.printStackTrace();
        }
        return obj;
    }
}
</code></pre>
<p>Here <code>List&lt;OpenFindingDTO&gt; openFindingList = openFindingRepository.getOpenFindings(Constants.INPUT_DATE);</code> always <code>null</code></p>
<p>Execution is happening in Oracle and gives result in sql developer unit testing
The execution is successful in oracle, but the List OpenFindingDTO is null even though there is data in the table.</p>
<pre><code>PROCEDURE OPEN_CODE_FINDINGS ( INPUT_DATE IN VARCHAR2, C_OUTPUT OUT SYS_REFCURSOR);
</code></pre>
<p>Can someone help to get <code>OUT SYS_REFCURSOR</code> into <code>List</code> ?</p>
",https://stackoverflow.com/questions/75902392/springboot-convert-sys-ref-cursor-into-java-list-is-not-working,"['spring-boot', 'jpa']",45,True,0,1
Use of ReflectionTestUtils.setField() in Junit testing to set a List of objects,"<p>in my implementation , i have</p>
<p><code>List&lt;recordEntity&gt; entityList = service.mapper(parameter1,parameter2);</code></p>
<p>i need to set the value for this <code>entityList</code> with a static value for my unit testing,
i know that using <code>ReflectionsTestUtils</code> we can set value, even i have used this for another scenaro,</p>
<p><code>ReflectionTestUtils.setField(classObject, &quot;implementations&quot;, Collections.singletonMap(&quot;mapper&quot;, new DTOMapper()));</code></p>
<p>but am not sure how to set a <code>list</code></p>
",https://stackoverflow.com/questions/76361345/use-of-reflectiontestutils-setfield-in-junit-testing-to-set-a-list-of-objects,"['java', 'junit', 'reflection']",28,True,0,1
How can I mock the Alamofire Extension on UIImageView?,"<p>Alamofire has an extension on UIImageView that makes loading an image very easy. But, for unit testing my code, I would like to mock the result of the response, so that I can test success and failure. How can I mock the <code>.af.setImage(withURL:)</code> function?</p>
<p>Example code:</p>
<pre class=""lang-swift prettyprint-override""><code>imageView.af.setImage(withURL: url) { response in
    // do stuff on success or failure
}
</code></pre>
",https://stackoverflow.com/questions/76133600/how-can-i-mock-the-alamofire-extension-on-uiimageview,"['ios', 'swift', 'alamofire', 'alamofireimage']",67,True,-1,2
Golang Issue with Unit Testing for simple error,"<p>I am having trouble trying to test this function with an error inside. The following is my ResponseJson function which does not return an error but sends a response json.</p>
<pre class=""lang-golang prettyprint-override""><code>func ResponseJson(w http.ResponseWriter, Code int, Message string) {
    jsonStatus := struct {
        Code int `json:&quot;code&quot;`
        Message string `json:&quot;message&quot;`
    }{
        Message: Message,
        Code: Code,
    }

    bs, err := json.Marshal(jsonStatus);

    if err != nil {
        log.Println(&quot;Error in Marshal JSON in ResponseJson: &quot;, err)
        str := &quot;Internal Server Error. Please contact the System Administrator.&quot;
        io.WriteString(w, str);
        return 
    } else {
        io.WriteString(w, string(bs));
        return
    }
    
}
</code></pre>
<p>The following is my unit testing code which creates a mock ResponseWriter and it is able to successfully test the writer response json for cases with no errors. Since I am not returning an error type in ResponseJson() function, how do I test it inside the Test_ResponseJson function as shown below?</p>
<pre class=""lang-golang prettyprint-override""><code>func Test_ResponseJson(t *testing.T) {
    responseJsonTests := []struct {
        testName string
        code int
        message string
        expectedJsonResponse string
    } {
        {&quot;Successful Login&quot;, http.StatusOK, &quot;Successfully Logged In!&quot;, `{&quot;code&quot;:200,&quot;message&quot;:&quot;Successfully Logged In!&quot;}`},
        {&quot;Existing username&quot;, http.StatusBadRequest, &quot;Username already exists. Please try again.&quot;, `{&quot;code&quot;:400,&quot;message&quot;:&quot;Username already exists. Please try again.&quot;}`},
    }

    for _, e := range responseJsonTests {
        // Creating a mock ResponseWriter
        w := httptest.NewRecorder()

        ResponseJson(w, e.code, e.message)

        // Read the response body as a string
        body, _ := io.ReadAll(w.Result().Body)
        actual := string(body)

        expected := e.expectedJsonResponse
        if actual != expected {
            t.Errorf(&quot;%s: expected %s but got %s&quot;, e.testName, e.expectedJsonResponse, actual)
        }
    }
}
</code></pre>
<p>Also, I have created a function which generates an actual log output for log.Println() built-in function. I am aware that the log.Println() function is a built-in function and it is highly unlikely to fail. However, I want to achieve 100% coverage in my unit testing. Please help! Thank you :)</p>
<pre class=""lang-golang prettyprint-override""><code>func GenerateLogOutput(message string, errorMessage string) string {
    // Create a new bytes.Buffer to capture the log output
    var buf bytes.Buffer

    // Redirect log output to a different destination set as a buffer
    // By default, log message are written to the standard error stream os.Stderr
    log.SetOutput(&amp;buf)

    // Generate an error
    err := errors.New(errorMessage)

    w := httptest.NewRecorder()

    // Calling the function
    InternalServerError(w, message, err)
    actualOutput := buf.String()

    return actualOutput
}
</code></pre>
",https://stackoverflow.com/questions/75710686/golang-issue-with-unit-testing-for-simple-error,"['unit-testing', 'go']",330,True,1,1
IllegalStateException: &quot;Rejecting additional inbound receiver&quot; using zipWith in Spring WebFlux,"<p>I try to perform two steps with the request body (<code>@RequestBody Flux&lt;ByteBuffer&gt; body</code>) of a WebFlux Controller method using <code>Mono.zipWith()</code>.</p>
<p>Unit testing the code with <code>WebTestClient</code> works as expected.</p>
<p><strong>BUT:</strong> When the WebFlux application runs, I receive the error (&quot;<strong>Rejecting additional inbound receiver</strong>&quot;) below.</p>
<p>The code is similar to this:</p>
<pre class=""lang-java prettyprint-override""><code>    @PostMapping(&quot;/jobs&quot;)
    public Mono&lt;ResponseEntity&lt;Map&lt;String, Object&gt;&gt;&gt; create(@RequestBody Flux&lt;ByteBuffer&gt; body) {

        Mono&lt;String&gt; mono1 = doSomethingWithTheContent(body);

        Mono&lt;Boolean&gt; mono2 = stopOnPatternDetection(body);

        Mono&lt;Tuple2&lt;String, Boolean&gt;&gt; zippedMono = mono1.zipWith(mono2);

        return zippedMono
            .map(Tuple2::getT1)
            .map(this::ok)
            .onErrorResume(PatternDetectedException.class, this::bad);
    }

    Mono&lt;ResponseEntity&lt;Map&lt;String, Object&gt;&gt;&gt; bad(PatternDetectedException patternDetectedException) {
        return Mono.just(
            ResponseEntity
                .badRequest()
                .body(Map.of(&quot;detection&quot;, true))
        );
    }

    ResponseEntity&lt;Map&lt;String, Object&gt;&gt; ok(String key) {
        return ResponseEntity
            .ok()
            .body(
                Map.of(
                    &quot;key&quot;, key,
                    &quot;detection&quot;, false
                )
            );
    }

    Mono&lt;Boolean&gt; stopOnPatternDetection(Flux&lt;ByteBuffer&gt; content) {
        return readContent(content)
            .map(bytes -&gt; {
                if (patternIsDetected(bytes)) {
                    throw new PatternDetectedException(&quot;Pattern detected in &quot; + Arrays.toString(bytes));
                }
                return true;
            });
    }

    Mono&lt;String&gt; doSomethingWithTheContent(Flux&lt;ByteBuffer&gt; content) {
        return readContent(content)
            .map(bytes -&gt; new String(bytes));
    }

    Mono&lt;byte[]&gt; readContent(Flux&lt;ByteBuffer&gt; content) {

        return content
            .reduce(
                new ByteArrayOutputStream(),
                (byteArrayOutputStream, buffer) -&gt; {
                    byteArrayOutputStream.write(buffer.array(), 0, buffer.limit());
                    return byteArrayOutputStream;
                })
            .map(ByteArrayOutputStream::toByteArray);
    }

    private boolean patternIsDetected(byte[] content) {

        return new String(content).contains(&quot;PATTERN-X&quot;);
    }
</code></pre>
<pre><code>java.lang.IllegalStateException: Rejecting additional inbound receiver. State=[terminated=false, cancelled=false, pending=0, error=false]
    at reactor.netty.channel.FluxReceive.startReceiver(FluxReceive.java:189) ~[reactor-netty-core-1.1.4.jar:1.1.4]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
    *__checkpoint ⇢ Handler com.giraone.jobs.receiver.web.rest.JobReceiveResource#create(Flux) [DispatcherHandler]
    *__checkpoint ⇢ org.springframework.web.filter.reactive.ServerHttpObservationFilter [DefaultWebFilterChain]
    *__checkpoint ⇢ HTTP POST &quot;/api/jobs&quot; [ExceptionHandlingWebHandler]
Original Stack Trace:
        at reactor.netty.channel.FluxReceive.startReceiver(FluxReceive.java:189) ~[reactor-netty-core-1.1.4.jar:1.1.4]
        at reactor.netty.channel.FluxReceive.subscribe(FluxReceive.java:148) ~[reactor-netty-core-1.1.4.jar:1.1.4]
        at reactor.core.publisher.InternalFluxOperator.subscribe(InternalFluxOperator.java:62) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.netty.ByteBufFlux.subscribe(ByteBufFlux.java:340) ~[reactor-netty-core-1.1.4.jar:1.1.4]
        at reactor.core.publisher.InternalFluxOperator.subscribe(InternalFluxOperator.java:62) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.netty.ByteBufFlux.subscribe(ByteBufFlux.java:340) ~[reactor-netty-core-1.1.4.jar:1.1.4]
        at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoZip$ZipCoordinator.request(MonoZip.java:216) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxMap$MapConditionalSubscriber.request(FluxMap.java:295) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxMap$MapConditionalSubscriber.request(FluxMap.java:295) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.request(MonoPeekTerminal.java:139) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.request(MonoPeekTerminal.java:139) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.set(Operators.java:2341) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onSubscribe(FluxOnErrorResume.java:74) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onSubscribe(MonoPeekTerminal.java:152) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onSubscribe(MonoPeekTerminal.java:152) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxMap$MapConditionalSubscriber.onSubscribe(FluxMap.java:194) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxMap$MapConditionalSubscriber.onSubscribe(FluxMap.java:194) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoZip.subscribe(MonoZip.java:125) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:165) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:79) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxPeek$PeekSubscriber.onNext(FluxPeek.java:200) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxPeek$PeekSubscriber.onNext(FluxPeek.java:200) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.complete(MonoIgnoreThen.java:292) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.onNext(MonoIgnoreThen.java:187) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:158) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoZip$ZipCoordinator.signal(MonoZip.java:293) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoZip$ZipInner.onNext(MonoZip.java:474) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onNext(MonoPeekTerminal.java:180) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.Operators$ScalarSubscription.request(Operators.java:2545) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.request(MonoPeekTerminal.java:139) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoZip$ZipInner.onSubscribe(MonoZip.java:466) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onSubscribe(MonoPeekTerminal.java:152) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoJust.subscribe(MonoJust.java:55) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoZip$ZipCoordinator.request(MonoZip.java:216) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoFlatMap$FlatMapMain.request(MonoFlatMap.java:194) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.onSubscribe(MonoIgnoreThen.java:134) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoFlatMap$FlatMapMain.onSubscribe(MonoFlatMap.java:117) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoZip.subscribe(MonoZip.java:125) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:240) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.onComplete(MonoIgnoreThen.java:203) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoFlatMap$FlatMapMain.onComplete(MonoFlatMap.java:189) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.Operators.complete(Operators.java:137) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoZip.subscribe(MonoZip.java:121) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.Mono.subscribe(Mono.java:4485) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:263) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:51) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:165) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:79) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onNext(FluxSwitchIfEmpty.java:74) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:82) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxConcatMapNoPrefetch$FluxConcatMapNoPrefetchSubscriber.innerNext(FluxConcatMapNoPrefetch.java:258) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxConcatMap$ConcatMapInner.onNext(FluxConcatMap.java:863) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:129) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onNext(MonoPeekTerminal.java:180) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.Operators$ScalarSubscription.request(Operators.java:2545) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.request(MonoPeekTerminal.java:139) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.request(FluxMapFuseable.java:171) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.request(Operators.java:2305) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxConcatMapNoPrefetch$FluxConcatMapNoPrefetchSubscriber.request(FluxConcatMapNoPrefetch.java:338) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoNext$NextSubscriber.request(MonoNext.java:108) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.set(Operators.java:2341) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onSubscribe(Operators.java:2215) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoNext$NextSubscriber.onSubscribe(MonoNext.java:70) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxConcatMapNoPrefetch$FluxConcatMapNoPrefetchSubscriber.onSubscribe(FluxConcatMapNoPrefetch.java:164) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:201) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:83) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.Mono.subscribe(Mono.java:4485) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:263) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:51) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.core.publisher.MonoDeferContextual.subscribe(MonoDeferContextual.java:55) ~[reactor-core-3.5.3.jar:3.5.3]
        at reactor.netty.http.server.HttpServer$HttpServerHandle.onStateChange(HttpServer.java:1006) ~[reactor-netty-http-1.1.4.jar:1.1.4]
        at reactor.netty.ReactorNetty$CompositeConnectionObserver.onStateChange(ReactorNetty.java:710) ~[reactor-netty-core-1.1.4.jar:1.1.4]
        at reactor.netty.transport.ServerTransport$ChildObserver.onStateChange(ServerTransport.java:477) ~[reactor-netty-core-1.1.4.jar:1.1.4]
        at reactor.netty.http.server.HttpServerOperations.onInboundNext(HttpServerOperations.java:633) ~[reactor-netty-http-1.1.4.jar:1.1.4]
        at reactor.netty.channel.ChannelOperationsHandler.channelRead(ChannelOperationsHandler.java:113) ~[reactor-netty-core-1.1.4.jar:1.1.4]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:444) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at reactor.netty.http.server.HttpTrafficHandler.channelRead(HttpTrafficHandler.java:228) ~[reactor-netty-http-1.1.4.jar:1.1.4]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:442) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:436) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:346) ~[netty-codec-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:333) ~[netty-codec-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:454) ~[netty-codec-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:290) ~[netty-codec-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:251) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:442) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:440) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:788) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:724) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:650) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:562) ~[netty-transport-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) ~[netty-common-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.89.Final.jar:4.1.89.Final]
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.89.Final.jar:4.1.89.Final]
        at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
</code></pre>
",https://stackoverflow.com/questions/75707612/illegalstateexception-rejecting-additional-inbound-receiver-using-zipwith-in,"['java', 'spring-webflux', 'reactor-netty']",394,False,0,0
Unexpected error while attempting a unit test,"<p>I've started writing my first unit testing for an if statement, wanting the error to show up if in an input hasn't been entered. Whenever I run the test its been recognised but it's showing as an error with no error message and I'm not sure why.</p>
<pre><code>//The test
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace practice_1._0
{
    [TestClass]
    public class MyFirstProgramTest
    {
        public const string V = &quot;&quot;;

        public object IgnoreCase { get; private set; }

        [TestMethod]
        public void ExactResults()
        {
            String expectedAnswer = (&quot;good&quot;);
            String expectedAnswer1 = (&quot;bad&quot;);
            String expectedAnswer2 = (&quot;poorly&quot;);
            string actualAnswer = V;

            Assert.AreEqual(IgnoreCase,expectedAnswer, expectedAnswer1, expectedAnswer2,        actualAnswer,&quot;please Enter an Emotion!&quot;);

        }
    }
}
// the if statement
static void Main(string[] args)
{

    Console.WriteLine(&quot;Tell me how you are?&quot;);
    string userInput = Console.ReadLine();

    if (userInput == $&quot;Good&quot;)
    {
        Console.WriteLine(&quot;Great, have a good day!&quot;);
    }
    else if (userInput == &quot;bad&quot;)
    {
        Console.WriteLine(&quot;Hey it could be worse!&quot;);
     }
    else if (userInput == &quot;poorly&quot;)
    {
        Console.WriteLine(&quot;Get better soon!&quot;);
    }
    else if (userInput == &quot;no&quot;)
    {
        Console.WriteLine(&quot;Oh just tell me!&quot;);
    }
    else
    {
        Console.WriteLine(&quot;please! Tell us how you feel!&quot;);
    }
</code></pre>
",https://stackoverflow.com/questions/75137010/unexpected-error-while-attempting-a-unit-test,"['c#', 'unit-testing']",53,False,-1,1
How to mock requests.Session.get using unittest module?,"<p>I want to mock <code>app.requests.Session.get</code> from <code>test_app.py</code> to return a mocked <code>requests.Response</code> object with a 404 <code>status_code</code> to generate an <code>InvalidPlayerIdException</code>.</p>
<p>However, no exception is raised as seen from the below output. Is it because I'm using <code>with</code> clauses, or why doesn't it work?</p>
<p>Reference: <a href=""https://www.pythontutorial.net/python-unit-testing/python-mock-requests/"" rel=""nofollow noreferrer"">https://www.pythontutorial.net/python-unit-testing/python-mock-requests/</a></p>
<p><code>Output</code>:</p>
<pre><code>(supersoccer-showdown) ➜  supersoccer-showdown-copy git:(main) ✗ python -m unittest                                                                                               git:(main|…3 
F
======================================================================
FAIL: test_pokemon_player_requestor_raise_exception (test_app.TestPlayerRequestor.test_pokemon_player_requestor_raise_exception)
----------------------------------------------------------------------
Traceback (most recent call last):
  File &quot;/opt/homebrew/Cellar/python@3.11/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/unittest/mock.py&quot;, line 1369, in patched
    return func(*newargs, **newkeywargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File &quot;/Users/dkNiLyIv/supersoccer-showdown-copy/test_app.py&quot;, line 21, in test_pokemon_player_requestor_raise_exception
    self.assertRaises(InvalidPlayerIdException, requestor.getPlayerById, 1)
AssertionError: InvalidPlayerIdException not raised by getPlayerById
</code></pre>
<p><code>app.py</code>:</p>
<pre><code>from __future__ import annotations
import abc
import requests

class InvalidPlayerIdException(Exception):
  pass

class Player(abc.ABC):
  def __init__(self, id: int, name: str, weight: float, height: float) -&gt; None:
    self.id = id
    self.name = name
    self.weight = weight
    self.height = height

class PokemonPlayer(Player):
  def __init__(self, id: int, name: str, weight: float, height: float) -&gt; None:
    super().__init__(id, name, weight, height)    

  def __repr__(self) -&gt; str:
    return f'Pokemon(id={self.id},name={self.name},weight={self.weight},height={self.height})'

class PlayerRequestor(abc.ABC):
  def __init__(self, url: str) -&gt; None:
    self.url = url

  @abc.abstractmethod
  def getPlayerCount(self) -&gt; int:
    pass

  @abc.abstractmethod
  def getPlayerById(self, id: int) -&gt; Player:
    pass

class PokemonPlayerRequestor(PlayerRequestor):
  def __init__(self, url: str) -&gt; None:
    super().__init__(url)

  def getPlayerCount(self) -&gt; int:
    with requests.Session() as rs:
      rs.mount('https://', requests.adapters.HTTPAdapter(
        max_retries=requests.urllib3.Retry(total=5, connect=5, read=5, backoff_factor=1)))
      with rs.get(f'{self.url}/api/v2/pokemon/', verify=True) as r:
        r.raise_for_status()
        json = r.json()
        return json[&quot;count&quot;]

  def getPlayerById(self, id: int) -&gt; Player:
    with requests.Session() as rs:
      rs.mount('https://', requests.adapters.HTTPAdapter(
        max_retries=requests.urllib3.Retry(total=5, connect=5, read=5, backoff_factor=1)))
      with rs.get(f'{self.url}/api/v2/pokemon/{id}', verify=True) as r:
        if r.status_code == 404:
          raise InvalidPlayerIdException
        r.raise_for_status()
        json = r.json()
        player = PokemonPlayer(id, json[&quot;name&quot;], json[&quot;weight&quot;], json[&quot;height&quot;])
        return player
</code></pre>
<p><code>test_app.py</code>:</p>
<pre><code>import unittest
from unittest.mock import MagicMock, patch
from app import *

class TestPlayerRequestor(unittest.TestCase):
  def setUp(self):
    pass

  def tearDown(self):
    pass

  @patch('app.requests')
  def test_pokemon_player_requestor_raise_exception(self, mock_requests):
    mock_response = MagicMock()
    mock_response.status_code = 404
    mock_session = MagicMock()
    mock_requests.Session = mock_session
    instance = mock_session.return_value
    instance.get.return_value = mock_response
    requestor = PokemonPlayerRequestor('https://pokeapi.co')
    self.assertRaises(InvalidPlayerIdException, requestor.getPlayerById, 1)
</code></pre>
",https://stackoverflow.com/questions/75625319/how-to-mock-requests-session-get-using-unittest-module,"['python', 'unit-testing', 'testing', 'python-requests', 'python-unittest']",114,True,0,1
Mocking scala object gives Cannot mock/spy class PQR,"<p>I have a scala class where i am accessing a method of an object from third party library.</p>
<p>While unit testing the scala class, I want to mock this third party method call. But I am getting below error</p>
<pre><code>Cannot mock/spy class PQR
Mockito cannot mock/spy because :
 - final class
org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class PQR
Mockito cannot mock/spy because :
 - final class
</code></pre>
<p>My code is as follows</p>
<pre><code>class XYZ {
  def test() : Unit = {
    val ret = PQR.test2(&quot;abc&quot;) // third party dependency, PQR is object
    ....
  }
}

class XYZSpec extends AnyFlatSpec with Matchers with MockitoSugar {
  it should &quot;create object&quot; in {
    val pqr = mock[PQR.type]
    when(pqr.test2(any[String])) thenReturn &quot;def&quot;
  }
}
</code></pre>
<p>How do we fix this?</p>
",https://stackoverflow.com/questions/75881593/mocking-scala-object-gives-cannot-mock-spy-class-pqr,"['scala', 'scalamock']",28,False,0,0
How to generate only alphanumeric string using Auto Fixure,"<p>I am using xUnit for unit testing in which I am using Autofixure to generate random strings. But in my API code, I am not allowing special characters as input to method hence test case is failing. Is there way to generate only alphanumeric string in auto fixure.</p>
",https://stackoverflow.com/questions/76113533/how-to-generate-only-alphanumeric-string-using-auto-fixure,"['c#', 'unit-testing', 'asp.net-web-api', '.net-6.0', 'xunit']",30,False,0,1
Jest how to mock environment variable in React Native react-native-dotenv,"<p>I am performing unit testing in React Native and when I run the test case its throwing the following error:</p>
<pre><code>  ● Test suite failed to run
    SyntaxError: /builds/Profile.component.js: Try to import dotenv variable &quot;PROFILE_URL&quot; which is not defined in any .env files.
</code></pre>
<p>.env file is not available on server.</p>
<p>Can anyone please help me out as how to solve it in jest? I am using react-native-dotenv</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/75607630/jest-how-to-mock-environment-variable-in-react-native-react-native-dotenv,"['reactjs', 'react-native', 'jestjs', 'mocha.js', 'enzyme']",165,False,0,0
Wrap inline function with generic type into a non-inline function,"<p>one of the library privides an inline functionA. Since inline function cannot be mocked for unit testing, I'm trying to wrap it into a non-inline function but not sure how to pass the clazz to functionA.
Please help.</p>
<pre><code>inline fun &lt;reified T&gt; functionA(string: String): T {
  // some implementation

}
</code></pre>
<pre><code>fun &lt;T&gt; functionAWrap(string:String, clazz:Class&lt;T&gt;):T {
  return functionA&lt;???&gt;(string)  // not sure how to implement here
}
</code></pre>
<p>In my project, I would expect to call</p>
<pre><code>functionAWrap(testString, AClass::class.java)
</code></pre>
<p>instead of</p>
<pre><code>functionA&lt;AClass&gt;(testString)
</code></pre>
",https://stackoverflow.com/questions/75768386/wrap-inline-function-with-generic-type-into-a-non-inline-function,"['kotlin', 'generics']",15,False,0,0
which url is used for testing code by GitHub when we push via GitHub actions added to repository?,"<p>I am new to CI/CD pipelines so I tried to integrate GitHub actions for unit testing on my existing app which runs on <code>xyz.com</code>. I wanted to make sure if I push code to GitHub which automates unit testing so which <code>url</code> GitHub uses to deploy app.</p>
<p>I am using laravel So in env file created for CI/CD GitHub action pipeline what would be APP_URL.</p>
<p>Question came to my mind as code pushed to GitHub will be tested by automated tests via GitHub actions before pushing it to server. Also is it feasible to connect to MySQL database which is on my server which already have data (don't want to use fresh database each time) because its a bit complex to create sample data to be insert to fresh database each time.</p>
<p>Thanks</p>
<p>Sample code laravel test</p>
<pre><code>public function test_can_check_password_policy()
    {

        $response = $this-&gt;withHeaders([
            'Content-Type' =&gt; 'application/json',
            'Accept' =&gt; 'application/json',
            'app-version' =&gt; 'xyz'
        ])-&gt;get('api/password-settings');

        $response-&gt;assertStatus(200);
        $response-&gt;assertJson([
            'success' =&gt; true
        ]);
        $response-&gt;assertJsonFragment(['password_uppercase' =&gt; '1']);
    }
</code></pre>
",https://stackoverflow.com/questions/75018572/which-url-is-used-for-testing-code-by-github-when-we-push-via-github-actions-add,"['laravel', 'unit-testing', 'github-actions', 'cicd', 'gitlab-ci.yml']",68,True,0,2
Unit Testing in Commerce tools in .net/C# API,"<p>What unit testing framework/library is recommended for Commerce tools in.net/C# API especially for mocking the commerce tool .net API .</p>
<p>I tried mocking the .net API of commerce tools with moq framework but faced issues in that . It does not let mock the objects saying overriding is not allowed .</p>
",https://stackoverflow.com/questions/76351103/unit-testing-in-commerce-tools-in-net-c-api,['commercetools'],19,False,0,0
How to call Mapping solidity where KeyValue is Enum and ValueType is Struct in Ether Js?,"<p>I'm confused about how do I call the solidity mapping for Unit Testing needs on Ether Js and Chai Js. Here's the Solidity code I'm using</p>
<pre><code>pragma solidity 0.8.17;

struct NftSpec {
        uint256 supplyLimit;
        uint256 cost;
        uint256 maxMintAmountPerTx;
        uint256 alreadyMinted;
        bool toggle;
    }
enum MintingFeature {
        publicMinting,
        whitelistMinting,
        giftMinting
    }

mapping(MintingFeature =&gt; NftSpec) public feature;

constructor() ERC721(&quot;Testing&quot;, &quot;TSNG&quot;) {
        feature[MintingFeature.publicMinting] = NftSpec(2000, 0.02 ether, 3, 0, false );
        feature[MintingFeature.whitelistMinting] = NftSpec(1000, 0.015 ether, 1, 0, false );
    }
</code></pre>
<p>I want to make sure that the value matches with value in the constructor. But I have a problem to call <code>feature</code> mapping directly using Ether Js.</p>
",https://stackoverflow.com/questions/75433840/how-to-call-mapping-solidity-where-keyvalue-is-enum-and-valuetype-is-struct-in-e,"['javascript', 'unit-testing', 'solidity', 'chai', 'ethers.js']",107,True,1,1
Why is this Unity unit test not setting up correctly?,"<p>I've just started learning about unit testing in Unity, and unit testing in general and have been stuck on writing my first test for my mobile game. I'm following vairous tutorail sites and youtube videos. I think I'm not setting things up correctly, or more likely, haven't understood something fundamental about unit testing.</p>
<p>I'm trying to test the opening scene Start function, which sets up the default values in the Sart Menu UI components.</p>
<pre><code>public class StartSceneScript : MonoBehaviour
{
    public TMP_InputField playerNameInput1, playerNameInput2;
    public TMP_Text warningText;
    public Slider blueShipCountSlider, redShipCountSlider;
    public TMP_Text blueShipCountText, redShipCountText;

    public void Start()
    {
        playerNameInput1.text = &quot;Blue Team&quot;;
        playerNameInput2.text = &quot;Red Team&quot;;
        warningText.text = &quot;&quot;;
        blueShipCountSlider.value = 1;
        redShipCountSlider.value = 1;
        ShowSliderValue();
    }

    public void ShowSliderValue()
    {
        GlobalVariables.blueShipsCount = Mathf.RoundToInt(blueShipCountSlider.value);
        GlobalVariables.redShipsCount = Mathf.RoundToInt(redShipCountSlider.value);
        blueShipCountText.text = GlobalVariables.blueShipsCount.ToString();
        redShipCountText.text = GlobalVariables.redShipsCount.ToString();
    }
}
</code></pre>
<p>This is the test code. I've tried it both as an Editor test and a Play Mode test, both gave the same error.</p>
<pre><code>using System.Collections;
using NUnit.Framework;
using TMPro;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UI;

public class Playtests_StartScene
{

    [UnityTest]
    public IEnumerator Start_InitializesUIElements()
    {
        // Create a new GameObject with the StartSceneScript component attached
        GameObject startSceneObject = new GameObject();
        var startSceneScript = startSceneObject.AddComponent&lt;StartSceneScript&gt;();

        // Set up the necessary UI components
        startSceneScript.playerNameInput1 = startSceneObject.AddComponent&lt;TMP_InputField&gt;();
        startSceneScript.playerNameInput2 = startSceneObject.AddComponent&lt;TMP_InputField&gt;();
        startSceneScript.warningText = startSceneObject.AddComponent&lt;TMP_Text&gt;();
        startSceneScript.blueShipCountSlider = startSceneObject.AddComponent&lt;Slider&gt;();
        startSceneScript.redShipCountSlider = startSceneObject.AddComponent&lt;Slider&gt;();
        startSceneScript.blueShipCountText = startSceneObject.AddComponent&lt;TMP_Text&gt;();
        startSceneScript.redShipCountText = startSceneObject.AddComponent&lt;TMP_Text&gt;();

        // Call the Start() method of the StartSceneScript component
        startSceneScript.Start();

        // Check that the UI elements have been initialized with the correct values
        Assert.AreEqual(&quot;Blue Team&quot;, startSceneScript.playerNameInput1.text);
        Assert.AreEqual(&quot;Red Team&quot;, startSceneScript.playerNameInput2.text);
        Assert.AreEqual(&quot;&quot;, startSceneScript.warningText.text);
        Assert.AreEqual(GlobalVariables.blueShipsCount, Mathf.RoundToInt(startSceneScript.blueShipCountSlider.value));
        Assert.AreEqual(GlobalVariables.redShipsCount, Mathf.RoundToInt(startSceneScript.redShipCountSlider.value));
        Assert.AreEqual(GlobalVariables.blueShipsCount.ToString(), startSceneScript.blueShipCountText.text);
        Assert.AreEqual(GlobalVariables.redShipsCount.ToString(), startSceneScript.redShipCountText.text);
        yield return null;
    }
}
</code></pre>
<p>The test fails due to the following error:
<code>System.NullReferenceException : Object reference not set to an instance of an object</code></p>
<p>I used debugging while running the test and traced the error to the second line of the Start function:
<code>playerNameInput2.text = &quot;Red Team&quot;;</code></p>
<p>It's occuring because <code>playerNameInput2</code> is null. Also, all other components after the first input field are showing null, too. This stumped me because the first <code>playerNameInput1</code> is showing as set to a new <code>TMP_InputField</code> and it's text is setting to &quot;Blue Team&quot;, so I guess the set up portion of the test is running, but giving up after creating the the first input field, but can't figure out why.</p>
<p>Here is a shot of the inspector showing everything on the script object, and the scene hierarchy too. It's basically a UI starting screen.</p>
<p><a href=""https://www.shonansoft.com/wp-content/uploads/2023/04/Inspector1.jpg"" rel=""nofollow noreferrer"">Inspector Picture Link</a></p>
<p><a href=""https://www.shonansoft.com/wp-content/uploads/2023/04/inspector.jpg"" rel=""nofollow noreferrer"">Scene Hierarchy Link</a></p>
<p>Also, could you tell me if this particular test would be best done in Editor or play mode?</p>
<p>Thank you in advance for any help.</p>
",https://stackoverflow.com/questions/76138914/why-is-this-unity-unit-test-not-setting-up-correctly,"['c#', 'unit-testing', 'unity-game-engine']",44,False,1,0
How to mock service class in hybrid Angular project for unit test,"<p>I have a hybrid Angular project. But I have problems with unit testing.</p>
<p>I have tried this <a href=""https://stackoverflow.com/questions/58331328/how-to-mock-service-function-in-angular-component-for-unit-test"">solution</a> but it seems doesn't work for my project.</p>
<p>there is an error from <code>ng test</code> command.</p>
<pre><code>Chrome 111.0.0.0 (Windows 10) GoComponent should create FAILED
        NullInjectorError: R3InjectorError(DynamicTestModule)[ABCadminService -&gt; ApiconfigurationService -&gt; ng1ServiceProviderUpgrade -&gt; ng1ServiceProviderUpgrade]:
          NullInjectorError: No provider for ng1ServiceProviderUpgrade!
        error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'ABCadminService', 'ApiconfigurationService', 'ng1ServiceProviderUpgrade', 'ng1ServiceProviderUpgrade' ] })
        NullInjectorError: R3InjectorError(DynamicTestModule)[ABCadminService -&gt; ApiconfigurationService -&gt; ng1ServiceProviderUpgrade -&gt; ng1ServiceProviderUpgrade]:
          NullInjectorError: No provider for ng1ServiceProviderUpgrade!
            at NullInjector.get (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11100:27)
</code></pre>
<p><strong>component.spec.ts</strong></p>
<pre><code>describe('GoComponent', () =&gt; {
  let component: GoComponent;
  let fixture: ComponentFixture&lt;GoComponent&gt;;
  let mockABCadminService;

  beforeEach(async () =&gt; {
    mockABCadminService = jasmine.createSpyObj(['getABC']);
    mockABCadminService.getABC.and.returnValue('abc');
    TestBed.configureTestingModule({
      imports: [HttpClientModule],
      declarations: [GoComponent],
      providers: [
        { provide: ABCadminService, useValue: mockABCadminService }
      ]
    })
      .compileComponents();
  });

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(GoComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>
<p><strong>service.ts</strong></p>
<pre><code>@Injectable({
    providedIn: 'root'
})

export class ABCadminService {
    private apiURL: string;
    private baseUrl: string = '/abcadmin';
    private url: string;
    constructor(
        private http: HttpClient,
        private apiConfig: ApiconfigurationService
    ) {
        this.apiURL = this.apiConfig.getApiUrl();
        this.url = this.apiURL + this.baseUrl;
    }

    getABC(): Observable&lt;abcTree&gt; {
        return this.http.get&lt;abcTree&gt;(this.url);
    }
}

</code></pre>
<p><strong>component.ts</strong></p>
<pre><code>export class GoComponent implements OnInit {

  contentLoading: boolean = false;
  content: string = '';

  constructor(private abcadminService: ABCadminService) { }

  ngOnInit(): void {
      this.contentLoading = true;
      this.abcadminService.getABC().subscribe(data =&gt; {
          this.content = data;
          this.contentLoading = false;
    })
  }
}
</code></pre>
<p>I think if I can mock <code>ABCadminService</code> I don't have to <code>ng1ServiceProviderUpgrade</code> anymore.<br />
Or should I mock every layer of <code>[ABCadminService -&gt; ApiconfigurationService -&gt; ng1ServiceProviderUpgrade -&gt; ng1ServiceProviderUpgrade]</code></p>
",https://stackoverflow.com/questions/75718393/how-to-mock-service-class-in-hybrid-angular-project-for-unit-test,"['angular', 'jasmine', 'karma-jasmine']",60,True,0,1
Golang GORM DB mock,"<p>I have to mock test a service.to create new service i need to pass gorm.DB{} but every time i pass it and run the test i get nil pointer error(panic).
please help on how to mock gorm.DB{} instance correctly for unit testing.</p>
<pre><code>func NewService(db *gorm.DB) Service {
    return &amp;service{
        repo:  newReactionRepo(db),
    }
}
</code></pre>
<p>making the mock call in the test like this :-</p>
<pre><code>mockDB = &amp;gorm.DB{}

package.NewService(mockDB)
</code></pre>
<p>getting this error</p>
<pre><code>testing.tRunner.func1.2({0x1648e40, 0x21cdd60})
    C:/Program Files/Go/src/testing/testing.go:1396 +0x24e
testing.tRunner.func1()
    C:/Program Files/Go/src/testing/testing.go:1399 +0x39f
panic({0x1648e40, 0x21cdd60})
    C:/Program Files/Go/src/runtime/panic.go:884 +0x212
gorm.io/gorm.(*DB).Session(0x21ef260, 0xc000861a50)
    C:/Users/acb/sdk/go1.17/pkg/mod/gorm.io/gorm@v1.24.2/gorm.go:215 +0x3b
gorm.io/gorm.(*DB).WithContext(...)
</code></pre>
",https://stackoverflow.com/questions/75250109/golang-gorm-db-mock,"['unit-testing', 'go', 'testing', 'go-gorm']",953,False,1,3
Golang dependency injection for mock database in unit testing,"<p>I am creating a mock database with Golang interfaces to test my handler function. However, I don't seem to be performing the dependency injection correctly in my unit testing environment. I have created a <code>setup_test.go</code> file to set up my mock database environment. In the code snippets below, I will go over the flow of how my dependency injection works.</p>
<ol>
<li><code>main.go</code></li>
</ol>
<pre class=""lang-golang prettyprint-override""><code>package main

type application struct {
    DB repository.DatabaseRepo
}

func main() {
    app := application{}

    conn, err := app.connectToDB()
    if err != nil {
        log.Fatal(&quot;Failed to connect to PostgreSQL:&quot;, err)
    }

    defer func() {
        conn.Close(context.Background())
    }()

    app.DB = &amp;dbrepo.PostgresDBRepo{DB: conn}

    // Passing app.DB to routes function for DI
    mux := routes.Routes(app.DB)
</code></pre>
<pre class=""lang-golang prettyprint-override""><code>package repository

type DatabaseRepo interface {
    Connection() *pgx.Conn
    GetCountByUsername(ctx context.Context, username string) (int, error)
}
</code></pre>
<ol start=""2"">
<li><code>routes.go</code></li>
</ol>
<pre class=""lang-golang prettyprint-override""><code>package routes

func Routes(app repository.DatabaseRepo) http.Handler {
    mux := chi.NewRouter()

    signUpH := user.New(app)
    mux.Post(&quot;/signup&quot;, utils.MakeHTTPHandler(signUpH.SignUp))
}
</code></pre>
<ol start=""3"">
<li><code>SignUp.go</code> <br>
The code fails at this line which is calling the database. I have set up my mock database in point 4 in <code>setup_test.go</code>. This is the error message I am getting &quot;panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation ...]&quot;.</li>
</ol>
<pre class=""lang-golang prettyprint-override""><code>package user

type application struct {
    DB repository.DatabaseRepo
}

// Dependency Injection of Repository (Database)
func New(app repository.DatabaseRepo) *application {
    return &amp;application{DB: app}
}

func (app application) SignUp(w http.ResponseWriter, req *http.Request) error {
    // some other logic

    // When I run `go run .`, this prints out to be *dbrepo.PostgresDBRepo
    // When I run `go test -v ./...`, this prints out to be &lt;nil&gt; 
    // but the expected type should be *dbrepo.TestDBRepo
    fmt.Printf(&quot;Type of app.DB: %T\n&quot;, app.DB)

    // fails on this line in unit testing
    userCount, err := app.DB.GetCountByUsername(ctx, Username)

    // some other logic
}
</code></pre>
<ol start=""4"">
<li><code>setup_test.go</code></li>
</ol>
<pre class=""lang-golang prettyprint-override""><code>package main

var app application

func TestMain(m *testing.M) {

    app.DB = &amp;dbrepo.TestDBRepo{}

    fmt.Printf(&quot;Type of app.DB: %T\n&quot;, app.DB) // output type is *dbrepo.TestDBRepo

    os.Exit(m.Run())
}
</code></pre>
<p>I have seen many unit testing for similar mock database using this approach but they usually do it within the same package main which will not have this issue if you have nested folders and packages like mine.</p>
<p>What can I try next?</p>
",https://stackoverflow.com/questions/75857122/golang-dependency-injection-for-mock-database-in-unit-testing,"['unit-testing', 'go']",148,True,1,1
Guidance on use of DUnitX in Delphi,"<p>For too many years I have been writing tightly-coupled spaghetti Delphi code.
I have decided to stop doing this and write only clean testable code from now on.
So, I have been studying clean code, dependency injection, refactoring, decoupling, unit testing, etc, etc (Nick Hodges, Ray Konopka, Uncle Bob, Alister Christie to name a few).</p>
<p>I'm stuck on how to go about unit testing one of my classes (using DUnitX). All the examples I have researched so far show the CUT's dependency interface being mocked and then being injected in the CUT's constructor, like this (from Nick Hodges):</p>
<pre><code>procedure TestTCCValidator.TestCardChargeReturnsProperAmountWhenCardIsGood;
var
  CCManager: TCreditCardManager;
  CCValidator: TMock&lt;ICreditCardValidator&gt;;
  GoodCard: String;
  Input: Double;
  Expected, Actual: Double;
begin
  //Arrange
  GoodCard := '123456';
  Input := 49.95;
  Expected := Input;
  CCValidator := TMock&lt;ICreditCardValidator&gt;.Create;
  CCValidator.Setup.WillReturn(True).When.IsCreditCardValid(GoodCard);
  CCManager := TCreditCardManager.Create(CCValidator);
  try
  //Act
  Actual := CCManager.ProcessCreditCard(GoodCard, Input)
  finally
  CCManager.Free;
  end;
  // Assert
Assert.AreEqual(Expected, Actual);
end;
</code></pre>
<p>That's fine and I understand all of it.</p>
<p>Unfortunately, my class does not have a constructor. It's only dependency (which is a record, not an interface) is passed in a class procedure, as follows:</p>
<p>This unit contains the interface implemented by my class...</p>
<pre><code>unit Unit15;

interface

type
  TMyRecord = record
    Flag: boolean
  end;

  IMyInterface = interface(IInvokable)
    ['{17783F54-0F63-413B-8198-88705CBA318F}']
    procedure DoSomething;
  end;


implementation

end.
</code></pre>
<p>This unit contains my class (that implements the above interface)...</p>
<pre><code>unit Unit14;

interface

uses
  Unit15;

type
  TMyClass = class(TInterfacedObject, IMyInterface)
    FRec: TMyRecord;
    procedure DoSomething;
    procedure DoThis;
    procedure DoThat;
    class procedure Execute(ARec: TMyRecord);
  end;

implementation

{ MyClass }

procedure TMyClass.DoSomething;
begin
  case FRec.Flag of
    true: DoThis;
    false: DoThat;
  end;
end;

procedure TMyClass.DoThat;
begin
  writeln('did that');
end;

procedure TMyClass.DoThis;
begin
  writeln('did this');
end;

class procedure TMyClass.Execute(ARec: TMyRecord);
begin
  var mc: IMyInterface := TMyClass.Create;
  TMyClass(mc).FRec := ARec;
  mc.DoSomething;
end;

end.
</code></pre>
<p>And here is how you might deploy my class...</p>
<pre><code>program Project12;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  Unit14 in 'Unit14.pas',
  Unit15 in 'Unit15.pas';

var
  Rec: TMyRecord;

begin
  try
    Rec.Flag := true;
    TMyClass.Execute(Rec);
    ReadLn;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
</code></pre>
<p>I created a DUnitX project and started to proceed like Nick's credit card manager example. But this is where I think I have failed to fully grasp the techniques used in unit testing. My Test project has this unit...</p>
<pre><code>unit Unit16;

interface

uses
  Unit14,
  Unit15,
  DUnitX.TestFramework;

type
  [TestFixture]
  TMyTestObject = class
  private
    FRec: TMyRecord;
    CUT: TMyClass;     // do I need this?
  public
    [Setup]
    procedure Setup;
    [TearDown]
    procedure TearDown;
    [Test]
//    [TestCase('Text Execute with true flag', true)]   // causes compiler error
//    [TestCase('Text Execute with false flag', false)]  // causes compiler error
    procedure TestExecute(const AFlag: boolean);
  end;

  // how do I mock IMyInterface (which is created in TMyClass.Execute)?

implementation

procedure TMyTestObject.Setup;
begin
end;

procedure TMyTestObject.TearDown;
begin
end;

procedure TMyTestObject.TestExecute(const AFlag: boolean);
begin
  FRec.Flag := AFlag;
  TMyClass.Execute(FRec);
end;

initialization
  TDUnitX.RegisterTestFixture(TMyTestObject);

end.
</code></pre>
<p>How should I test that DoSomething behaves correctly when called?</p>
<p>Is it possible to test MyClass as I have written it or must I restructure it?</p>
<p>Can someone point me in the right direction?</p>
",https://stackoverflow.com/questions/75574660/guidance-on-use-of-dunitx-in-delphi,"['unit-testing', 'delphi', 'mocking']",173,True,0,1
intellij test fails: Please refer to ..target\surefire-reports for the individual test results,"<p>I want to test my java intellij project using maven and get error which is not related to
my code. To be more specific Intellij editor complains so:</p>
<blockquote>
<p>&quot;Please refer to C:\Users\USER\IdeaProjects\testing\target\surefire-reports for the individual test results.&quot;</p>
</blockquote>
<p>I added needed dependencies for unit testing im pom.xm file:</p>
<pre><code>&lt;dependencies&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
        &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&gt;
        &lt;version&gt;${junit.jupiter.version}&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
        &lt;artifactId&gt;junit-jupiter-engine&lt;/artifactId&gt;
        &lt;version&gt;${junit.jupiter.version}&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;

&lt;build&gt;
    &lt;plugins&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
            &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
            &lt;version&gt;3.1.0&lt;/version&gt;
        &lt;/plugin&gt;
    &lt;/plugins&gt;
&lt;/build&gt;
</code></pre>
",https://stackoverflow.com/questions/76346422/intellij-test-fails-please-refer-to-target-surefire-reports-for-the-individua,"['intellij-idea', 'junit', 'junit5']",130,True,1,1
java.lang.IllegalStateException: Could not load CacheAwareContextLoaderDelegate unit test spring,"<p><strong>Unit Testing with Spring framework - Java</strong></p>
<p>I got the below error when I run the spring unit test with a java context</p>
<pre><code>java.lang.IllegalStateException: Could not load CacheAwareContextLoaderDelegate [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
</code></pre>
<p>My <strong>pom.xml</strong> have these dependencies but still faced this issue when i run my test case</p>
<pre><code>        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
            &lt;version&gt;6.0.3&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;junit&lt;/groupId&gt;
            &lt;artifactId&gt;junit&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.mockito&lt;/groupId&gt;
            &lt;artifactId&gt;mockito-core&lt;/artifactId&gt;
            &lt;version&gt;4.5.1&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
</code></pre>
<p>My current version of spring and java</p>
<pre><code>    &lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;2.7.7&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;
    &lt;groupId&gt;com.example&lt;/groupId&gt;
    &lt;artifactId&gt;demo&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
    &lt;name&gt;demo&lt;/name&gt;
    &lt;description&gt;Demo project for Spring Boot&lt;/description&gt;
    &lt;properties&gt;
        &lt;java.version&gt;11&lt;/java.version&gt;
    &lt;/properties&gt;
</code></pre>
<p>I just change my <strong>pom.xml</strong>, remove the version then run, it worked perfectly</p>
<pre><code>      &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt; 
</code></pre>
",https://stackoverflow.com/questions/75062502/java-lang-illegalstateexception-could-not-load-cacheawarecontextloaderdelegate,"['java', 'spring', 'spring-boot', 'junit', 'mockito']",899,True,2,2
Create an issue on GitHub with log contents,"<p>I am trying to make my yaml file create a GitHub issue when the unit testing fails. It does create an issue but I cannot append the log file into the issue body to clarify why it failed.</p>
<pre><code>      # Run the Python API testing script and check the exit status 

       - name: Run the Python API testing script 

  

         # Set the ID of the step for referencing later 

         id: status 

         run: | 

  

           # Change working directory to the location of the test script 

           cd .github/workflows 

  

           # Run the test script and save the output to a log file 

           python test_session.py &gt; terminal.log 2&gt;&amp;1  

  

       # Create a GitHub issue if the build fails. 

       - name: Create GitHub issue on test failure 

         env: 

           GITHUB_TOKEN: ${{ github.token }} 

         run: | 

  

           cd .github/workflows 

  

           # Check if the previous step failed 

           if [ &quot;${{ steps.status.outcome }}&quot; == &quot;failure&quot; ]; then 

             curl -X POST \ 

               -H &quot;Accept: application/vnd.github+json&quot; \ 

               -H &quot;Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}&quot; \ 

               -H &quot;X-GitHub-Api-Version: 2022-11-28&quot; \ 

              https://api.github.com/repos/${{ github.repository }}/issues \
              
-d '{&quot;title&quot;:&quot;API Test Failure&quot;,&quot;body&quot;:&quot;'$(cat terminal.log)'&quot;}'

           fi
</code></pre>
<p>Is there a way to create an issue with the log from the previous steps and how?</p>
",https://stackoverflow.com/questions/75561747/create-an-issue-on-github-with-log-contents,"['github', 'devops', 'cicd']",12,False,0,0
How to unit test a function with a large input data that is essential for the expected output?,"<p>I have a dilemma in unit testing.</p>
<p>In the following code, the <code>model.bin</code> file is very large and takes 10 minutes to load on my system, which hinders the testing efficiency. However, if I use a smaller model, the function does not return the correct output. How can I achieve both fast and accurate testing?</p>
<pre class=""lang-py prettyprint-override""><code>&gt;&gt;&gt; wordEmbedding = WordEmbedding()
&gt;&gt;&gt; wordEmbedding.load_model('model.bin')
&gt;&gt;&gt; wordEmbedding.doesnt_match('sky', 'book','notebook')
sky # This output is expected because the input model is large. Using a smaller model would produce incorrect output.
</code></pre>
",https://stackoverflow.com/questions/76338767/how-to-unit-test-a-function-with-a-large-input-data-that-is-essential-for-the-ex,"['python', 'unit-testing', 'docstring']",23,False,0,0
"use mockito to execute, java.lang.NullPointerException at net.bytebuddy.dynamic.scaffold.inline.RedefinitionDynamicTypeBuilder.jrGetTypeDependencies","<p>Here is my framework dependency version
mockito-core 4.8.0
mockito-inline 4.8.0
mockito-junit-jupiter 4.8.0
byte-buddy  1.12.0
junit 4.12
spring-boot-starter 1.5.22</p>
<p>When I run the springboot container for unit testing, debug runs wrong。I can't see the specific location of this dependency error
！</p>
<p>Here's what I'm running</p>
<pre><code>org.mockito.exceptions.base.MockitoException: 
Failed to release mocks

This should not happen unless you are using a third-party mock maker

    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.initMocks(MockitoTestExecutionListener.java:67)
    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.prepareTestInstance(MockitoTestExecutionListener.java:47)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at com.taobao.pandora.boot.test.junit4.PandoraBootRunner.run(PandoraBootRunner.java:111)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.goldenBellCocoon.starter.TestStarter.start(TestStarter.java:41)
    at com.goldenBellCocoon.starter.TestStarter.lambda$main$0(TestStarter.java:55)
    at com.goldenBellCocoon.starter.TestStarter.main(TestStarter.java:69)
Caused by: org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class com..sec.core.manager.TaskManager.

If you're not sure why you're getting this error, please open an issue on GitHub.


Java               : 1.8
JVM vendor name    : Oracle Corporation
JVM vendor version : 25.291-b10
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 1.8.0_291-b10
JVM info           : mixed mode
OS name            : Mac OS X
OS version         : 10.16


You are seeing this disclaimer because Mockito is configured to create inlined mocks.
You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.

Underlying exception : org.mockito.exceptions.base.MockitoException: Could not modify all classes [interface org.springframework.beans.factory.Aware, interface org.springframework.context.ApplicationContextAware, class com..sec.core.manager.TaskManager, class java.lang.Object]
    ... 33 more
Caused by: org.mockito.exceptions.base.MockitoException: Could not modify all classes [interface org.springframework.beans.factory.Aware, interface org.springframework.context.ApplicationContextAware, class com..sec.core.manager.TaskManager, class java.lang.Object]
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:153)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:366)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:175)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:377)
    ... 33 more
Caused by: java.lang.IllegalStateException: 
Byte Buddy could not instrument all classes within the mock's type hierarchy

This problem should never occur for javac-compiled classes. This problem has been observed for classes that are:
 - Compiled by older versions of scalac
 - Classes that are part of the Android distribution
    at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.triggerRetransformation(InlineBytecodeGenerator.java:284)
    at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.mockClass(InlineBytecodeGenerator.java:217)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.lambda$mockClass$0(TypeCachingBytecodeGenerator.java:47)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:153)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:366)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:175)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:377)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:40)
    at org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMaker.createMockType(InlineDelegateByteBuddyMockMaker.java:395)
    at org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMaker.doCreateMock(InlineDelegateByteBuddyMockMaker.java:355)
    at org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMaker.createMock(InlineDelegateByteBuddyMockMaker.java:334)
    at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.createMock(InlineByteBuddyMockMaker.java:56)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:99)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:88)
    at org.mockito.Mockito.mock(Mockito.java:1998)
    at org.mockito.internal.configuration.MockAnnotationProcessor.processAnnotationForMock(MockAnnotationProcessor.java:74)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:28)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:25)
    at org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:44)
    at org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:72)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:73)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:47)
    at org.mockito.MockitoAnnotations.openMocks(MockitoAnnotations.java:81)
    at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:99)
    ... 33 more
Caused by: java.lang.NullPointerException
    at net.bytebuddy.dynamic.scaffold.inline.RedefinitionDynamicTypeBuilder.jrGetTypeDependencies(RedefinitionDynamicTypeBuilder.java:42008)
    at net.bytebuddy.dynamic.scaffold.inline.RedefinitionDynamicTypeBuilder.make(RedefinitionDynamicTypeBuilder.java:224)
    at net.bytebuddy.dynamic.scaffold.inline.AbstractInliningDynamicTypeBuilder.make(AbstractInliningDynamicTypeBuilder.java:123)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3659)
    at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.transform(InlineBytecodeGenerator.java:398)
    at sun.instrument.TransformerManager.transform(TransformerManager.java:188)
    at sun.instrument.InstrumentationImpl._jrDoTransform(InstrumentationImpl.java:428)
    at sun.instrument.InstrumentationImpl._jrTransform(InstrumentationImpl.java:42001)
    at com.zeroturnaround.jrebelbase.reorder.b.transform(SourceFile:177)
    at com.zeroturnaround.jrebelbase.reorder.b.transform(SourceFile:150)
    at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:43001)
    at sun.instrument.InstrumentationImpl.retransformClasses0(Native Method)
    at sun.instrument.InstrumentationImpl.retransformClasses(InstrumentationImpl.java:144)
    at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.triggerRetransformation(InlineBytecodeGenerator.java:280)
    ... 56 more
</code></pre>
<p>help with my problem</p>
",https://stackoverflow.com/questions/75751853/use-mockito-to-execute-java-lang-nullpointerexception-at-net-bytebuddy-dynamic,"['java', 'spring', 'mocking', 'mockito']",88,False,0,0
Spec file not able to create component successfully for Unit testing using Jasmine Karma,"<p><strong>Default spec file   in Angular framework is not able to create  component for  Unit testing using Jasmine Karma because of following error</strong></p>
<pre><code>Chrome 111.0.0.0 (Mac OS 10.15.7) VaccineCheckerComponent should be created FAILED
        TypeError: Cannot read properties of undefined (reading 'set')
            at LocalStorageService.store (node_modules/ngx-webstorage/fesm2020/ngx-webstorage.mjs:78:23)
            at new StoreApiResponseHelperService (src/app/shared/services/store-api-response-helper.service.ts:37:22)
            at Object.factory (ng:///StoreApiResponseHelperService/ɵfac.js:4:10)
            at R3Injector.hydrate (node_modules/@angular/core/fesm2020/core.mjs:9252:35)
            at R3Injector.get (node_modules/@angular/core/fesm2020/core.mjs:9146:33)
            at injectInjectorOnly (node_modules/@angular/core/fesm2020/core.mjs:4778:33)
            at ɵɵinject (node_modules/@angular/core/fesm2020/core.mjs:4782:12)
            at Object.factory (ng:///BccContentService/ɵfac.js:5:40)
            at R3Injector.hydrate (node_modules/@angular/core/fesm2020/core.mjs:9252:35)
            at R3Injector.get (node_modules/@angular/core/fesm2020/core.mjs:9146:33)
</code></pre>
<p>Tried <code>npm install</code> and looked for the functions which is failing
Ex: store function in <code>LocalStorageService</code>
It is not even used in the component so not able to figure out why its pointing to that.</p>
",https://stackoverflow.com/questions/75796170/spec-file-not-able-to-create-component-successfully-for-unit-testing-using-jasmi,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-runner']",36,False,0,0
How to test http.post in Angular?,"<p>one more question about unit testing in Angular. Sorry, I am new to this so sorry if the solution is trivial. I have this simple class:</p>
<pre><code>export class HttpService {
  constructor(private http: HttpClient) {}

  postV2(url: string, request: IHttpRequestV2) {
    return this.http.post&lt;IHttpResponse&gt;(url, request);
  }

  postV3(url: string, request: IHttpRequestV3) {
    return this.http.post&lt;IHttpResponse&gt;(url, request);
  }
}
</code></pre>
<p>Can somebody point me the right direction how is possible to cover this functions with unit tests? Thanks</p>
<p>Solution: Thanks to @nate-kumar this is the solution that works:</p>
<pre><code>  it('should call postV2 with right parameters', () =&gt; {
    const mockRequest: IHttpRequestV2 = {
      data: {
        cred: {
          n: &quot;n&quot;,
          p: &quot;p&quot;
        }
      }
    }

    service.postV2(&quot;http://some.url&quot;, mockRequest).subscribe();
    
    const testRequest = httpMock.expectOne(
      (request) =&gt; request.url === &quot;http://some.url&quot;
    );
    expect(testRequest.request.body[&quot;data&quot;][&quot;cred&quot;][&quot;n&quot;]).toEqual(&quot;n&quot;);
    expect(testRequest.request.body[&quot;data&quot;][&quot;cred&quot;][&quot;p&quot;]).toEqual(&quot;p&quot;);
  });
</code></pre>
",https://stackoverflow.com/questions/75174040/how-to-test-http-post-in-angular,"['angular', 'unit-testing', 'http', 'jasmine']",47,False,0,0
Type &#39;string&#39; is not assignable to type &#39;Date nest js unit testing,"<p>I created a sample project with CRUD using NestJs. I create a User with a randomly generated <code>Id</code>, <code>name</code>, <code>birthdate</code> and <code>email</code>. I need to do unit testing for this create CRUD operation. But I do not know how to test the birthDate. It gives me an error.</p>
<p><a href=""https://i.stack.imgur.com/JPHWr.png"" rel=""nofollow noreferrer"">This is what I got when I tried to pass the date </a></p>
<p><strong>User Entity:</strong></p>
<pre class=""lang-js prettyprint-override""><code>import {
  Column,
  CreateDateColumn,
  Entity,
  PrimaryGeneratedColumn,
} from 'typeorm';

@Entity('users')
export class User {
  //auto increment
  @PrimaryGeneratedColumn('increment')
  id: number;

  @Column({ nullable: true, default: null })
  name: string;

  @CreateDateColumn({ nullable: true })
  birthDate: Date;

  @Column({ type: 'varchar' })
  email: string;
}
</code></pre>
",https://stackoverflow.com/questions/74994452/type-string-is-not-assignable-to-type-date-nest-js-unit-testing,"['unit-testing', 'date', 'nestjs', 'crud']",310,True,0,1
Getting undefined on service called from html,"<p>I'm currently working on an Angular project and I am creating unit testing for a component using Karma + Jasmine, so I have HTML that has a <code>ngIf</code> calling the API Service as:</p>
<p><strong>HTML</strong></p>
<pre><code>&lt;div class=&quot;row&quot; *ngIf=&quot;apiService.utilsService.userBelongsTo('operations')&quot;&gt;&lt;/div&quot;&gt;
</code></pre>
<p><strong>TS</strong></p>
<pre><code>export class CashFlowSalariesComponent implements OnInit, OnChanges {
constructor(
public apiService: ApiService,
) {}
</code></pre>
<p><strong>SPECT.TS</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>describe('CashFlowSalariesComponent', () =&gt; {
      let fixture: ComponentFixture &lt; CashFlowSalariesComponent &gt; ;
      let mockCashFlowService;
      let data;

      beforeEach(async(() =&gt; {
        data = [{
          id: 1006,
          role: ""Developer"",
          ...
        }]

        mockCashFlowService = jasmine.createSpyObj(['createTableData'])

        TestBed.configureTestingModule({
          schemas: [CUSTOM_ELEMENTS_SCHEMA],
          imports: [
            RouterTestingModule,
            FormsModule,
            ReactiveFormsModule,
            BrowserModule,
            HttpClientTestingModule,
            ToastrModule.forRoot({
              positionClass: 'toast-bottom-right'
            })
          ],
          declarations: [
            CashFlowSalariesComponent,
          ],
          providers: [{
              provide: ApiService,
              useValue: mockCashFlowService
            }, UserService, ProfileService, VettingStatusService, ApplicationRoleService,
            SeniorityLevelService, PlacementStatusService, EducationLevelService, UtilsService, ShirtSizeService,
            CountryService, CityService, PostalCodeService, StateService, ClientSectorService, JobService, ProfileActivityService, ProfileSalaryActivityService, ClientService, RequestTimeOffService, TimeOffTypeService, PulsecheckDetailService, PulsecheckMasterService,
            PulsecheckQuestionService, ExpenseService, DepartmentService, ExchangeRateService, SkillCategoriesService, ProfileRoleService,
            ToastrService
          ]

        })

        fixture = TestBed.createComponent(CashFlowSalariesComponent);
      }));

      it('should create', () =&gt; {
        expect(CashFlowSalariesComponent).toBeTruthy();
      });


      it('should set salaries data correctly', () =&gt; {

        mockCashFlowService.userBelongsTo = 'operations'
        mockCashFlowService.createTableData.and.returnValue( of (data))
        debugger;
        fixture.detectChanges();

        expect(fixture.componentInstance.dataHeaders.length).toBe(10);
      })</code></pre>
</div>
</div>
</p>
<p>As you see, I tried to set userBelongsTo as: <code>mockCashFlowService.userBelongsTo = 'operations'</code> but I get an error:</p>
<blockquote>
<p>TypeError: Cannot set properties of undefined (setting
'userBelongsTo')</p>
</blockquote>
<p><strong>ApiService</strong></p>
<pre><code>@Injectable()
export class ApiService {
 public utilsService: UtilsService;

constructor(private injector: Injector) {
this.utilsService = injector.get(UtilsService);
}
}
</code></pre>
<p><strong>Utils.Service:</strong></p>
<pre><code>userBelongsTo(groupName: string) {
    return this.groups.split(',').reduce((c, g) =&gt; c || g.toUpperCase() == groupName.toUpperCase(), false);
  }
</code></pre>
",https://stackoverflow.com/questions/75176212/getting-undefined-on-service-called-from-html,"['javascript', 'angular', 'typescript', 'jasmine', 'karma-jasmine']",41,False,0,1
Can Dart or Flutter unit tests be automatically repeated?,"<p>When unit testing with Dart or Flutter
If there are 100 unit tests, if you run the <code>flutter test</code> command, 100 test codes will be tested once.
But I want to repeat this N times.
Is there a command or way to automatically start the test again after one full test and report if the test is broken?</p>
",https://stackoverflow.com/questions/75380753/can-dart-or-flutter-unit-tests-be-automatically-repeated,"['flutter', 'dart', 'unit-testing', 'testing']",118,False,0,0
Algorithm or a tool to compare two spectrogram outputs for unit testing purposes,"<p>I am looking for a good algorithm or a tool to compare two spectrogram outputs for unit testing. I can visually confirm the outputs are similar but I would like to automate this process. The basic stats of the outputs, such as min/max/avg/median are kind of the same but this would not catch true differences.</p>
",https://stackoverflow.com/questions/75393470/algorithm-or-a-tool-to-compare-two-spectrogram-outputs-for-unit-testing-purposes,"['unit-testing', 'compare', 'spectrogram']",5,False,0,0
Does returning values from an event handler makes the Subgraph to crash?,"<p>I tried returning the entity objects from the event handlers on the AssemblyScript Subgraph code to simplify unit testing. For example, this works fine:</p>
<pre class=""lang-js prettyprint-override""><code>// Original code
export function handleEventCreation(
       event: EventCreation
): void {
...
}
</code></pre>
<p>but this fails:</p>
<pre class=""lang-js prettyprint-override""><code>// Failing code in Subgraph (it compiles well)
export function handleEventCreation(
     event: EventCreation,
): CreationEntity | null {
...
}
</code></pre>
<p>Both examples compile well.</p>
<p>Is there any explanation for that?
In the Subgraph API site, I see that it failed indexing events only, but no further details about it.</p>
",https://stackoverflow.com/questions/75852971/does-returning-values-from-an-event-handler-makes-the-subgraph-to-crash,"['subgraph', 'assemblyscript', 'thegraph']",23,False,0,0
how to set value for android.util.Pair variable in android studio java unit testing,"<p>I am working on unit testing and I have to test a method which is return a &quot;MutableLiveData&lt;Pair&lt;String, Boolean&gt;&gt;&quot; .So make a Pair variable and set value . But when I debug the test case, I notice that Pair varible is null</p>
<pre><code>Pair&lt;String,Boolean&gt; pair = new Pair&lt;&gt;(&quot;dsn&quot;,true);
</code></pre>
<p>please don't suggest android.support.v4.util.Pair instead of android.util.Pair,it  doesn't work for me.</p>
",https://stackoverflow.com/questions/75820731/how-to-set-value-for-android-util-pair-variable-in-android-studio-java-unit-test,"['java', 'android-studio', 'junit4']",47,False,0,0
Sinon library how to mock this async validateMyRequest function to disable the auth?,"<p>**validateMyRequest javascript function is as per below **</p>
<p>this function validates the post api call .</p>
<pre><code>file.js

// this function validates the token 
const validateToken = async (req, res) =&gt; {
    try {
        await getAuthInfo(req);
    } catch (err) {
        throw err;
    }


// this function validates the post api call request  
const validateMyRequest = async (req, res, next) =&gt; {
    try {
        await validateToken(req, res);
        if (!req.file || !req.body.filename || !req.body.filetype) {
            return res.status(400).send(
                {
                    code: '400',
                    message: 'Invalid request',
                },
            );
        }
    } catch (err) {
        next(err);
    }
    next();
};

// this function stores the file in database
const storeFile = async (request, response, next) =&gt; {
// logic to store file
try {
        const client = await connectToDB();
        const db = client.db('test');
        const fileCollection = db.collection('files');
        const fileRecord = { name: `${request.body.filename}`, type: `${request.body.filetype}` };
        const resp = await fileCollection.insertOne(fileRecord);
    } catch (error) {
        throw error;
    }
}

const router = express.Router();
router.use(express.json());
router.use(routeLogger);
router.post('/', upload.single('input'), validateMyRequest, storeFile);
module.exports = {
    validateMyRequest, storeFile, router,
};
</code></pre>
<p>fileTest.js - (unit testing with mocha, sinon and supertest)</p>
<p>there seems to be issue with below stubbing logic and test case fails with 500 and expected response is 200</p>
<pre><code>const storeFileStub = sinon.stub(fileController, 'validateMyRequest').resolves(Promise.resolve('next()'));
</code></pre>
<blockquote>
<pre><code>fileTest.js

const fileController = require('../../../src/controllers/file.js');

const app = express();
app.use(express.urlencoded({ extended: false }));
app.use('/', packagesRoute.router);


describe('the post controller - Create a file', () =&gt; {
      it('should return a 200 status when all parameters are passed correctly', async () =&gt; {
      const storeFileStub = sinon.stub(fileController, 'validateMyRequest').resolves(Promise.resolve('next()'));
      await request(app)
          .post('/')
          .field('filename', 'testfile')
          .field('filetype', 'pdf')
          .attach('input', 'test/test.zip')
          .set('Content-Type', 'multipart/form-data')
                  .set('Authorization', `Bearer wjeijwiejwe`)
          .expect(200)
          .expect(response =&gt; {
              assert.deepStrictEqual(response.status, 200);
          });
      storeFileStub.restore();
});
</code></pre>
</blockquote>
<p>I tried adding the sinon stub method from as per below but test case is failing
<code>Error: expected 200 &quot;OK&quot;, got 401 &quot;Unauthorized&quot;</code></p>
<p><code>const storeFileStub = sinon.stub(fileController, 'validateMyRequest').resolves(Promise.resolve('next()'));</code></p>
",https://stackoverflow.com/questions/76342067/sinon-library-how-to-mock-this-async-validatemyrequest-function-to-disable-the-a,"['javascript', 'unit-testing', 'mocha.js', 'sinon', 'supertest']",15,False,0,0
Error &quot;Variable is used before being assigned&quot; in an Angular unit test although it&#39;s like in an article,"<p>I'm new at Angular unit tests and try to test an API access.</p>
<p>Here's my code:</p>
<pre><code>import { ComponentFixture, TestBed } from '@angular/core/testing'
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'
import { JwtHelperService, JWT_OPTIONS } from '@auth0/angular-jwt'

import { AuthService } from '../../services/auth.service'
import { UserService } from '../../services/user.service'
import { WorkService } from '../../services/work.service'
import { ErrorToLogService } from '../../services/errorToLog.service'

import { FooterComponent } from './footer.component'

describe('FooterComponent', () =&gt; {
  let component: FooterComponent
  let fixture: ComponentFixture&lt;FooterComponent&gt;
  let httpController: HttpTestingController

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [
        AuthService,
        UserService,
        WorkService,
        ErrorToLogService,
        JwtHelperService,
        { provide: JWT_OPTIONS, useValue: JWT_OPTIONS },
      ],
      declarations: [ FooterComponent ]
    })
    .compileComponents()
  })

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(FooterComponent)
    component = fixture.componentInstance
    fixture.detectChanges()
    httpController = TestBed.inject(HttpTestingController)
  })

  afterEach(() =&gt; {
    TestBed.resetTestingModule()
  })

  it('should create', () =&gt; {
    expect(component).toBeTruthy()
  })

  it('Check API returns the webmaster',  () =&gt;  {
    let res: string
    component.getUserService().getWebmasterEmail().subscribe(
      data =&gt; res = data,
    )

    const req = httpController.expectOne({
      method: 'GET',
      url: `/api/getWebmasterEmail`,
    })

    req.flush(&quot;toto&quot;)
    expect(res).toEqual(&quot;toto&quot;)
  })
})
</code></pre>
<p>The test <code>Check API returns the webmaster</code> doesn't compile because <code>Variable 'res' is used before being assigned</code>.</p>
<p>I kind of understand but I can't see why it would work better in the paragraph &quot;Angular Service Unit Testing Example with HttpClient&quot; of <a href=""https://www.dotnetcurry.com/angularjs/unit-testing-angular-services"" rel=""nofollow noreferrer"">this article</a> (test &quot;should return data&quot;).</p>
<p>Anyone to shed light on this issue?</p>
",https://stackoverflow.com/questions/75574625/error-variable-is-used-before-being-assigned-in-an-angular-unit-test-although,"['angular', 'typescript', 'unit-testing', 'karma-jasmine']",60,True,0,1
Testing .Net Library Options Don&#39;t Appear,"<p>I'm currently learning unit testing with C# in VS Code and I'm using the .Net framework, not .Net Core. When I try <code>Assert.Equal(exp, act)</code>, I have to force it in because it doesn't generate automatically and it thinks I want to type something else. How do I allow the Xunit testing library options to show up in VS Code?</p>
<p><a href=""https://i.stack.imgur.com/0V03n.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0V03n.png"" alt=""enter image description here"" /></a></p>
<p><a href=""https://i.stack.imgur.com/Rz7JU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Rz7JU.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/75328336/testing-net-library-options-dont-appear,"['c#', 'visual-studio-code', 'xunit']",30,False,0,1
Unit Test Clarity Language,"<p>I have a question on about Unit Test
While I putting some code on Tx.contractCall in the .ts file, what types should I choose if I want to put contract name?</p>
<pre><code>Tx.contractCall(
                &quot;&quot;dex&quot;&quot;,
                &quot;&quot;provide-liquidity&quot;&quot;,
                [
                    types.principal(deployer).avocado, --&gt; This part....(I already checked it works on console, but don't know how to express in .ts files. 
                    types.uint(10000),
                    types.uint(10000),

                ],
                deployer,
            )
</code></pre>
<p>ps. it's console code I checked.

(contract-call? .dex provide-liquidity .avocado u100 u100). -&gt; I would like to convert this statement to the above ts Unit testing.&quot;</p>
",https://stackoverflow.com/questions/75989655/unit-test-clarity-language,"['stack', 'smartcontracts', 'clarity-lang', 'stacks-blockchain']",8,False,0,0
publish codecoverage for scala unit test results in Azure devops,"<pre><code>script: |
      cd $(Build.Repository.LocalPath)/framework/project1-scala/project1-scala &amp;&amp; sbt clean
      echo &quot;sbt Clean&quot;
    displayName: 'Running $ sbt clean'
  - script: |
      cd $(Build.Repository.LocalPath)/framework/project1-scala/project1-scala &amp;&amp; sbt update
      echo &quot;sbt update&quot;
    displayName: 'Running $ sbt update'
  - script: |
      cd $(Build.Repository.LocalPath)/framework/project1-scala/project1-scala &amp;&amp; sbt compile
      echo &quot;sbt compile&quot;
    displayName: 'Running $ sbt compile'
  - script: |
      cd $(Build.Repository.LocalPath)/framework/project1-scala/project1-scala &amp;&amp; sbt clean coverage test
      echo &quot;sbt test &amp; coverage&quot;
    displayName: 'Running $ sbt test &amp; coverage'
  - script: |
      cd $(Build.Repository.LocalPath)/framework/project1-scala/project1-scala  &amp;&amp; sbt coverageReport
      echo &quot;sbt coverageReport&quot;      
    displayName: 'Running $ sbt coverageReport'
  - task: PublishCodeCoverageResults@1
    displayName: 'Publish code coverage'
    inputs:
      codeCoverageTool: 'Cobertura'
      summaryFileLocation: '$(System.DefaultWorkingDirectory)/**/scoverage.xml'
      reportDirectory: '$(System.DefaultWorkingDirectory)/**/htmlcov
</code></pre>
<p>'I want to see coverageReport in Azure pipeline UI but it is not showing. Even though I have given scoverage.xml file path correctly.It seems this file not recognizing while generating the coveragrereport.This is scala unit testing with scoverage plugin.  All three files are publishing but I could not be able to see the results in codecoverage tab'</p>
<p><a href=""https://i.stack.imgur.com/MBomi.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/MBomi.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/76093700/publish-codecoverage-for-scala-unit-test-results-in-azure-devops,"['azure', 'scala', 'azure-devops', 'sbt', 'code-coverage']",40,False,0,0
How to use the Stub in Rhino.Mocks to simulate System functions,"<p>In unit testing, I often use Stub to mock third-party functions.</p>
<p>But I don't know how to Stub a code like this.</p>
<p><a href=""https://i.stack.imgur.com/65cmJ.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
<p>I want to control the return value of registry.</p>
<p>I tried to use the following for Stub.</p>
<pre><code>    RegistryKey registry = MockRepository.GenerateMock&lt;RegistryKey&gt;();
    registry.Stub(x =&gt; x.GetValue(keyName)).Return(&quot;123&quot;).IgnoreArguments();
    var Path = _mock.GetAppRegistryPath(appItem, keyName);
</code></pre>
<p>But I found that the value of resgistry is not the value I set.</p>
",https://stackoverflow.com/questions/75680883/how-to-use-the-stub-in-rhino-mocks-to-simulate-system-functions,"['c#', 'rhino-mocks']",15,True,0,1
Swift XC UnitTest of PassthrowSubject is getting crashed while access sut object,"<p>I am very new in iOS development unit testing.
I have a view model as below</p>
<pre><code>class PostsViewViewModel {
    private let serviceRequest: NetworkRequestProtocol
    public private(set) var requestOutput: PassthroughSubject&lt;RequestOutput, Never&gt; = .init()
 private var cancellables = Set&lt;AnyCancellable&gt;()

    init(
        request: NetworkRequestProtocol,
        user: LoginUserModel,
        codeDataManager: CoreDataManagerProtocol) {
            serviceRequest = request
            loadPostsFromServerFor(user: user)
        }

    private func loadPostsFromServerFor(user: LoginUserModel) {
        Task {
            do {
                let postsRecived = try await serviceRequest.callService(
                    with: ServiceEndPoint.fetchPostsForUser(id: user.userid),
                    model: [PostModel].self,
                    serviceMethod: .get
                )
                if postsRecived.isEmpty {
                    requestOutput.send(.fetchPostsDidSucceedWithEmptyList)
                } else {
                    recievedRawPostsModel = postsRecived
                    createPostModelsFromPostRecieved(postsRecived)
                    requestOutput.send(.fetchPostsDidSucceed)
                }
            } catch {
                requestOutput.send(.fetchPostsDidFail)
            }
        }
    }
}
extension PostsViewViewModel {        
    enum RequestOutput {
        case fetchPostsDidFail
        case fetchPostsDidSucceed
        case fetchPostsDidSucceedWithEmptyList
        case reloadPost
    }
  }
</code></pre>
<p>Now I created a test class of ViewModel as below</p>
<pre><code>final class PostViewViewModelTest: XCTestCase {
    let userInput: PassthroughSubject&lt;PostsViewViewModel.UserInput, Never&gt; = .init()

    private var cancellable = Set&lt;AnyCancellable&gt;()
    private let mockUser = LoginUserModel(userid: 1)
    private let coreDataManager = CoreDataStackInMemory()
    private var sutPostViewModel: PostsViewViewModel!
    
    override func setUp() {
        sutPostViewModel = PostsViewViewModel(
            request: MockNetworkRequestPostSuccess(),
            user: mockUser, codeDataManager: coreDataManager
        )
    }
    
    override func tearDown() {
       sutPostViewModel = nil
    }
    
    func testPostsViewViewModel_WhenPostModelLoaded_NumberOfRowsSouldBeMoreThanZero()  {
//        let postViewModel = sutPostViewModel!

        self.sutPostViewModel.requestOutput
            //.receive(on: DispatchQueue.main)
            .sink { [weak self] output in
                XCTAssertTrue(output == .fetchPostsDidSucceed)
                XCTAssertTrue((self?.sutPostViewModel.numberOfRowsInPostTableView)! &gt; 0)
            }
            .store(in: &amp;cancellable)
    }
    
    func testPostsViewViewModel_WhenPostModelLoaded_GetPostAtGivenIndexPathMustHaveEqualPostID() {
//        let postViewModel = sutPostViewModel!
        self.sutPostViewModel.requestOutput
            .receive(on: DispatchQueue.main)
            .sink { [weak self] output in
            print(output == .reloadPost)
            let post = self?.sutPostViewModel.getPost(at: IndexPath(row: 0, section: 0))
            let postModel: [PostModel] = JSONLoader.load(&quot;Posts.json&quot;)
            XCTAssertTrue(post.postID == postModel[0].id)
        }
        .store(in: &amp;cancellable)
    }
}
</code></pre>
<p>But test cases get crashed while access sutPostViewModel. I am unable to understand what am I doing wrong here.</p>
<p>While debugging I found tearDown() is being called before sink and test crash.</p>
<p><a href=""https://i.stack.imgur.com/tK2qZ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/tK2qZ.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/75454208/swift-xc-unittest-of-passthrowsubject-is-getting-crashed-while-access-sut-object,"['ios', 'swift', 'xcode', 'unit-testing']",75,True,0,1
C++ writing into .log file doesn&#39;t work in unit test project,"<p>I am using Visual Studio, C++, sqlapi and the Microsoft Unit Testing Framework for C++.</p>
<p>I wrote a simple method in my main project for writing some errors into a .log file when an exception is coming. The method is calling when I am catching a SAException.</p>
<pre><code>void LogException(const SAException&amp; e)
    {
        auto now = system_clock::now();
        auto now_c = system_clock::to_time_t(now);

        stringstream ss;
        ss &lt;&lt; put_time(localtime(&amp;now_c), &quot;%Y-%m-%d %H:%M:%S&quot;) &lt;&lt; &quot;\n&quot; &lt;&lt; (const char*)e.ErrText() &lt;&lt; &quot;\n\n&quot;;
        ofstream logfile(&quot;exceptions.log&quot;, ios_base::app);cout &lt;&lt; put_time(localtime(&amp;now_c), &quot;%Y-%m-%d %H:%M:%S&quot;) &lt;&lt; &quot;\n&quot; &lt;&lt; (const char*)e.ErrText() &lt;&lt; &quot;\n\n&quot;;
        logfile &lt;&lt; ss.str();
        logfile.close();
    }
</code></pre>
<p>As far as I am only running the project in Visual Studio everythings fine and the .log file got some text. Now I am using a second project with the the Microsoft Unit Testing Framework for C++ and do some unit testsing for my methods. When I now run my tests the .log file is not getting new entries but the tests themselves are working fine as always.</p>
<p>One test method where the .log file should get a new entry.</p>
<pre><code>TEST_METHOD(openConnnectionException)
        {
            myDb-&gt;initParameter(&quot;dsn&quot;, &quot;user&quot;, &quot;pw&quot;, &quot;client&quot;, &quot;db&quot;);
            Assert::IsTrue(myDb-&gt;openConnection() == -1);
        }
</code></pre>
<p>the openConnection() method</p>
<pre><code>int openConnection()
    {
        try
        {
            //trying to open the connection
        }
        catch (SAException&amp; sae)
        {
            cout &lt;&lt; &quot;Error opening database. Check parameters or contact an administrator\n&quot;;
            LogException(sae);
            return -1;
        }
    };
</code></pre>
<p>My code is going trough the catch block and the LogException() method giving me the right return value but the .log file is still not getting a new entry. Somebody got any ideas why it's not working?</p>
",https://stackoverflow.com/questions/76218267/c-writing-into-log-file-doesnt-work-in-unit-test-project,"['c++', 'unit-testing', 'exception', 'logging']",20,False,0,1
Unit Testing in C scope pointer issue,"<p>I am trying to implement unit testing in C using Ceedling.</p>
<pre><code>struct Person *list;
/* TASK_FIND_BY */
void test_main_task_find_by_normal(void)
{
    char *string = (char *)malloc(sizeof(char));
    struct Person new_list_instance;
    struct Person *new_list = &amp;new_list_instance;
    ask_input_ExpectAndReturn(string);
    llist_find_by_ExpectAndReturn(list, string, new_list);
    llist_print_Expect(new_list);
    llist_remove_all_Expect(&amp;new_list);

    printf(&quot;\nOutside single: %p\n&quot;, new_list);
    printf(&quot;Outside double: %p\n&quot;, &amp;new_list);

    task_find_by(list);
}
</code></pre>
<pre><code>void task_find_by(struct Person *list)
{
    char *input = NULL;
    struct Person *new = NULL;

    printf(&quot;Input exact name/surname/email/phone: &quot;);
    input = ask_input();
    if (input == NULL) {
        printf(&quot;Error!&quot;);
        return;
    }
    new = llist_find_by(list, input);
    if (new != NULL)
        llist_print(new);
    else 
        printf(&quot;Address not found!\n&quot;);
    
    printf(&quot;\nInside single: %p\n&quot;, new);
    printf(&quot;Inside double: %p\n&quot;, &amp;new);
    
    free(input);
    llist_remove_all(&amp;new);
}

</code></pre>
<p>I expect the function inside <code>task_find_by</code> to be called with the same argument as here: <code>llist_remove_all_Expect(&amp;new_list)</code>.
But the actual function is called with the address of <code>new</code> pointer, where <code>new</code> holds the <code>new_list</code>. Since <code>new_list</code> and <code>new</code> are different pointers their addresses are different. Is there any way to test the called argument without changing the implementation of <code>task_find_by</code> function?</p>
<pre><code>  - &quot;Outside single: 0x7ffc2e3c03d0&quot;
  - &quot;Outside double: 0x7ffc2e3c03c0&quot;
  - &quot;Inside single: 0x7ffc2e3c03d0&quot;
  - &quot;Inside double: 0x7ffc2e3c0398&quot;
</code></pre>
",https://stackoverflow.com/questions/76208999/unit-testing-in-c-scope-pointer-issue,"['c', 'unit-testing', 'pointers', 'ceedling']",98,True,2,2
How to create a mock mongo client for unit testing?,"<p>I am new to Golang, trying to figure out how to create a mock mongo client for unit testing. I am able to create a mock mongo collection using go.mongodb.org/mongo-driver/mongo/integration/mtest,</p>
<pre><code>mt := mtest.New(t, mtest.NewOptions().ClientType(mtest.Mock))
    defer mt.Close()

collection := mt.Coll
</code></pre>
<p>However, for creating a client, using <code>mt.Client</code> or <code>mt.Coll.Database().Client()</code> don't work - getting nil client in result.</p>
<p>Is there anything that I am missing here possibly - kindly guide, thank you!</p>
",https://stackoverflow.com/questions/75692284/how-to-create-a-mock-mongo-client-for-unit-testing,"['mongodb', 'unit-testing', 'go']",148,False,2,1
"Attempting to mock child method, fails if parent module imports it using object destructuring","<p>I was doing some basic jest unit testing in attempt to learn it more.</p>
<p>I have this issue I do not know how to explain</p>
<p>This file has the child function add</p>
<pre><code>// FileB.js 

const add = (a, b) =&gt; {
  return a + b;
}

module.exports = {
  add,
};
</code></pre>
<p>This file has the parent function addTen</p>
<pre><code>// FileA.js

const { add } = require('./FileB');

const addTen = num =&gt; {
  return add(10, num);
}

module.exports = {
  addTen,
};
</code></pre>
<p>this is my test file, where I am trying to either check <code>&lt;mockedFunction/spy&gt;.mock.calls</code> or do <code>toHaveBeenCalledWith</code> to see if the inner child method, add, is being passed in 10,10 when i call <code>addTen(10);</code></p>
<p>This file is not used in any real env, its simply me trying to learn jest + unit testing more.</p>
<pre><code>// randomTest.js

const { addTen } = require('../src/FileA');
const fileB = require('../src/FileB'); 

describe('temp', () =&gt; {
  it('temp', () =&gt; {
    const addSpy = jest.spyOn(fileB, 'add');

    addTen(10);
    console.log(addSpy.mock.calls);

    expect(addSpy).toHaveBeenCalledWith(10,10)
  });
});
</code></pre>
<p>Now for the issue, the test fails, saying <code>add</code> was never called, or nothing passed in. I logged the add function within <code>FileB</code></p>
<p>However, if I modify <code>FileA</code> in this way, by importing entore module instead of destructuring, the test passes and I cna log out the functions and everything and see it works</p>
<p>This is what works</p>
<pre><code>// FileA.js

const fileB = require('./FileB');

const addTen = num =&gt; {
  return fileB.add(10, num);
}

module.exports = {
  addTen,
};
</code></pre>
<p>Why does this slight change work? And is there a way to avoid this and keep my destrcutoring?</p>
",https://stackoverflow.com/questions/75036458/attempting-to-mock-child-method-fails-if-parent-module-imports-it-using-object,"['javascript', 'node.js', 'unit-testing', 'jestjs']",129,True,0,1
Not able to create mock object using mocker,"<p>I am trying to create mock object for unit testing but somehow always actual object is called.
Below is the code for reference:-</p>
<ol>
<li>utility_functions.py</li>
</ol>
<pre><code>import os
import json


def get_module_configurations(key):
    config = os.getcwd()
    config = config + &quot;\\xyz.json&quot;
    with open(config) as f:
        module_config = json.load(f)
    module_config = module_config[key]
    return module_config

</code></pre>
<ol start=""2"">
<li>load_class</li>
</ol>
<pre><code>from importlib import import_module
from inspect import isclass, isabstract


def load_module(data):
    package_path = data['Package']
    module_name = data['ModuleName']
    class_name = data['ClassName']

    try:
        module_name = str(module_name.split('.py')[0])
        module = import_module('.' + module_name, package_path)

    except Exception as error:
        pass

    try:
        _class = getattr(module, class_name)
    except Exception as error:
        pass
    if isclass(_class) and not (isabstract(_class)):
        return _class
    else:
        return None

</code></pre>
<ol start=""3"">
<li>function1.py</li>
</ol>
<pre><code>import load_class
from utility_functions import get_module_configurations


def load_helpers(task_name):
    module = get_module_configurations(task_name)
    cls = load_class.load_module(module)
    return cls
</code></pre>
<ol start=""4"">
<li>test_function.py</li>
</ol>
<pre><code>import pytest
from function1 import load_helpers


def test_mock(mocker):
    class_to_load = {&quot;Package&quot;: &quot;Test&quot;, &quot;ModuleName&quot;: &quot;default_class.py&quot;, &quot;ClassName&quot;: 
                    &quot;DefaultClass&quot;}
    mocker.patch('function1.load_helpers', return_value= class_to_load)
    result = load_helpers('c')
    assert result is not None
</code></pre>
<p>Since I am mocking, load helpers should not be called but it always calls actual implementation saying path is invalid.</p>
<p>I am missing something basic but cannot figure out what.
Any help will be great.</p>
",https://stackoverflow.com/questions/75006041/not-able-to-create-mock-object-using-mocker,"['python-3.x', 'pytest', 'pytest-mock']",100,True,1,1
Not able to create mock object using mocker,"<p>I am trying to create mock object for unit testing but somehow always actual object is called.
Below is the code for reference:-</p>
<ol>
<li>utility_functions.py</li>
</ol>
<pre><code>import os
import json


def get_module_configurations(key):
    config = os.getcwd()
    config = config + &quot;\\xyz.json&quot;
    with open(config) as f:
        module_config = json.load(f)
    module_config = module_config[key]
    return module_config

</code></pre>
<ol start=""2"">
<li>load_class</li>
</ol>
<pre><code>from importlib import import_module
from inspect import isclass, isabstract


def load_module(data):
    package_path = data['Package']
    module_name = data['ModuleName']
    class_name = data['ClassName']

    try:
        module_name = str(module_name.split('.py')[0])
        module = import_module('.' + module_name, package_path)

    except Exception as error:
        pass

    try:
        _class = getattr(module, class_name)
    except Exception as error:
        pass
    if isclass(_class) and not (isabstract(_class)):
        return _class
    else:
        return None

</code></pre>
<ol start=""3"">
<li>function1.py</li>
</ol>
<pre><code>import load_class
from utility_functions import get_module_configurations


def load_helpers(task_name):
    module = get_module_configurations(task_name)
    cls = load_class.load_module(module)
    return cls
</code></pre>
<ol start=""4"">
<li>test_function.py</li>
</ol>
<pre><code>import pytest
from function1 import load_helpers


def test_mock(mocker):
    class_to_load = {&quot;Package&quot;: &quot;Test&quot;, &quot;ModuleName&quot;: &quot;default_class.py&quot;, &quot;ClassName&quot;: 
                    &quot;DefaultClass&quot;}
    mocker.patch('function1.load_helpers', return_value= class_to_load)
    result = load_helpers('c')
    assert result is not None
</code></pre>
<p>Since I am mocking, load helpers should not be called but it always calls actual implementation saying path is invalid.</p>
<p>I am missing something basic but cannot figure out what.
Any help will be great.</p>
",https://stackoverflow.com/questions/75006041/not-able-to-create-mock-object-using-mocker,"['python-3.x', 'pytest', 'pytest-mock']",100,True,1,1
Explain @Mock and @Spy in Java?,"<p>I Recently Started Learning About unit testing i came across Mockito Framwork i read about @Mock and @Spy when() etc..</p>
<pre><code>@Mock
Service service;

@Test
void test(){
   when(service.runCode(Mock.anyString()).thenReturn(&quot;Working&quot;);
}

</code></pre>
<p>What my doubt in the above line is dose the runCode(String a) will get excuted OR once the Method is invoked then what i given the thenReturn() part will given by the mock</p>
<p>I am trying to understand mock</p>
",https://stackoverflow.com/questions/76352205/explain-mock-and-spy-in-java,"['mockito', 'junit5']",40,True,1,1
How do I test that an element has a `display: none` in React using Testing-Library and Jest,"<p>I recently start introducing some unit-testing in React using Testing Library and Jest and I'm looking to check if the css properties are working correctly. Not sure how should I check them with <code>expect</code>.</p>
<p>My test is expecting that an element will have a <code>display: none</code> and when hover a <code>display: block</code> and <code>color: hsl(0, 0%, 93%)</code>.</p>
<p>I tried to use <code>toHaveStyle</code> to check the style but my test is failing.</p>
<pre><code>test('Card like-function is working correctly', async() =&gt; {
    const user = userEvent.setup();
    render(&lt;Card card={cardData}/&gt;);

    const card = screen.getByRole('article', {name: 'card'});
    const like = screen.getByText('❤');
    expect(like).toHaveStyle('display: none');

    await user.hover(card);
    const likeHover = screen.getByText('❤');
    expect(like).toHaveStyle('display: block');
    expect(likeHover).toHaveStyle('color: hsl(0, 0%, 93%)');
})
</code></pre>
",https://stackoverflow.com/questions/75988828/how-do-i-test-that-an-element-has-a-display-none-in-react-using-testing-libra,"['reactjs', 'jestjs', 'react-testing-library']",134,False,0,0
How to test image carousel in react,"<p>I am creating an image carousel component, see below:</p>
<h2>ImageSlider</h2>
<pre><code> import React,{useState} from 'react'
import {BsChevronCompactLeft,BsChevronCompactRight} from 'react-icons/bs'

function ImageSlider({images}) {

  const [currentIndex, setCurrentState] = useState(0);
  const length = images.length;

  const prevImage = () =&gt; {
    const isFirstSlide = currentIndex === 0
    const newIndex = isFirstSlide ? length - 1 : currentIndex - 1
    setCurrentState(newIndex)
  }
  
  const nextImage = () =&gt; {
    const isLastSlide = currentIndex === length - 1
    const newIndex = isLastSlide ? 0 : currentIndex + 1 
    setCurrentState(newIndex)
  }
  
  return (
    &lt;div className='max-w-[800px] h-[500px] w-full m-auto py-16 px-4 relative'&gt;
    {/* &lt;FaArrowAltCircleLeft className='left-arrow' onClick={prevImage}&gt; 
  &lt;/FaArrowAltCircleLeft&gt;
    &lt;FaArrowAltCircleRight className='right-arrow' onClick={nextImage}&gt;&lt;/FaArrowAltCircleRight&gt; */}
      &lt;div 
      style={{ backgroundImage: `url(&quot;${images[currentIndex]}&quot;)` }}  
      className='w-full h-full rounded-2xl bg-center bg-cover duration-500'
    &gt;

      &lt;/div&gt;
      &lt;div className='absolute top-50% -translate-x-0 translate-y-[-50%] left-5 text-2xl rounded-full p-2 bg-black/20 text-white cursor-pointer'&gt;
        &lt;BsChevronCompactLeft size={30} onClick={prevImage}&gt;&lt;/BsChevronCompactLeft&gt;
      &lt;/div&gt;
      &lt;div className='absolute top-50% -translate-x-0 translate-y-[-50%] right-5 text-2xl rounded-full p-2 bg-black/20 text-white cursor-pointer'&gt;
        &lt;BsChevronCompactRight size={30} onClick={nextImage}&gt;&lt;/BsChevronCompactRight&gt;
      &lt;/div&gt;


    &lt;/div&gt;
  )
}
</code></pre>
<p>export default ImageSlider</p>
<hr />
<p>it gets passed images. However, I can't seem to be able to test if the image is rendered or not, and if the buttons work to change images.</p>
<h2>I have tried</h2>
<pre><code> import ImageSlider from &quot;./component/ImageSlider&quot; 
    import {render, screen} from &quot;@testing-library/react&quot;
    import React from &quot;react&quot;
    import image1 from &quot;./image1.jpg&quot;
    import image2 from &quot;./image2.jpg&quot;
    
    test('should render images', () =&gt; {
      const images = [image1, image2];
      render(&lt;ImageSlider images={images} role='img'/&gt;);
      const img = screen.getAllByTestId(&quot;img&quot;);
      expect(img).toBeInTheDocument();
    });

// test('should navigate to the next image', () =&gt; {
//   const images = [image1, image2];
//   render(&lt;ImageSlider images={images} /&gt;);
//   fireEvent.click(screen.getByText('Next'));
//   expect(screen.getByAltText('image2')).toBeInTheDocument();
// });

// test('should navigate to the previous image', () =&gt; {
//   const images = [image1, image2];
//   render(&lt;ImageSlider images={images} /&gt;);
//   fireEvent.click(screen.getByText('Previous'));
//   expect(screen.getByAltText('image2')).toBeInTheDocument();
// });
</code></pre>
<p>But there doesn't seem to be very good resources on image unit testing online. any help would be appreciated.</p>
",https://stackoverflow.com/questions/76169998/how-to-test-image-carousel-in-react,"['javascript', 'reactjs', 'image', 'unit-testing', 'testing']",35,False,0,0
how to assert values from anonymous type passed from an oknegatiatedresult,"<p>I'm currently unit testing controllers, and my controller code goes like this</p>
<pre><code>public IHttpActionResult Submit(){
    ...
    return Ok(new { Success = true, ErrorMessage = &quot;&quot;, RedirectUrl = &quot;http://myurl&quot; });
}
</code></pre>
<p>in my unit test method goes like this</p>
<pre><code>var result = sut.Submit(); //result is not null
</code></pre>
<p>result is not null however I can't get any of the anonymous properties sent by the method I called. no other properties like &quot;value&quot; or &quot;content&quot; available from VS intelisense. any idea how to get those values so I can assert them further?</p>
",https://stackoverflow.com/questions/75478731/how-to-assert-values-from-anonymous-type-passed-from-an-oknegatiatedresult,['unit-testing'],11,False,0,0
Coverage-Gutter extension for visual studio code is not showing line coverage - .NET,"<p>For .net unit testing I installed Coverage Gutter in visual studio code.</p>
<p><a href=""https://marketplace.visualstudio.com/items?itemName=ryanluker.vscode-coverage-gutters"" rel=""nofollow noreferrer"">https://marketplace.visualstudio.com/items?itemName=ryanluker.vscode-coverage-gutters</a>.</p>
<p>But is not showing the line coverage.</p>
<p>when I press Coverage Gutter display coverage or press the &quot;watch&quot; option in the footer it says &quot;Could not find coverage file&quot;</p>
<p>Error:</p>
<p><code>Could not find a Coverage file! Searched for lcov.info, cov.xml, coverage.xml, jacoco.xml, coverage.cobertura.xml</code></p>
<p><a href=""https://i.stack.imgur.com/xygEp.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/xygEp.png"" alt=""Project structure"" /></a></p>
<p>my setting.json</p>
<pre><code>{

  &quot;dotnet-test-explorer.testProjectPath&quot;: &quot;**/*test.csproj&quot;,
  &quot;dotnet-test-explorer.runInParallel&quot;: true,
  &quot;coverage-gutters.showLineCoverage&quot;: true,
  &quot;dotnet-test-explorer.testArguments&quot;: &quot;/p:CollectCoverage=true /p:CoverletOutputFormat=lcov /p:CoverletOutput=../../lcov.info&quot;,
  &quot;coverage-gutters.coverageBaseDir&quot;: &quot;**&quot;,
  &quot;coverage-gutters.coverageFileNames&quot;: [
    &quot;lcov.info&quot;,
    &quot;cov.xml&quot;,
    &quot;coverage.xml&quot;,
    &quot;jacoco.xml&quot;,
    &quot;coverage.cobertura.xml&quot;
  ]
}

</code></pre>
<p>I think the issue is in <code> &quot;coverage-gutters.coverageBaseDir&quot;: &quot;**&quot;,</code>
Can anyone help me to fix the issue?</p>
",https://stackoverflow.com/questions/74983417/coverage-gutter-extension-for-visual-studio-code-is-not-showing-line-coverage,"['unit-testing', 'visual-studio-code', 'code-coverage']",531,False,2,1
Spring Boot Integration Testing with TestContainers with MySql - BeanDefinitionStoreException,"<p>I'm trying to implement an integration test using TestContainers. But I'm continuously getting BeanDefinitionStoreException.</p>
<p>My Test Class</p>
<pre><code>    @SpringBootTest
@AutoConfigureMockMvc
class OrderServiceApplicationTests {

    @Container
    static final MySQLContainer mySQLContainer = new MySQLContainer&lt;&gt;(&quot;mysql:8.0.30&quot;)
            .withDatabaseName(&quot;testcontainer&quot;)
            .withUsername(&quot;test&quot;)
            .withPassword(&quot;test&quot;);

    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    private MockMvc mockMvc;
    @Autowired
    OrderRepository orderRepository;

    @DynamicPropertySource
    static void setProperties(DynamicPropertyRegistry properties){
        properties.add(&quot;spring.datasource.url&quot;, mySQLContainer::getJdbcUrl);
        properties.add(&quot;spring.datasource.username&quot;, mySQLContainer::getUsername);
        properties.add(&quot;spring.datasource.password&quot;, mySQLContainer::getPassword);
    }

    @Test
    void shouldPlaceOrder() throws Exception {

        OrderItemsDto orderItemsDto = OrderItemsDto.builder()
                .skuCode(&quot;Test SKU&quot;)
                .price(new BigDecimal(123.32))
                .quantity(2).build();
        OrderDto orderDto = OrderDto.builder()
                .orderItemsDtos(Arrays.asList(orderItemsDto)).build();
        String reqString = objectMapper.writeValueAsString(orderDto);
        mockMvc.perform(MockMvcRequestBuilders.post(&quot;api/order&quot;)
        .contentType(MediaType.APPLICATION_JSON)
        .content(reqString))
                .andExpect(status().isCreated());
        Assertions.assertTrue(orderRepository.findAll().size() == 1);

    }

}
</code></pre>
<p>Here is my POM File</p>
<pre><code>    &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;3.1.0-SNAPSHOT&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;
    &lt;groupId&gt;com.example&lt;/groupId&gt;
    &lt;artifactId&gt;order-service&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
    &lt;name&gt;order-service&lt;/name&gt;
    &lt;description&gt;Order Service&lt;/description&gt;
    &lt;properties&gt;
        &lt;java.version&gt;17&lt;/java.version&gt;
    &lt;/properties&gt;
    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;com.mysql&lt;/groupId&gt;
            &lt;artifactId&gt;mysql-connector-j&lt;/artifactId&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
            &lt;artifactId&gt;lombok&lt;/artifactId&gt;
            &lt;optional&gt;true&lt;/optional&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;
            &lt;artifactId&gt;mysql&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;dependencyManagement&gt;
        &lt;dependencies&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;
                &lt;artifactId&gt;testcontainers-bom&lt;/artifactId&gt;
                &lt;version&gt;1.18.0&lt;/version&gt;
                &lt;type&gt;pom&lt;/type&gt;
                &lt;scope&gt;import&lt;/scope&gt;
            &lt;/dependency&gt;
        &lt;/dependencies&gt;
    &lt;/dependencyManagement&gt;

    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
                &lt;configuration&gt;
                    &lt;excludes&gt;
                        &lt;exclude&gt;
                            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
                            &lt;artifactId&gt;lombok&lt;/artifactId&gt;
                        &lt;/exclude&gt;
                    &lt;/excludes&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;
    &lt;repositories&gt;
        &lt;repository&gt;
            &lt;id&gt;spring-milestones&lt;/id&gt;
            &lt;name&gt;Spring Milestones&lt;/name&gt;
            &lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;
            &lt;snapshots&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/snapshots&gt;
        &lt;/repository&gt;
        &lt;repository&gt;
            &lt;id&gt;spring-snapshots&lt;/id&gt;
            &lt;name&gt;Spring Snapshots&lt;/name&gt;
            &lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt;
            &lt;releases&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/releases&gt;
        &lt;/repository&gt;
    &lt;/repositories&gt;
    &lt;pluginRepositories&gt;
        &lt;pluginRepository&gt;
            &lt;id&gt;spring-milestones&lt;/id&gt;
            &lt;name&gt;Spring Milestones&lt;/name&gt;
            &lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;
            &lt;snapshots&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/snapshots&gt;
        &lt;/pluginRepository&gt;
        &lt;pluginRepository&gt;
            &lt;id&gt;spring-snapshots&lt;/id&gt;
            &lt;name&gt;Spring Snapshots&lt;/name&gt;
            &lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt;
            &lt;releases&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/releases&gt;
        &lt;/pluginRepository&gt;
    &lt;/pluginRepositories&gt;

&lt;/project&gt;
</code></pre>
<p>This is my console.</p>
<pre><code>16:14:14.843 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils -- Could not detect default configuration classes for test class [com.example.orderservice.OrderServiceApplicationTests]: OrderServiceApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
16:14:14.940 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper -- Found @SpringBootConfiguration com.example.orderservice.OrderServiceApplication for test class com.example.orderservice.OrderServiceApplicationTests
16:14:15.163 [main] WARN org.testcontainers.utility.TestcontainersConfiguration -- Attempted to read Testcontainers configuration file at file:/C:/Users/binul/.testcontainers.properties but the file was not found. Exception message: FileNotFoundException: C:\Users\binul\.testcontainers.properties (The system cannot find the file specified)
16:14:15.169 [main] INFO org.testcontainers.utility.ImageNameSubstitutor -- Image name substitution will be performed by: DefaultImageNameSubstitutor (composite of 'ConfigurationFileImageNameSubstitutor' and 'PrefixingImageNameSubstitutor')

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v3.1.0-SNAPSHOT)

2023-05-10T16:14:15.441+05:30  INFO 13040 --- [           main] c.e.o.OrderServiceApplicationTests       : Starting OrderServiceApplicationTests using Java 17.0.7 with PID 13040 (started by binul in D:\Project Docs\R&amp;D\Microservices-Online-Shop\order-service)
2023-05-10T16:14:15.444+05:30  INFO 13040 --- [           main] c.e.o.OrderServiceApplicationTests       : No active profile set, falling back to 1 default profile: &quot;default&quot;
2023-05-10T16:14:16.013+05:30  INFO 13040 --- [           main] .t.d.DockerMachineClientProviderStrategy : docker-machine executable was not found on PATH ([C:\Program Files\Common Files\Oracle\Java\javapath, C:\Program Files (x86)\Common Files\Oracle\Java\javapath, C:\Windows\system32, C:\Windows, C:\Windows\System32\Wbem, C:\Windows\System32\WindowsPowerShell\v1.0\, C:\Windows\System32\OpenSSH\, C:\Program Files\Git\cmd, C:\Program Files\Java\jdk1.8.0_311\bin, C:\dev_tools\apache-maven-3.8.3\bin, C:\Program Files\PuTTY\, C:\Program Files\dotnet\, C:\Program Files\nodejs\, C:\Program Files\Meld\, C:\Users\binul\AppData\Local\Microsoft\WindowsApps, C:\Users\binul\AppData\Local\Programs\Microsoft VS Code\bin, C:\dev_tools\gradle-6.8.1\bin, C:\Users\binul\AppData\Roaming\npm, C:\Users\binul\.dotnet\tools])
2023-05-10T16:14:16.014+05:30 ERROR 13040 --- [           main] o.t.d.DockerClientProviderStrategy       : Could not find a valid Docker environment. Please check configuration. Attempted configurations were:
As no valid configuration was found, execution cannot continue.
See https://www.testcontainers.org/on_failure.html for more details.
2023-05-10T16:14:16.027+05:30  WARN 13040 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.example.orderservice.OrderServiceApplication]: Error processing condition on org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseConfiguration
2023-05-10T16:14:16.054+05:30  INFO 13040 --- [           main] .s.b.a.l.ConditionEvaluationReportLogger : 

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-05-10T16:14:16.088+05:30 ERROR 13040 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.example.orderservice.OrderServiceApplication]: Error processing condition on org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseConfiguration
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:524) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorGroupingHandler.lambda$processGroupImports$1(ConfigurationClassParser.java:726) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at java.base/java.lang.Iterable.forEach(Iterable.java:75) ~[na:na]
    at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorGroupingHandler.processGroupImports(ConfigurationClassParser.java:723) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorHandler.process(ConfigurationClassParser.java:694) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:182) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:415) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:287) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:344) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:115) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:747) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:565) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:733) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:435) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:311) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.test.context.SpringBootContextLoader.lambda$loadContext$3(SpringBootContextLoader.java:137) ~[spring-boot-test-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:58) ~[spring-core-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:46) ~[spring-core-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.boot.SpringApplication.withHook(SpringApplication.java:1405) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.test.context.SpringBootContextLoader$ContextLoaderHook.run(SpringBootContextLoader.java:545) ~[spring-boot-test-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:137) ~[spring-boot-test-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:108) ~[spring-boot-test-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:184) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:118) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:127) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:191) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:130) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:241) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$10(ClassBasedTestDescriptor.java:377) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:382) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$11(ClassBasedTestDescriptor.java:377) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[na:na]
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) ~[na:na]
    at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310) ~[na:na]
    at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735) ~[na:na]
    at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762) ~[na:na]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:376) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:289) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:288) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:278) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at java.base/java.util.Optional.orElseGet(Optional.java:364) ~[na:na]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:277) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:105) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:104) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:68) ~[junit-jupiter-engine-5.9.3.jar:5.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$2(NodeTestTask.java:123) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:123) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:90) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) ~[na:na]
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) ~[na:na]
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54) ~[junit-platform-engine-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53) ~[junit-platform-launcher-1.9.3.jar:1.9.3]
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69) ~[junit5-rt.jar:na]
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) ~[junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) ~[junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) ~[junit-rt.jar:na]
Caused by: java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseConfiguration
    at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:60) ~[spring-boot-autoconfigure-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:108) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:219) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser.processMemberClasses(ConfigurationClassParser.java:365) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:265) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:243) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:514) ~[spring-context-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    ... 93 common frames omitted
Caused by: java.lang.IllegalStateException: Previous attempts to find a Docker environment failed. Will not retry. Please see logs and check configuration
    at org.testcontainers.dockerclient.DockerClientProviderStrategy.getFirstValidStrategy(DockerClientProviderStrategy.java:212) ~[testcontainers-1.18.0.jar:1.18.0]
    at org.testcontainers.DockerClientFactory.getOrInitializeStrategy(DockerClientFactory.java:150) ~[testcontainers-1.18.0.jar:1.18.0]
    at org.testcontainers.DockerClientFactory.dockerHostIpAddress(DockerClientFactory.java:323) ~[testcontainers-1.18.0.jar:1.18.0]
    at org.testcontainers.containers.ContainerState.getHost(ContainerState.java:64) ~[testcontainers-1.18.0.jar:na]
    at org.testcontainers.containers.MySQLContainer.getJdbcUrl(MySQLContainer.java:104) ~[mysql-1.18.0.jar:na]
    at com.example.orderservice.OrderServiceApplicationTests.lambda$setProperties$0(OrderServiceApplicationTests.java:46) ~[test-classes/:na]
    at org.springframework.test.context.support.DynamicValuesPropertySource.getProperty(DynamicValuesPropertySource.java:43) ~[spring-test-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:85) ~[spring-core-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver$DefaultResolver.getProperty(ConfigurationPropertySourcesPropertyResolver.java:123) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver.findPropertyValue(ConfigurationPropertySourcesPropertyResolver.java:97) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver.getProperty(ConfigurationPropertySourcesPropertyResolver.java:74) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver.getProperty(ConfigurationPropertySourcesPropertyResolver.java:60) ~[spring-boot-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:552) ~[spring-core-6.0.9-20230509.130721-27.jar:6.0.9-SNAPSHOT]
    at org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseCondition.hasDataSourceUrlProperty(DataSourceAutoConfiguration.java:156) ~[spring-boot-autoconfigure-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$EmbeddedDatabaseCondition.getMatchOutcome(DataSourceAutoConfiguration.java:139) ~[spring-boot-autoconfigure-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47) ~[spring-boot-autoconfigure-3.1.0-20230509.165129-256.jar:3.1.0-SNAPSHOT]
    ... 99 common frames omitted
</code></pre>
<p>I highly suspect that this is related to injecting Mysql image into the local environment.
Note : I did the same code to Mongodb and it works fine.</p>
<p>Could anyone had the same issue and resolved ? btw unit testing becoming embarrassing :-(</p>
",https://stackoverflow.com/questions/76217978/spring-boot-integration-testing-with-testcontainers-with-mysql-beandefinitions,"['java', 'spring-boot', 'unit-testing', 'testcontainers', 'testcontainers-junit5']",164,True,2,3
Android ViewModel with StateFlow - testing issue. Test never waits for next value,"<p>I have search view model like this.
<code>searchPoiUseCase</code> doing requests to Room DB. For testing purposes i am using <code>Room.inMemoryDatabaseBuilder</code>.</p>
<pre><code>@HiltViewModel
class SearchVm @Inject constructor(
    private val searchPoiUseCase: SearchPoiUseCase
) : ViewModel() {

    private val queryState = MutableStateFlow(&quot;&quot;)
    
    @OptIn(FlowPreview::class)
    val searchScreenState = queryState
        .filter { it.isNotEmpty() }
        .debounce(500)
        .distinctUntilChanged()
        .map { query -&gt; searchPoiUseCase(SearchPoiUseCase.Params(query)) }
        .map { result -&gt;
            if (result.isEmpty()) SearchScreenUiState.NothingFound
            else SearchScreenUiState.SearchResult(result.map { it.toListUiModel() })
        }
        .stateIn(
            viewModelScope,
            SharingStarted.WhileSubscribed(5_000),
            SearchScreenUiState.None
        )
    
    fun onSearch(query: String) {
        queryState.value = query
    }

}
</code></pre>
<p>On the device this logic works perfectly fine. But i can't succeed with Unit Testing this logic.
Here is my unit test:</p>
<pre><code>@OptIn(ExperimentalCoroutinesApi::class)
@HiltAndroidTest
@Config(application = HiltTestApplication::class)
@RunWith(RobolectricTestRunner::class)
class SearchViewModelTest {

    @get:Rule
    var hiltRule = HiltAndroidRule(this)

    @Inject
    lateinit var searchUseCase: SearchPoiUseCase

    lateinit var SUT: SearchVm

    @Before
    fun setup() {
        hiltRule.inject()
        SUT = SearchVm(searchUseCase)
        Dispatchers.setMain(UnconfinedTestDispatcher())
    }

    @After
    fun teardown() {
        Dispatchers.resetMain()
    }

    @Test
    fun `test search view model`() = runTest {
        val collectJob = launch { SUT.searchScreenState.collect() }
        assertEquals(SearchScreenUiState.None, SUT.searchScreenState.value)

        SUT.onSearch(&quot;Query&quot;)
        assertEquals(SearchScreenUiState.NothingFound, SUT.searchScreenState.value)

        collectJob.cancel()
    }
}
</code></pre>
<p>The second assertion always failed.
Am i missing something? Thanks in advance!</p>
<p><strong>UPDATED</strong>
Thanks to <a href=""https://stackoverflow.com/users/3512164/ibrahim-disouki"">Ibrahim Disouki</a></p>
<p>His solution working for me with one change</p>
<pre><code> @Test
    fun `test search view model`() = runTest {
        whenever(searchUseCase(SearchPoiUseCase.Params(&quot;Query&quot;))).thenReturn(emptyList()) // here you can create another test case when return valid data

        assertEquals(SearchScreenUiState.None, SUT.searchScreenState.value)

        val job = launch {
            SUT.searchScreenState.collect() //now it should work
        }

        SUT.onSearch(&quot;Query&quot;)
        advanceTimeBy(500) // This is required in order to bypass debounce(500)
        runCurrent() // Run any pending tasks at the current virtual time, according to the testScheduler.

        assertEquals(SearchScreenUiState.NothingFound, SUT.searchScreenState.value)

        job.cancel()
    }
</code></pre>
",https://stackoverflow.com/questions/75118478/android-viewmodel-with-stateflow-testing-issue-test-never-waits-for-next-valu,"['android', 'unit-testing', 'android-viewmodel', 'kotlin-stateflow']",427,True,2,1
react native unit test: received value must be an HTMLElement or an SVGElement,"<p>I am new to react native (expo) and to unit testing. I have been trying to test the style of a custom text component but many of the jest matchers aren't working.</p>
<p>This is the custom text component:</p>
<pre class=""lang-js prettyprint-override""><code>import { styled } from 'nativewind';
import React from 'react';
import type { TextProps } from 'react-native';
import { StyleSheet, Text as NNText } from 'react-native';

const SText = styled(NNText);

export interface CustomTextProps extends TextProps {
  variant?: keyof typeof textVariants;
  className?: string;
}

export const textVariants = {
//.....
};

export const Text = ({
  variant = 'md',
  className = '',
  style,
  children,
  ...props
}: CustomTextProps) =&gt; {
  return (
    &lt;SText
      className={`
      ${textVariants[variant]}
      ${className}
    `}
      style={StyleSheet.flatten([
        { writingDirection: isRTL ? 'rtl' : 'ltr' },
        style,
      ])}
      {...props}
    &gt;
      {children}
    &lt;/SText&gt;
  );
};
</code></pre>
<p>And this is the testing code:</p>
<pre class=""lang-js prettyprint-override""><code>import '@testing-library/jest-native/extend-expect';
import { render, screen } from '@testing-library/react-native';

import { CustomTextProps, Text } from '../text';

describe('text component', () =&gt; {
  const renderComponent = (props: CustomTextProps) =&gt;
    render(&lt;Text {...props} /&gt;);

  it('should accept variant and className props', async () =&gt; {
    renderComponent({
      variant: 'xs',
      className: 'bg-primary-50',
      children: 'tested text',
    });

    const text = screen.getByText('tested text');
    expect(text).toBeTruthy();

    expect(text).toHaveStyle({ fontSize: 16 }); //error is here
  });
});
</code></pre>
<p>This is the error I'm getting</p>
<pre><code>expect(received).toHaveStyle()

received value must be an HTMLElement or an SVGElement.
Received has type:  object
Received has value: {&quot;_fiber&quot;: {&quot;_debugHookTypes&quot;: null, &quot;_debugNeedsRemount&quot;: false, &quot;_debugOwner&quot;: [FiberNode], &quot;_debugSource&quot;: null, &quot;actualDuration&quot;: 0, &quot;actualStartTime&quot;: -1, &quot;alternate&quot;: null, &quot;child&quot;: [FiberNode], &quot;childLanes&quot;: 0, &quot;deletions&quot;: null, &quot;dependencies&quot;: null, &quot;elementType&quot;: [Function Component], &quot;flags&quot;: 1, &quot;index&quot;: 0, &quot;key&quot;: null, &quot;lanes&quot;: 0, &quot;memoizedProps&quot;: [Object], &quot;memoizedState&quot;: null, &quot;mode&quot;: 0, &quot;pendingProps&quot;: [Object], &quot;ref&quot;: null, &quot;return&quot;: [FiberNode], &quot;selfBaseDuration&quot;: 0, &quot;sibling&quot;: null, &quot;stateNode&quot;: [Component], &quot;subtreeFlags&quot;: 0, &quot;tag&quot;: 1, &quot;treeBaseDuration&quot;: 0, &quot;type&quot;: [Function Component], &quot;updateQueue&quot;: [Object]}}

  18 |     expect(text).toBeTruthy();
  19 |
&gt; 20 |     expect(text).toHaveStyle({ fontSize: 16 });
     |                  ^
  21 |   });
  22 | });
  23 |

  at __EXTERNAL_MATCHER_TRAP__ (node_modules/expect/build/index.js:342:30)
  at Object.toHaveStyle (node_modules/expect/build/index.js:343:15)
  at Object.&lt;anonymous&gt; (src/ui/core/__test__/text.test.tsx:20:18)
  at asyncGeneratorStep (node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
  at _next (node_modules/@babel/runtime/helpers/asyncToGenerator.js:22:9)
  at node_modules/@babel/runtime/helpers/asyncToGenerator.js:27:7
  at tryCallTwo (node_modules/promise/lib/core.js:45:5)
  at doResolve (node_modules/promise/lib/core.js:200:13)
  at new Promise (node_modules/promise/lib/core.js:66:3)
</code></pre>
<p>I have tried to work with jest native and avoid dom matchers but even those don't work.</p>
",https://stackoverflow.com/questions/75458834/react-native-unit-test-received-value-must-be-an-htmlelement-or-an-svgelement,"['react-native', 'testing-library', 'jest-expo']",160,False,1,0
Golang create a mock database with handler and call to database using interfaces,"<p>I am trying to implement unit testing on my SignUp Handler and a call to database. However, it throws panic error on the database call in my SignUp Handler. It is a simple SignUp Handler that receives a JSON with username, password, and email. I will then use a SELECT statement to check if this username is duplicated inside the SignUp handler itself.</p>
<p>This all works when I am sending my post request to this handler. However, when I am actually doing unit testing, it doesn't work and threw me the 2 error messages. I feel that this is because the database wasn't initialized in the test environment but I am not sure how do do this without using third party frameworks to conduct a mock database.</p>
<p><strong>error message</strong></p>
<pre><code>panic: runtime error: invalid memory address or nil pointer dereference [recovered]
        panic: runtime error: invalid memory address or nil pointer dereference
</code></pre>
<p><strong>signup.go</strong></p>
<pre class=""lang-golang prettyprint-override""><code>package handler

type SignUpJson struct {
    Username string `json:&quot;username&quot;`
    Password string `json:&quot;password&quot;`
    Email    string `json:&quot;email&quot;`
}

func SignUp(w http.ResponseWriter, r *http.Request) {
    // Set Headers
    w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
    var newUser auth_management.SignUpJson

    // Reading the request body and UnMarshal the body to the LoginJson struct
    bs, _ := io.ReadAll(req.Body)
    if err := json.Unmarshal(bs, &amp;newUser); err != nil {
        utils.ResponseJson(w, http.StatusInternalServerError, &quot;Internal Server Error&quot;)
        log.Println(&quot;Internal Server Error in UnMarshal JSON body in SignUp route:&quot;, err)
        return
    }

    ctx := context.Background()
    ctx, cancel = context.WithTimeout(ctx, time.Minute * 2)
    defer cancel()

    // Check if username already exists in database (duplicates not allowed)
    isExistingUsername := database.GetUsername(ctx, newUser.Username) // throws panic error here when testing
    if isExistingUsername {
        utils.ResponseJson(w, http.StatusBadRequest, &quot;Username has already been taken. Please try again.&quot;)
        return
    }

    // other code logic...
}
</code></pre>
<p><strong>sqlquery.go</strong></p>
<pre class=""lang-golang prettyprint-override""><code>package database

var SQL_SELECT_FROM_USERS = &quot;SELECT %s FROM users WHERE %s = $1;&quot;

func GetUsername(ctx context.Context, username string) bool {
    row := conn.QueryRow(ctx, fmt.Sprintf(SQL_SELECT_FROM_USERS, &quot;username&quot;, &quot;username&quot;), username)
    return row.Scan() != pgx.ErrNoRows
}
</code></pre>
<p><strong>SignUp_test.go</strong></p>
<pre class=""lang-golang prettyprint-override""><code>package handler

func Test_SignUp(t *testing.T) {

    var tests = []struct {
        name               string
        postedData         SignUpJson
        expectedStatusCode int
    }{
        {
            name: &quot;valid login&quot;,
            postedData: SignUpJson{
                Username: &quot;testusername&quot;,
                Password: &quot;testpassword&quot;,
                Email:    &quot;test@email.com&quot;,
            },
            expectedStatusCode: 200,
        },
    }

    for _, e := range tests {
        jsonStr, err := json.Marshal(e.postedData)
        if err != nil {
            t.Fatal(err)
        }

        // Setting a request for testing
        req, _ := http.NewRequest(http.MethodPost, &quot;/signup&quot;, strings.NewReader(string(jsonStr)))
        req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)

        // Setting and recording the response
        res := httptest.NewRecorder()
        handler := http.HandlerFunc(SignUp)

        handler.ServeHTTP(res, req)

        if res.Code != e.expectedStatusCode {
            t.Errorf(&quot;%s: returned wrong status code; expected %d but got %d&quot;, e.name, e.expectedStatusCode, res.Code)
        }
    }
}
</code></pre>
<p><strong>setup_test.go</strong></p>
<pre class=""lang-golang prettyprint-override""><code>func TestMain(m *testing.M) {

    os.Exit(m.Run())
}

</code></pre>
<p>I have seen a similar question here but not sure if that is the right approach as there was no response and the answer was confusing: <a href=""https://stackoverflow.com/questions/73639698/how-to-write-an-unit-test-for-a-handler-that-invokes-a-function-that-interacts-w"">How to write an unit test for a handler that invokes a function that interacts with db in Golang using pgx driver?</a></p>
",https://stackoverflow.com/questions/75798345/golang-create-a-mock-database-with-handler-and-call-to-database-using-interfaces,"['unit-testing', 'go']",382,True,2,1
Test events were not received&quot; when run tests using Intellij,"<p>Learning Unit testing on android, my tests are not running now, says &quot;Test events were not received, not much details on the stack trace I tried adding and removing some dependencies but did not worked. looked into some other stackoverflow results still not working, I am doing this by following a udemy course on TDD.</p>
<p>Here is one of my test classes</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import petros.efthymiou.groovy.utils.BaseUnitTest
import petros.efthymiou.groovy.utils.getValueForTest


class PlayListViewModelShould:BaseUnitTest() {


    private val repository: PlayListRepository = mock()
    private val playList = mock&lt;List&lt;PlayList&gt;&gt;()
    private val expected = Result.success(playList)
    private val exception = java.lang.RuntimeException(""SOMETHING NOT RIGHT"")


    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    suspend fun getPlaylistsFromRepository()= runTest{
        val viewModel = mockSuccesfulCase()

        viewModel.playlists.getValueForTest()

        verify(repository,times(1)).getPlaylists()
    }
    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun emitPlaylistsFromRepository()= runTest {

        val viewModel = mockSuccesfulCase()
        assertEquals(expected, viewModel.playlists.getValueForTest())

    }
    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun emitErrorWhenRecieveError() {
        runTest {
            whenever(repository.getPlaylists()).thenReturn(
                flow {
                    emit(Result.failure&lt;List&lt;PlayList&gt;&gt;(exception))
                }
            )
        }
        val viewModel = PlayListViewModel(repository)
        assertEquals(java.lang.RuntimeException(""another error""), viewModel.playlists.getValueForTest()!!.exceptionOrNull())
    }


    private fun mockSuccesfulCase(): PlayListViewModel {
        runBlocking {
            whenever(repository.getPlaylists()).thenReturn(
                flow {
                    emit(expected)
                }
            )
        }

        return PlayListViewModel(repository)
    }

}</code></pre>
</div>
</div>
</p>
<p>My gradle</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>android {
    compileSdkVersion 30

    defaultConfig {
        applicationId ""petros.efthymiou.groovy""
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName ""1.0""

        testInstrumentationRunner ""androidx.test.runner.AndroidJUnitRunner""
    }
    testOptions {
        execution 'ANDROIDX_TEST_ORCHESTRATOR'

        unitTests.all {
            useJUnitPlatform()
        }
    }



    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
        freeCompilerArgs = freeCompilerArgs + ""-Xallow-result-return-type""
    }

    testOptions {
        animationsDisabled = true
    }
    buildFeatures {
        viewBinding true
    }
}

dependencies {

    implementation ""org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version""
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.0-alpha04'
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.2.1'
    implementation 'com.jakewharton.espresso:okhttp3-idling-resource:1.0.0'


//    testImplementation 'com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0'
    testImplementation 'org.mockito:mockito-inline:2.21.0'
    testImplementation 'androidx.arch.core:core-testing:2.1.0'
    testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.8'
    testRuntimeOnly(""org.junit.jupiter:junit-jupiter-engine:5.9.1"")
    testImplementation 'org.mockito.kotlin:mockito-kotlin:4.0.0'
    testImplementation ""org.mockito:mockito-core:4.3.1""
    androidTestImplementation ""org.mockito:mockito-android:3.10.0""
    testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.9.1'
    testImplementation 'org.junit.vintage:junit-vintage-engine:5.9.1'


    androidTestImplementation 'com.jakewharton.espresso:okhttp3-idling-resource:1.0.0'
    androidTestImplementation 'androidx.test:runner:1.5.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
    androidTestImplementation ""org.mockito:mockito-core:4.3.1""

    androidTestImplementation 'junit:junit:4.13.2'
    androidTestImplementation ""org.robolectric:robolectric:4.3.1""
    androidTestImplementation('com.schibsted.spain:barista:3.6.0') {
        exclude group: 'org.jetbrains.kotlin' // Only if you already use Kotlin in your project
    }
}</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/75212062/test-events-were-not-received-when-run-tests-using-intellij,"['android', 'kotlin', 'unit-testing', 'junit']",306,False,0,0
Testing with store.dispatch(action) doesn&#39;t work with redux-toolkit,"<p>Redux toolkit, redux-mock-store, redux-thunk</p>
<p>I'm struggling to understand the reason why my <code>store.dispatch(action)</code> doesn't work whereas <code>userSlice.reducer</code> seems to be working in the context of unit testing.</p>
<p>I did read this <a href=""https://stackoverflow.com/questions/72677850/weird-error-testing-a-reducer-redux-toolkit"">Weird error testing a reducer (redux toolkit)</a> but it didn't help to resolve the issue.</p>
<p>user.tsx</p>
<pre><code>import { createAsyncThunk, createSlice } from &quot;@reduxjs/toolkit&quot;;
import { refreshAccessToken } from &quot;../../api/auth&quot;;
import { getUserData, patchUserData } from &quot;../../api/user&quot;;
import { UserDataResponse } from &quot;../../types/user&quot;;
import { RootState } from &quot;../store&quot;;
import { logoutUserReducer } from &quot;./auth&quot;;
export interface User {
  email?: string;
  name?: string;
  password?: string;
}

export interface InitialStateUser {
  user: User | null;
  userIsLoading: boolean;
  userIsLoaded?: boolean;
}

const initialState: InitialStateUser = {
  user: null,
  userIsLoading: false,
};

export const getUserDataReducer = createAsyncThunk(
  &quot;getUserData&quot;,
  async (_, { rejectWithValue }) =&gt; {
    // some async code with FETCH API and getUserData()
    }
  }
);

export const userSlice = createSlice({
  name: &quot;user&quot;,
  initialState,
  reducers: {},
  extraReducers: (builder) =&gt; {
    builder
      .addCase(getUserDataReducer.fulfilled, (state, action) =&gt; {
        state.user = action.payload.user;
        state.userIsLoading = false;
        state.userIsLoaded = true;
      })
      .addCase(getUserDataReducer.pending, (state) =&gt; {
        state.userIsLoading = true;
        state.userIsLoaded = false;
      })
      .addCase(getUserDataReducer.rejected, (state, action) =&gt; {
        state.userIsLoading = false;
        state.userIsLoaded = false;
      })
  },
});

export default userSlice.reducer;
</code></pre>
<p>user.test.tsx</p>
<pre><code>import { AppDispatch, RootState } from &quot;../store&quot;;
import configureMockStore, { MockStoreEnhanced } from &quot;redux-mock-store&quot;;
import thunk from &quot;redux-thunk&quot;;
import { initialIngredientsState } from &quot;./ingredients.test&quot;;
import { initialOrderState } from &quot;./order.test&quot;;
import userReducer, {
  getUserDataReducer,
  InitialStateUser,
  userSlice,
} from &quot;../slices/user&quot;;
import fetchMock from &quot;fetch-mock&quot;;
import { BASE_URL } from &quot;../../api&quot;;
import { getCookie } from &quot;../../utils/cookieHandler&quot;;

const initialUserState: InitialStateUser = {
  user: null,
  userIsLoading: false,
};

const mockStoreInitialState = {
  user: { ...initialUserState }
};

describe(&quot;user reducer&quot;, () =&gt; {
  let store: MockStoreEnhanced&lt;RootState&gt;;
  beforeEach(() =&gt; {
    store = mockStore(mockStoreInitialState);
  });
  afterEach(() =&gt; {
    fetchMock.restore();
  });
  // WORKS
  it(&quot;should getUserData fullfilled&quot;, () =&gt; {
    const newState = userSlice.reducer(initialUserState, {
      type: &quot;getUserData/fulfilled&quot;,
      payload: {
        user: { email: &quot;test@gmail.com&quot;, name: &quot;testU2dfd&quot; },
      },
    });

    expect(newState.user).toEqual({
      email: &quot;test@gmail.com&quot;,
      name: &quot;testU2dfd&quot;,
    });
    expect(newState.userIsLoaded).toBe(true);
  });
  // DOESN't WORK
  it(&quot;should getUserData pending&quot;, async () =&gt; {
    await store.dispatch(getUserDataReducer.pending(&quot;&quot;));
    const { userIsLoaded, userIsLoading } = store.getState().user;
    console.log(store.getState());
    expect(userIsLoaded).toBe(false);
    expect(userIsLoading).toBe(true);
  });
});

</code></pre>
<p>The redux state is simply not updated for the <code>await store.dispatch(getUserDataReducer.pending(&quot;&quot;));</code>.</p>
<pre><code>● user reducer › should getUserData pending

    expect(received).toBe(expected) // Object.is equality

    Expected: false
    Received: undefined
</code></pre>
<p>Am I missing something here or misunderstood smth?</p>
",https://stackoverflow.com/questions/75538543/testing-with-store-dispatchaction-doesnt-work-with-redux-toolkit,"['unit-testing', 'redux', 'redux-toolkit', 'redux-mock-store']",41,False,0,1
How to mock custom wrapper object in Service layer of SpringBoot,"<p>I want to unit test my service layer code using junit and mockito.Now in my service layer method instead of returning directly dao layer response,I am returning a wrapper response in following way</p>
<pre><code>public MyResponseClass fetchMyEntityRecords(){

  List&lt;MyEntity&gt; myEntities = myDao.findAll();
  List&lt;MyDto&gt; myDtoList = new ArrayList&lt;MyDto&gt;();
  MyResponseClass obj = new MyResponseClass();
  if(myEntities!=null &amp;&amp; !myEntities.isEmpty()){
     obj.setStatus(&quot;Success&quot;)
     obj.setMessage(&quot;Data Found&quot;);
     for(MyEntity myEntity : myEntities){
        MyDto myDto = new MyDto();
        BeanUtils.copyProperties(myEntity,myDto);
        myDtoList.add(myDto);
      }
      obj.setData(myDtoList)
   }else{
      obj.setStatus(&quot;Failure&quot;)
      obj.setMessage(&quot;Data Not Found&quot;);
      obj.setData(Collections.emptyList());
   }
      return obj;
 }
</code></pre>
<p>Now in Unit testing time</p>
<pre><code>@Mock
private MyDao myDao;

@InjectMocks
private MyService myService;

@Test
void listOfMyEntityTest() {
    MyEntity myEntity1= new MyEntity();
    //setter method's invoked for setting value to enity1 object
     MyEntity myEntity2= new MyEntity();
    //setter method's invoked for setting value to enity2 object
    when(myDao.findAll()).thenReturn(List.of(enity1,enity2));
    var response = myService.fetchMyEntityRecords();
    Assertions.assertThat(response.getData().size()&gt;0).isTrue();
}
</code></pre>
<p>I am getting following error</p>
<pre><code>Expecting value to be true but was false 
org.opentest4j.AssertionFailedError: 
Expecting value to be true but was false
</code></pre>
<p>Now the response is actually MyResponseClass.Now my unit test is failing because i am unable to mock this MyResponseClass. How to achieve it?</p>
",https://stackoverflow.com/questions/75086534/how-to-mock-custom-wrapper-object-in-service-layer-of-springboot,"['spring-boot', 'junit', 'mockito']",61,False,0,0
Can you run unit tests with Quarkus without starting all dependencies?,"<p>New to Quarkus and tried unit testing and it seems to take too long starting all the dependencies.
Previous projects used PowerMockRunner so it tested just the class i was working with, but preferably wanted to just use Quarkus dependencies/options and not introduce new one. How can i make it run faster or make it run just the class...cause is a unit test.</p>
<pre><code>@QuarkusTest
public class ExampleTest {

@InjectMock
private Dependency dep;

@Inject
private MyCLass underTest;

@Test
public void testStuff() {
    underTest.doStuff();
    Mockito.verify(dep, Mockito.times(1)).doMoreStuff(Mockito.any());
}
}
</code></pre>
",https://stackoverflow.com/questions/75898850/can-you-run-unit-tests-with-quarkus-without-starting-all-dependencies,"['java', 'unit-testing', 'quarkus']",63,False,0,0
how to unit test Aspect annotation,"<p>I have defined an Aspect and it will be used when the method is annotated. Please see the sample code below</p>
<pre><code>@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PredefinedCheck {

}

@Aspect
@Component
public class PredefinedAspect {
    
    @Before(&quot;@annotation(PredefinedCheck)&quot;)
    @SneakyThrows
    public void check(JoinPoint joinPoint) {

        ......
        log.debug(&quot;hello!!&quot;);
    }
}

@Service
public class ActionService {
     
     @PredefinedCheck
     public MyEntity updateMyEntity(AuthenticationJwtToken authToken, EntityUpdateRequest request) {
          ......
     }
}
</code></pre>
<p>Now, the question is how can I unit test my PredefinedAspect code? I thought unit testing the <code>updateMyEntity</code> method will trigger it, but it didn't (I debugged and it not hit the break point. Also, the sonarqube doesn't shows the code being covered). Please advise.</p>
",https://stackoverflow.com/questions/75216580/how-to-unit-test-aspect-annotation,"['java', 'spring', 'unit-testing', 'junit', 'spring-aop']",331,True,0,1
"TypeError: (0 , _rulesUnitTesting.clearFirestoreData) is not a function","<p>i'm trying to follow this <a href=""https://eliteionic.com/tutorials/using-tdd-to-test-deploy-firestore-security-rules/"" rel=""nofollow noreferrer"">setup tutorial</a> of Firebase rules unit testing as much as I can but i'm getting errors. Its the setup for Angular and i'm using React so its not far-fetched that i missed something.</p>
<p>Here is my code:</p>
<pre><code>import {
  assertFails,
  assertSucceeds,
  initializeAdminApp,
  initializeTestApp,
  apps,
  clearFirestoreData,
} from &quot;@firebase/rules-unit-testing&quot;;

const PROJECT_ID = &quot;My_Project&quot;;

const getFirestore = () =&gt;
  initializeTestApp({ projectId: PROJECT_ID }).firestore();
const getAdminFirestore = () =&gt;
  initializeAdminApp({ projectId: PROJECT_ID }).firestore();

describe(&quot;Our social app&quot;, () =&gt; {
  it(&quot;Understand basic addition&quot;, () =&gt; {
    expect(2 + 2).toEqual(4);
  });

  describe(&quot;Firestore security rules&quot;, () =&gt; {
    beforeEach(async () =&gt; {
      await clearFirestoreData({ projectId: PROJECT_ID });
    });
    it(&quot;can not read from the messages collection&quot;, async () =&gt; {
      const db = getFirestore();
      const testDoc = db.collection(&quot;messages&quot;).doc(&quot;testDoc&quot;);
      await assertFails(testDoc.get());
    });
    afterAll(async () =&gt; {
      const cleanUpApps = apps().map((app) =&gt; app.delete());
      await Promise.all(cleanUpApps);
    });
  });
});
</code></pre>
<p>But i get the error:</p>
<pre><code>TypeError: (0 , _rulesUnitTesting.clearFirestoreData) is not a function
</code></pre>
<p>or i get this one:</p>
<pre><code>TypeError: (0 , _rulesUnitTesting.initializeTestApp) is not a function

      11 |
      12 | const getFirestore = () =&gt;
    &gt; 13 |   initializeTestApp({ projectId: PROJECT_ID }).firestore();
         |                    ^
      14 | const getAdminFirestore = () =&gt;
      15 |   initializeAdminApp({ projectId: PROJECT_ID }).firestore();
</code></pre>
<p>when i comment out the <code>beforeEach</code> paragraph of code.</p>
<pre><code>&quot;@firebase/rules-unit-testing&quot;: &quot;^2.0.7&quot;,
</code></pre>
<p>What is producing these 2 errors?</p>
",https://stackoverflow.com/questions/76036488/typeerror-0-rulesunittesting-clearfirestoredata-is-not-a-function,"['node.js', 'firebase', 'google-cloud-firestore', 'jestjs', 'firebase-security']",33,False,0,0
Supertest port Already in use even after setting setting Jest to &quot;runInBand&quot;,"<p>I am new to unit testing. So, I am writing a node application and having issues testing the route.</p>
<p>I am using Supertest and Jest and I have tried all answers I can find.</p>
<p>I keep getting the error</p>
<pre><code>code: 'EADDRINUSE',
  errno: -4091,
  syscall: 'listen',
  address: '::',
  port: 5000
</code></pre>
<p>Here is my <strong>package.json</strong></p>
<pre><code>&quot;test&quot;: &quot;jest --verbose --watchAll --runInBand --detectOpenHandles --forceExit --coverage&quot; 
</code></pre>
<p>I have also tried maxWorkers=1
`</p>
<p>Here is my <strong>index.js</strong></p>
<pre><code>app.use(&quot;/api/v1&quot;, clinicRoutes);

let PORT;

process.env.STATUS === &quot;production&quot;
  ? (PORT = process.env.PROD_PORT)
  : (PORT = process.env.DEV_PORT);

app.listen(PORT, () =&gt; {
  logger.info(
    `app is running in ${process.env.STATUS} mode, listening on port ${PORT}`
  );
});
</code></pre>
<p>Here is my <strong>index.test.js</strong></p>
<pre><code>const request = require(&quot;supertest&quot;);
const app = require(&quot;../index&quot;);


describe(&quot;Test the clinic search API&quot;, () =&gt; {
  test(&quot;It should respond with a list of clinics&quot;, async () =&gt; {
    const response = await request(app)
      .post(&quot;/api/v1/search&quot;)
      .send({
        name: &quot;Scratch&quot;,
        state: &quot;California&quot;,
        availableFrom: &quot;01:00&quot;,
        availableTo: &quot;23:00&quot;,
      })
      .set(&quot;Accept&quot;, &quot;application/json&quot;);

    expect(response.statusCode).toBe(200);
    expect(response.body).toHaveProperty(&quot;data&quot;);
    expect(Array.isArray(response.body.data)).toBe(true);
    expect(response.body.data[0]).toHaveProperty(&quot;name&quot;);
    expect(response.body.data[0]).toHaveProperty(&quot;state&quot;);
    expect(response.body.data[0]).toHaveProperty(&quot;availability&quot;);
    expect(response.body.data[0].availability).toHaveProperty(&quot;from&quot;);
    expect(response.body.data[0].availability).toHaveProperty(&quot;to&quot;);
  });
});
</code></pre>
<p>Can anyone tell me how I can fix this?</p>
",https://stackoverflow.com/questions/75789805/supertest-port-already-in-use-even-after-setting-setting-jest-to-runinband,"['node.js', 'express', 'unit-testing', 'jestjs', 'supertest']",84,False,0,0
Setup service provider on unit testing,"<p>I have a component the following:</p>
<p><strong>TS</strong></p>
<pre><code>export class CashFlowSalariesComponent implements OnInit, OnChanges {

...

constructor(
    public apiService: ApiService,
    private modalService: NgbModal,
    private toastr: ToastrService
  ) {}

  ngOnInit() {

  }
}
</code></pre>
<p>Now I want to create a unit testing for it so I try</p>
<p><strong>.spec.ts</strong></p>
<pre><code>describe('CashFlowSalariesComponent', () =&gt; {
    let component: CashFlowSalariesComponent;
    let fixture: ComponentFixture&lt;CashFlowSalariesComponent&gt;;
    let apiService: ApiService;


  
    beforeEach(async(() =&gt; {
      TestBed.configureTestingModule({
        schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
        imports: [
                            [RouterModule.forRoot([])],
                            RouterTestingModule,
                            FormsModule,
                            ReactiveFormsModule,
                            BrowserModule,
                            HttpClientTestingModule,
                        ],
        declarations: [ 
            CashFlowSalariesComponent,
        ],
        providers: [{provide: apiService}]

      })
      .compileComponents();
    }));
  
    beforeEach(() =&gt; {
      fixture = TestBed.createComponent(CashFlowSalariesComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    });
  
    it('should create', () =&gt; {
      expect(component).toBeTruthy();
    });
</code></pre>
<p>But this is throwing an error message:</p>
<blockquote>
<p>NullInjectorError:
StaticInjectorError(DynamicTestModule)[CashFlowSalariesComponent -&gt;
ApiService]:    StaticInjectorError(Platform:
core)[CashFlowSalariesComponent -&gt; ApiService]:
NullInjectorError: No provider for ApiService!</p>
</blockquote>
<p>As you can see, I tried to set the ApiService as a provider, but it did not work; what am I doing wrong?</p>
",https://stackoverflow.com/questions/75162774/setup-service-provider-on-unit-testing,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",38,True,0,2
Cobertura page is empty/unknown after deploying to Gitlab&#39;s pages,"<p>To run the test locally, I use this:</p>
<pre><code>&quot;test-ci&quot;: &quot;jest --runInBand webapp/test/ivw --config ./jest.config.js --watchAll=false&quot;,
</code></pre>
<p>In the terminal, I have the coverage report fine, and this also generates de Cobertura page:</p>
<p><a href=""https://i.stack.imgur.com/Hpmxb.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Hpmxb.png"" alt=""enter image description here"" /></a></p>
<p>I have 2 stages in my pipeline, one for the unit testing and another one to publish this coverage page:</p>
<pre><code>unit:
  script:
    - npm run test-ci
  coverage: /All files[^|]*\|[^|]*\s+([\d\.]+)/
  cache:
    paths:
      - coverage/
  artifacts:
    paths:
      - coverage/
    when: always
    reports:
      junit:
        - junit.xml
      coverage_report:
        coverage_format: cobertura
        path: coverage/cobertura-coverage.xml

    pages:
      stage: coverage
      dependencies:
        - unit
      script:
        - mv coverage/ public/
      artifacts:
        paths:
          - public/
</code></pre>
<p>This is taken from here:</p>
<p><a href=""https://gist.github.com/rishitells/3c4536131819cff4eba2c8ab5bbb4570"" rel=""nofollow noreferrer"">https://gist.github.com/rishitells/3c4536131819cff4eba2c8ab5bbb4570</a></p>
<p>The thing is that it publishes the page but this has an unknown coverage:</p>
<p><a href=""https://i.stack.imgur.com/jLcne.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/jLcne.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/75832963/cobertura-page-is-empty-unknown-after-deploying-to-gitlabs-pages,"['jestjs', 'gitlab-ci', 'gitlab-pages', 'jest-junit']",37,False,0,1
sqlmock &quot;expecting database transaction Begin&quot;,"<p>I am trying to do unit testing with sqlmock. I have the mock.ExpectBegin() and the mock.ExpectCommit(), but I keep getting this error:</p>
<pre><code>there is a remaining expectation which was not matched: ExpectedBegin =&gt; expecting database transaction Begin
</code></pre>
<p>I'm not sure what to do to fix this. Any idea?</p>
<p>I've tried moving the begin command to different parts in the code and I've tried different ending mocks (i.e. expectRollback or expectClose) to no avail.</p>
<p>I'm just expecting the unit test to pass</p>
",https://stackoverflow.com/questions/75890014/sqlmock-expecting-database-transaction-begin,"['gomock', 'go-sqlmock']",35,False,0,0
No unit-test result in Power Query M,"<p>I am trying to write a custom connector for Power BI, in Visual Studio Code, using power query M, and I am trying to write some unit-test for it.</p>
<p>Following the example here: <a href=""https://learn.microsoft.com/en-us/power-query/handling-unit-testing"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/power-query/handling-unit-testing</a></p>
<pre><code>shared MyExtension.UnitTest =
[
    TestAccessToken = &quot;nkls8CDwDZZGmjFFDrPFI64X&quot;,
    TestStartTime = &quot;2020-09-13T00:00:00Z&quot;,
    TestEndTime = &quot;2023-06-13T00:00:00Z&quot;,
    TestEndpoint = &quot;Events&quot;,
    result = API.GetRecords(TestEndpoint, TestStartTime,TestEndTime),
    facts =
    {
        Fact(&quot;Check that we have three entries in our nav table&quot;, 3, Table.RowCount(result))
    },
    report = Facts.Summarize(facts)
][report];
</code></pre>
<p>However when I run this in Visual Studio Code, I get the following results:</p>
<pre><code>[12:37:57 PM]   [Info]  RunTestBattery result [
    {
        &quot;ActivityId&quot;: &quot;042c992f-409e-49ff-9e7a-fe70477fad69&quot;,
        &quot;DataSourceAnalysis&quot;: [
            ...
        ],
        &quot;Details&quot;: &quot;MyExtension.UnitTest&quot;,
        &quot;EndTime&quot;: &quot;2023-05-05T19:37:57.4942915+00:00&quot;,
        &quot;Method&quot;: &quot;MyExtension.UnitTest&quot;,
        &quot;Name&quot;: &quot;API.query.pq&quot;,
        &quot;StartTime&quot;: &quot;2023-05-05T19:37:55.0417748+00:00&quot;,
        &quot;Output&quot;: [
            {
                &quot;Result&quot;: null,
                &quot;Notes&quot;: null,
                &quot;Details&quot;: null
            },
            {
                &quot;Result&quot;: null,
                &quot;Notes&quot;: null,
                &quot;Details&quot;: null
            }
        ],
        &quot;RowCount&quot;: 2,
        &quot;Status&quot;: &quot;Passed&quot;,
        &quot;Type&quot;: &quot;PQTest.RunTest&quot;
    }
]
</code></pre>
<p>How come there is no test results?</p>
",https://stackoverflow.com/questions/76185565/no-unit-test-result-in-power-query-m,"['powerbi', 'powerquery', 'm']",23,False,0,0
How to write unit test for BigQuery Java code,"<p>Can you help me write the Java unit test cases for increasing the coverage for the below Java code which retrieves the data from the BigQuery using the given query ?</p>
<pre class=""lang-java prettyprint-override""><code>BigQuery bigQueryInst =
                BigQueryOptions.newBuilder().setProjectId(projectId).setCredentials(googleCred.generateCred()).build()
                        .getService();

       
        String queryResp  = /* Query to be executed */;
     
        QueryJobConfiguration queryJobConfiguration =                     QueryJobConfiguration.newBuilder(carbonAgriRawDataRespQuery)
                .addPositionalParameter(QueryParameterValue.string(nodeID)).build();
      
        Job queryJob = bigQueryInst.create(JobInfo.newBuilder(queryJobConfiguration).build());
        queryJob = queryJob.waitFor();

        if (queryJob == null) {
            throw new Exception(&quot;Job no longer exists for Carbon Agriculture Raw Data&quot;);
        }

        if (queryJob.getStatus().getError() != null) {
            throw new Exception(queryJob.getStatus().getError().toString());
        }

        TableResult result = queryJob.getQueryResults();

        for (FieldValueList row : result.iterateAll()) {

        }
</code></pre>
<p>I tried to mock the BigQuery instance, Job configuration instance, and Job instance using the key.json. But it resulted in a null pointer exception.</p>
<p>I am expecting a way to do the Unit Testing coverage for the mentioned Java code.</p>
",https://stackoverflow.com/questions/75070416/how-to-write-unit-test-for-bigquery-java-code,"['java', 'google-cloud-platform', 'google-bigquery', 'spring-test', 'test-coverage']",263,False,2,0
Azure DevOps Services REST API 5.1 - get unit testing (VSTest) and sonarqued,"<p>I'm creating a script in ISE powershell to get information from the projects in azure devops. Some apis that I already use in my script are the following:</p>
<ol>
<li>ApiUri = &quot;$projectUri/_apis/tfvc/branches?$apiVersion&quot;</li>
<li>ApiUri =
&quot;$projectUri/_apis/distributedtask/deploymentgroups?$apiVersion-preview&quot;</li>
<li>ApiUri = &quot;$projectUri/_apis/pipelines?$apiVersion-preview&quot;</li>
<li>ApiUri = &quot;$projectUri/_apis/git/repositories?$apiVersion&quot;</li>
<li>ApiReleasePipelinesUri =
&quot;$projectUri/_apis/release/definitions?$apiVersion&quot;</li>
</ol>
<p>An example of what I'm getting with the above apis is:</p>
<p><a href=""https://i.stack.imgur.com/ZXsQU.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ZXsQU.jpg"" alt=""enter image description here"" /></a></p>
<p>In the value, if it is 1 or more, the information of that process goes.</p>
<p><strong>Now I want to extract the information about the unit testing (Visual studio test) and sonarqued.</strong></p>
<p>I would like to have something like this for the case of sonarqued and unittesting. 0 if there was never such an implementation and 1 if unit testing and sonarqued were applied.</p>
<p>I can't find something similar to what I need, if someone could guide me or know how to extract that information it would help me</p>
<p>Used this task for unit tests:
<a href=""https://i.stack.imgur.com/oTMfk.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/oTMfk.jpg"" alt=""enter image description here"" /></a></p>
<p>Used this task to sonarqued:
<a href=""https://i.stack.imgur.com/yEeex.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/yEeex.jpg"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/75137494/azure-devops-services-rest-api-5-1-get-unit-testing-vstest-and-sonarqued,"['azure-pipelines', 'azure-devops-rest-api', 'azure-api-apps']",84,True,0,1
Mocha test (in Visual Studio/ Resharper) gives different results from &#39;npm test&#39;,"<p>I want to test some JS files that are within a Visual Studio solution.</p>
<p>I've been following <a href=""https://github.com/MicrosoftDocs/visualstudio-docs/blob/main/docs/javascript/unit-testing-javascript-with-visual-studio.md"" rel=""nofollow noreferrer"">https://github.com/MicrosoftDocs/visualstudio-docs/blob/main/docs/javascript/unit-testing-javascript-with-visual-studio.md</a> .</p>
<p>I have a file in <code>/js/Layers.js</code>:</p>
<pre><code>class Layers {

    constructor() {

        this.xxxLayers = [];
    }
}
</code></pre>
<p>I have test file in <code>/test/Layers.test.js</code>:</p>
<pre><code>
require(&quot;./../js/Layers&quot;);

describe('Layers class ctor',
    function () {
        it('should have initialised arrays',
            function () {
                let sut = new Layers();
                expect(true).toBe(true);
            });
    });
</code></pre>
<p>When I run this in Visual Studio (using the Resharper test runner) it passes without raising an error.</p>
<p>My <code>package.json</code> is:</p>
<pre><code>{
  &quot;name&quot;: &quot;nodejs-web-app1&quot;,
  &quot;version&quot;: &quot;0.0.0&quot;,
  &quot;description&quot;: &quot;NodejsWebApp1&quot;,
  &quot;main&quot;: &quot;server.js&quot;,
  &quot;author&quot;: {
    &quot;name&quot;: &quot;&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;eslint&quot;: &quot;^8.21.0&quot;
  },
  &quot;eslintConfig&quot;: {},
  &quot;dependencies&quot;: {
    &quot;mocha&quot;: &quot;^10.2.0&quot;
  },
  &quot;scripts&quot;: {
    &quot;test&quot;: &quot;mocha test&quot;
  }
}

</code></pre>
<p>When I run <code> npm test</code> I see that the test is run but it does not seem to load the <code>Layers.js</code> file that I wish to test:</p>
<pre><code>$ npm test

&gt; nodejs-web-app1@0.0.0 test
&gt; mocha test



  Layers class ctor
    1) should have initialised arrays


  0 passing (3ms)
  1 failing

  1) Layers class ctor
       should have initialised arrays:
     ReferenceError: Layers is not defined
      at Context.&lt;anonymous&gt; (test\Layers.test.js:9:27)
      at process.processImmediate (node:internal/timers:471:21)


</code></pre>
<p>I wonder if Resharper's test runner is filling in a gap that I have missed . Interestingly compared to the advice in <a href=""https://github.com/MicrosoftDocs/visualstudio-docs/blob/main/docs/javascript/unit-testing-javascript-with-visual-studio.md"" rel=""nofollow noreferrer"">https://github.com/MicrosoftDocs/visualstudio-docs/blob/main/docs/javascript/unit-testing-javascript-with-visual-studio.md</a> I cannot see the tests in the VS Test Explorer. only in the Resharper one, although that feels like a different issue. What I want is to be able to run the tests from the command line so I can add it to our CI pipeline.</p>
<p>Can anyone advise?</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/75151187/mocha-test-in-visual-studio-resharper-gives-different-results-from-npm-test,"['node.js', 'visual-studio', 'mocha.js']",16,False,0,0
Mockk verify ask a function to run inside a coroutine body,"<p>I was learning about Unit Testing with Mockk library, and the function i was testing is using a verify. So i run the test with coroutine test runTest{} but verify method ask me to run inside a coroutine body</p>
<p><a href=""https://i.stack.imgur.com/6oTvF.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/6oTvF.png"" alt=""Function Error"" /></a></p>
<p>And, here is the code for function implementation :</p>
<pre><code>override suspend fun getAnimeByAnimeId(animeID: Int): AnimeEntity? {
    return localDataSource.getAnimeByAnimeId(animeID)
}
</code></pre>
<p>So, i wonder what is wrong in here, why can't i call verify here even when the function is inside a coroutine body.</p>
",https://stackoverflow.com/questions/75005448/mockk-verify-ask-a-function-to-run-inside-a-coroutine-body,"['android', 'kotlin', 'unit-testing', 'mockk']",234,True,1,1
C# Moq Find and FindAsync,"<p>I know there are a few articles on this topic, but I can't really find any helpful answers. I want to enable the Find and FindAsync methods of the Entity Framework for anonymous types. We are a larger company and the following is not my code, but maybe it will help to find a solution.</p>
<pre class=""lang-cs prettyprint-override""><code>var dataList = new List&lt;T&gt;();
var data = dataList.AsQueryable();

var mockSet = new Mock&lt;DbSet&lt;T&gt;&gt;();

mockSet.As&lt;IDbAsyncEnumerable&lt;T&gt;&gt;().Setup(m =&gt; m.GetAsyncEnumerator()).Returns(new TestDbAsyncEnumerator&lt;T&gt;(data.GetEnumerator()));
mockSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.Provider).Returns(new TestDbAsyncQueryProvider&lt;T&gt;(data.Provider));
mockSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.Expression).Returns(data.Expression);
mockSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(data.ElementType);
mockSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(data.GetEnumerator());

mockSet.Setup(d =&gt; d.Add(It.IsAny&lt;T&gt;())).Callback&lt;T&gt;((s) =&gt; dataList.Add(s));
mockSet.Setup(d =&gt; d.Remove(It.IsAny&lt;T&gt;())).Callback&lt;T&gt;((s) =&gt; dataList.Remove(s));
mockSet.Setup(d =&gt; d.RemoveRange(It.IsAny&lt;IEnumerable&lt;T&gt;&gt;())).Callback&lt;IEnumerable&lt;T&gt;&gt;(range =&gt; range.ToList().ForEach(item =&gt; dataList.Remove(item)));
mockSet.Setup(d =&gt; d.Include(It.IsAny&lt;string&gt;())).Returns(mockSet.Object);
mockSet.Setup(d =&gt; d.AsNoTracking()).Returns(mockSet.Object);
mockSet.Setup(d =&gt; d.FindAsync(It.IsAny&lt;object[]&gt;())).Returns( **** );
</code></pre>
<p>I want to use the Entity Framework methods Find and FindAsync with moq for unit-testing.</p>
",https://stackoverflow.com/questions/75298967/c-moq-find-and-findasync,"['c#', 'entity-framework', 'moq']",78,False,0,0
Unit test won&#39;t pass when trying to throw error,"<p>I am a bit new to Mocha, Chai and Unit Testing. I am trying to write a basic test to check that Authorization headers are present in the request coming through my middle ware. I have tried a few things from passing the <code>TypeError</code> to <code>throw()</code> as well as message and <code>Error</code> no luck.... any help would be greatly appreciated.</p>
<p><strong>My Middleware</strong></p>
<pre class=""lang-js prettyprint-override""><code>exports.verify = async (req, res, next) =&gt; {
      try {
        const headers = req.get('Authorization');
        let decodedToken;
    
        if (!headers) {
          const error = new Error('Not Authenticated');
          error.statusCode = 401;
          throw error;
        }
        const token = headers.split(' ')[1];
    
        try {
          decodedToken = jwt.verify(token, SECRET);
        } catch (err) {
          err.statusCode = 500;
          throw err;
        }
    
        if (!decodedToken) {
          const error = new Error('Not Authenticated');
          error.statusCode = 401;
          throw error;
        }
    
        req.userUid = decodedToken.userUid;
    
        const queryRef = await users.where('uid', '==', req.userUid).get();
    
        if (queryRef.empty) {
          const error = new Error('Not Authenticated');
          error.statusCode = 401;
          throw error;
        } 
        next();
      } catch (err) {
        log.error(err);
        next(err);
      }
    };

</code></pre>
<p><strong>My Test</strong></p>
<pre class=""lang-js prettyprint-override""><code>it('Should throw an error if no auth header provided.', function () {
  const req = {
    get: function () {
      return null;
    },
  };

  expect(function () {
    verify(req, {}, () =&gt; {});
  }).to.throw();
});
</code></pre>
<p><em>just in case</em> - <strong>Error handling at app.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>
app.use((err, req, res, next) =&gt; {
  const status = err.statusCode || 500;
  const message = err.message;
  const data = err.data || [];
  const userUid = req.userUid;
  const stack = err.stack;
  log.error(`STATUS: ${status} - MESSAGE: ${message} - STACK: ${stack}`);
  res.status(status).json(message);
});
</code></pre>
",https://stackoverflow.com/questions/75746558/unit-test-wont-pass-when-trying-to-throw-error,"['javascript', 'express', 'unit-testing', 'mocha.js', 'chai']",30,False,0,1
Unit testing does not fill the component object,"<p>I'm new in Angular, and I just implemented on an existing project the unit testing with Karma and Jasmine, so I created the spec.ts component and html as:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>describe('CashFlowSalariesComponent', () =&gt; {
      let fixture: ComponentFixture &lt; CashFlowSalariesComponent &gt; ;
      let mockCashFlowService;
      let data;

      beforeEach(async(() =&gt; {
        data = [{
          id: 1006,
          role: ""Test"",
          ...
        }]

        mockCashFlowService = jasmine.createSpyObj(['createTableData'])
        TestBed.configureTestingModule({
          schemas: [CUSTOM_ELEMENTS_SCHEMA],
          imports: [
            RouterTestingModule,
            FormsModule,
            ReactiveFormsModule,
            BrowserModule,
            HttpClientTestingModule,
            ToastrModule.forRoot({
              positionClass: 'toast-bottom-right'
            })
          ],
          declarations: [
            CashFlowSalariesComponent,
          ],
          providers: [{
              provide: ApiService,
              useValue: mockCashFlowService
            }, UserService, ProfileService, VettingStatusService, ApplicationRoleService,
            SeniorityLevelService, PlacementStatusService, EducationLevelService, UtilsService, ShirtSizeService,
            CountryService, CityService, PostalCodeService, StateService, ClientSectorService, JobService, ProfileActivityService, ProfileSalaryActivityService, ClientService, RequestTimeOffService, TimeOffTypeService, PulsecheckDetailService, PulsecheckMasterService,
            PulsecheckQuestionService, ExpenseService, DepartmentService, ExchangeRateService, SkillCategoriesService, ProfileRoleService,
            ToastrService
          ]

        })

        fixture = TestBed.createComponent(CashFlowSalariesComponent);
      }));

      it('should set salaries data correctly', () =&gt; {
        mockCashFlowService.userBelongsTo = 'operations'
        mockCashFlowService.createTableData.and.returnValue(of (data))
        debugger;
        fixture.detectChanges();
        expect(fixture.componentInstance.data.length).toBe(1);
      })</code></pre>
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;div class=""row"" *ngIf=""apiService.utilsService.userBelongsTo('operations')""&gt;
  &lt;div class=""col-12 my-2""&gt;
    &lt;div class=""shadow bg-white rounded""&gt;
      &lt;div class=""card"" *ngIf=""salariesCard""&gt;
        &lt;div class=""card-body""&gt;
          &lt;div class=""row px-4""&gt;
            &lt;div class=""col-md-6""&gt;
              &lt;h4 class=""my-card-title""&gt;Employee Salaries&lt;/h4&gt;
            &lt;/div&gt;
            &lt;div class=""col-md-6 text-right d-flex justify-content-end""&gt;
              &lt;h5 class=""card-title mr-2 my-2""&gt;{{ salariesCard.usdExpensesTotal | currency }}&lt;/h5&gt;
              &lt;csv-export-button [data]=""dataExport"" [propertyKeys]=""propertyKeysExport"" [headerNames]=""dataHeadersExport"" fileName=""Employee Salaries""&gt;
              &lt;/csv-export-button&gt;
            &lt;/div&gt;

          &lt;/div&gt;
          &lt;div class=""my-table-wrapper mt-4""&gt;

            &lt;table class=""table salaries-table""&gt;
              &lt;thead class=""""&gt;
                &lt;th scope=""col"" *ngFor=""let header of dataHeaders"" [width]=""header.width""&gt;{{header.name}}&lt;/th&gt;
              &lt;/thead&gt;
              &lt;tbody&gt;
                &lt;tr *ngFor=""let salary of data; index as i"" [class.bg-danger]=""salary.isPaymentHold""&gt;
                  &lt;td scope=""row""&gt;{{i + 1}}&lt;/td&gt;
                  &lt;td&gt;
                    &lt;span class=""badge"" [class.badge-outline-info]=""salary.role == 'Developer'"" [class.badge-outline-success]=""salary.role == 'Drafter'"" [class.badge-outline-warning]=""salary.role == 'Admin' || salary.role == 'Recruiter'""&gt;
                          {{
                            salary.role == 'Developer' ? 'Dev' :
                            salary.role == 'Drafter' ? 'Draft' :
                            salary.role.trim()
                          }}
                        &lt;/span&gt;
                  &lt;/td&gt;
                  &lt;td&gt;
                    &lt;strong class=""not-so-strong""&gt;{{ salary.name }}&lt;/strong&gt;
                  &lt;/td&gt;
                  &lt;td&gt;
                    &lt;div&gt;
                      {{ salary.client }}
                    &lt;/div&gt;
                  &lt;/td&gt;

                  &lt;td&gt;
                    &lt;input *ngIf=""selectedProfile != null &amp;&amp; selectedProfile.id == salary.id"" type=""number"" class=""form-control form-control-sm text-sm"" [(ngModel)]=""selectedProfileMXNExpense"" [disabled]=""selectedProfileExpenseCurrency == 1""&gt;
                    &lt;div *ngIf=""selectedProfile == null || selectedProfile.id != salary.id"" class=""profile-perception""&gt;
                      {{ salary.mxnAmount | currency }}
                    &lt;/div&gt;
                  &lt;/td&gt;

                  &lt;td&gt;
                    &lt;input *ngIf=""selectedProfile != null &amp;&amp; selectedProfile.id == salary.id"" type=""number"" class=""form-control form-control-sm text-sm"" [(ngModel)]=""selectedProfileUSDExpense"" [disabled]=""selectedProfileExpenseCurrency == 2""&gt;
                    &lt;div *ngIf=""selectedProfile == null || selectedProfile.id != salary.id"" class=""profile-perception""&gt;
                      {{ salary.usdAmount | currency }}
                    &lt;/div&gt;
                  &lt;/td&gt;

                  &lt;td&gt;
                    &lt;select *ngIf=""selectedProfile != null &amp;&amp; selectedProfile.id == salary.id"" type=""text"" class=""form-control form-control-sm text-sm"" [(ngModel)]=""selectedProfileExpenseCurrency"" (ngModelChange)=""setSelectedProfileCurrency()""&gt;
                      &lt;option value=""1""&gt;USD&lt;/option&gt;
                      &lt;option value=""2""&gt;MXN&lt;/option&gt;
                    &lt;/select&gt;
                    &lt;div *ngIf=""selectedProfile == null || selectedProfile.id != salary.id""&gt;
                      {{ salary.paymentCurrency }}
                    &lt;/div&gt;
                  &lt;/td&gt;

                  &lt;td&gt;
                    &lt;!-- Health Insurance Cost --&gt;
                    &lt;input *ngIf=""selectedProfile != null &amp;&amp; selectedProfile.id == salary.id"" type=""number"" class=""form-control form-control-sm text-sm"" [(ngModel)]=""selectedProfileInsuranceExpense""&gt;
                    &lt;div *ngIf=""selectedProfile == null || selectedProfile.id != salary.id"" class=""profile-expense""&gt;
                      {{ salary.mxnInsuranceCost | currency }}
                    &lt;/div&gt;
                  &lt;/td&gt;

                  &lt;td&gt;
                    &lt;!-- Net Payment --&gt;
                    &lt;div&gt;
                      {{ salary.mxnNetPayment | currency }}
                    &lt;/div&gt;
                  &lt;/td&gt;
                  &lt;td&gt;
                    &lt;!-- Enrolled in health insurance --&gt;
                    &lt;div&gt;
                      {{ salary.isEnrolledInHealthInsurance ? 'YES' : 'NO' }}
                    &lt;/div&gt;
                  &lt;/td&gt;

                  &lt;td&gt;
                    &lt;div class=""d-flex actions-container""&gt;
                      &lt;button *ngIf=""selectedProfile == null || selectedProfile.id != salary.id"" (click)=s etProfile(salary.profile) class=""btn"" ngbTooltip=""Edit""&gt;
                        &lt;i class=""mdi mdi-pencil""&gt;&lt;/i&gt;
                      &lt;/button&gt;
                      &lt;button *ngIf=""(selectedProfile == null || selectedProfile.id != salary.id) &amp;&amp; !salary.isPaymentHold"" (click)=""holdProfilePayment(profile, true)"" class=""btn"" ngbTooltip=""Hold Payment""&gt;
                        &lt;i class=""mdi mdi-pause""&gt;&lt;/i&gt;
                      &lt;/button&gt;
                      &lt;button *ngIf=""(selectedProfile == null || selectedProfile.id != salary.id) &amp;&amp; salary.isPaymentHold"" (click)=""holdProfilePayment(profile, false)"" class=""btn"" ngbTooltip=""Resume Payment""&gt;
                        &lt;i class=""mdi mdi-play""&gt;&lt;/i&gt;
                      &lt;/button&gt;
                      &lt;a *ngIf=""selectedProfile == null || selectedProfile.id != salary.id"" [href]=""'/profiles/detail/' + salary.id"" target=""_blank"" ngbTooltip=""Go to profile"" class=""btn""&gt;
                        &lt;i class=""mdi mdi-eye""&gt;&lt;/i&gt;
                      &lt;/a&gt;
                      &lt;button *ngIf=""selectedProfile != null &amp;&amp; selectedProfile.id == salary.id"" class=""btn"" (click)=""saveProfileExpense(salariesCard)"" ngbTooltip=""Save""&gt;
                        &lt;i class=""mdi mdi-check""&gt;&lt;/i&gt;
                      &lt;/button&gt;
                      &lt;button *ngIf=""selectedProfile != null &amp;&amp; selectedProfile.id == salary.id"" class=""btn"" (click)=""selectedProfile = null"" ngbTooltip=""Cancel""&gt;
                        &lt;i class=""mdi mdi-cancel""&gt;&lt;/i&gt;
                      &lt;/button&gt;
                      &lt;button *ngIf=""(selectedProfile == null || selectedProfile.id != salary.id) &amp;&amp; !salary.isPaymentHold"" (click)=""showHistory(salary.profile)"" class=""btn"" ngbTooltip=""Salary history""&gt;
                        &lt;i class=""mdi mdi-currency-usd""&gt;&lt;/i&gt;
                      &lt;/button&gt;
                    &lt;/div&gt;
                  &lt;/td&gt;
                &lt;/tr&gt;
              &lt;/tbody&gt;
            &lt;/table&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</code></pre>
</div>
</div>
</p>
<p><strong>TS:</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>@Component({
  selector: ""cash-flow-salaries"",
  templateUrl: ""./cash-flow-salaries.component.html"",
  styleUrls: [""./cash-flow-salaries.component.css""],
})
export class CashFlowSalariesComponent implements OnInit, OnChanges {
  @Input() salariesCard: SalariesCardItem;
  @Input() exchangeRate: number;
  @Input() roleNamesByProfileId: string[];
  @Input() clients: ClientModel[] = [];

  @Output() profileEdited: EventEmitter &lt; number &gt; = new EventEmitter &lt; number &gt; ();

  selectedProfile: ProfileModel = null;
  selectedProfileUSDExpense: string = """";
  selectedProfileMXNExpense: string = """";
  selectedProfileInsuranceExpense: string = """";
  selectedProfileExpenseCurrency: number = 2;
  selectedProfileClientId: number = 0;
  originalSalary: number;

  public dataHeaders = [{
      name: ""#"",
      width: ""6%""
    },
    {
      name: ""Role"",
      width: ""7%""
    },
    {
      name: ""Name""
    },
    {
      name: ""Client""
    },
    {
      name: ""MXN Amount""
    },
    {
      name: ""USD Amount""
    },
    {
      name: ""Payment Currency"",
      width: ""8%""
    },
    {
      name: ""MXN Insurance Cost""
    },
    {
      name: ""MXN Net Payment""
    },
    {
      name: ""Is Enrolled in Health Insurance?""
    },
  ];

  public dataHeadersExport = [
    ""#"",
    ""Role"",
    ""Name"",
    ""Client"",
    ""MXN Amount"",
    ""USD Amount"",
    ""Payment Currency"",
    ""MXN Insurance Cost"",
    ""MXN Net Payment"",
    ""Is Enrolled in Health Insurance?"",
    ""Uses TPS"",
    ""Hiring date"",
  ];
  public propertyKeys: string[];
  public propertyKeysExport: string[];

  public data = [];
  public dataExport = [];
  constructor(
    public apiService: ApiService,
    private modalService: NgbModal,
    private toastr: ToastrService
  ) {}

  ngOnInit() {
 
  }
  ngOnChanges() {
    this.createTableData();
  }

  createTableData() {
    this.propertyKeys = Object.keys(new SalaryDataModel());
    this.data =
      this.salariesCard &amp;&amp; this.salariesCard.shownProfiles ?
      this.salariesCard.shownProfiles.map((p) =&gt; {
        let salary: SalaryDataModel = new SalaryDataModel();
        salary.id = p.id;
        salary.role = this.roleNamesByProfileId[p.id];
        salary.name = p.firstName + "" "" + p.lastName;
        salary.client = this.salariesCard.getClientName(p);
        salary.mxnAmount =
          p.monthlyOfferedNetSalaryCurrencyId == 2 ?
          p.monthlyOfferedNetSalary :
          p.monthlyOfferedNetSalary * this.exchangeRate;
        salary.usdAmount =
          p.monthlyOfferedNetSalaryCurrencyId == 1 ?
          p.monthlyOfferedNetSalary :
          p.monthlyOfferedNetSalary / this.exchangeRate;
        salary.paymentCurrency =
          p.monthlyOfferedNetSalaryCurrencyId == 1 ? ""USD"" : ""MXN"";
        salary.mxnInsuranceCost = p.monthlyInsuranceCost;
        salary.mxnNetPayment = this.getNetPayment(p);
        salary.isEnrolledInHealthInsurance =
          p.isEnrolledInHealthInsuranceBonus;
        salary.isPaymentHold = p.isPaymentHold;

        salary.profile = p;

        return salary;
      }) :
      null;
  }


export class SalaryDataModel {
  id: number = 0;
  role: string = """";
  name: string = """";
  client: string = """";
  mxnAmount: number = 0;
  usdAmount: number = 0;
  paymentCurrency: string = """";
  mxnInsuranceCost: number = 0;
  mxnNetPayment: number = 0;
  isEnrolledInHealthInsurance ? : boolean = false;
  isPaymentHold: boolean = false;
  profile: ProfileModel;
}
export class SalaryDataModelExport {
  id: string = """";
  role: string = """";
  name: string = """";
  client: string = """";
  mxnAmount: number = 0;
  usdAmount: number = 0;
  paymentCurrency: string = """";
  mxnInsuranceCost: number = 0;
  mxnNetPayment: number = 0;
  isEnrolledInHealthInsurance ? : boolean = false;
  profile: ProfileModel;
  TXP: string = """";
  HiringDate: string = """";
}</code></pre>
</div>
</div>
</p>
<p>So, as you can see I try to access to:
<code>expect(fixture.componentInstance.data.length).toBe(1);</code>, but the length is always 0, this is weird because I specifying the value on:</p>
<pre><code>mockCashFlowService.createTableData.and.returnValue(of(data))
</code></pre>
<p>Why the data value is not detecting that I set the property on the test?</p>
",https://stackoverflow.com/questions/75167220/unit-testing-does-not-fill-the-component-object,"['javascript', 'angular', 'typescript', 'jasmine', 'karma-jasmine']",29,False,0,0
How do you create two local python packages in one project?,"<p>My current directory is set up like this</p>
<pre><code>src
  api
    __init__.py
    class1.py
    py.typed
  models
    __init__.py
    class2.py
    py.typed
tests
  test_class_1.py
  test_class_2.py
requirements.txt
requirements_dev.txt
pyproject.toml
setup.cfg
setup.py
tox.ini
</code></pre>
<p>I have made <code>models</code> an installable package so that I can import it in my <code>tests</code> directory for unit testing. I would also like to make <code>api</code> an installable package so that I can do the same thing.</p>
<p>Is there a way to do this?</p>
<p>Can you use the same <code>pyproject.toml</code> and <code>setup.cfg</code> files? Do you need to have separate versions of those files for each installable package you want to create?</p>
",https://stackoverflow.com/questions/76343467/how-do-you-create-two-local-python-packages-in-one-project,"['python', 'setup.py', 'python-packaging', 'pyproject.toml']",50,True,3,1
How to write spec for time Zone in angular,"<p>Below ill share, my code for reference</p>
<pre><code> getTimeZoneTime(val: string) {
    const userTimeZoneTime = moment
      .utc(val)
      .utcOffset(this.currentTimeZone)
      .local()
      .format('YYYY-MM-DD HH:mm:ss A');
    return userTimeZoneTime;
  }
</code></pre>
<p>I have set the time zone using moment and UTC and I have returned the time zone at the end in this I have set the type to the current time zone as string <code>currentTimeZone: string</code> here I have created a form in that time zone will be displayed, I'm new to unit testing how can I write a spec for this function</p>
",https://stackoverflow.com/questions/75092181/how-to-write-spec-for-time-zone-in-angular,"['angular', 'android-unit-testing']",35,False,0,0
&#39;No such module XCTest&#39; while trying to create a unit test class and importing &#39;XCTest&#39;,"<p>I'm just starting with learning Unit testing. I didn't check the 'Include tests' check box while creating the project. When I tried to create a Unit Test Case class by myself, I received a warning in the line where XCTest is imported saying 'No such module XCTest'.</p>
<p>I created a file with class Unit Test Case class under a folder that I made. Inside which i got the warning.</p>
",https://stackoverflow.com/questions/75554520/no-such-module-xctest-while-trying-to-create-a-unit-test-class-and-importing,"['ios', 'swift', 'xcode', 'unit-testing', 'compiler-warnings']",70,False,-2,1
"CodeIgniter 4 , unit test using PHPUnit","<p>I am using PHP version 7.3.2 with CodeIgniter version 4 using with PHPUnit version 9.6 and want to perform unit testing, How can I create test classes and run those tests? Also I cannot change the version of PHP and CodeIgniter.</p>
<p>For this I've tried to create test classes with the documentation of CodeIgniter 4 (<a href=""https://codeigniter.com/user_guide/testing/overview.html"" rel=""nofollow noreferrer"">https://codeigniter.com/user_guide/testing/overview.html</a>), But unable to run the test with CLI using command <code>phpunit tests\app\Libraries\FooTest.php</code></p>
",https://stackoverflow.com/questions/75603059/codeigniter-4-unit-test-using-phpunit,"['unit-testing', 'codeigniter', 'phpunit']",139,False,0,0
Microsoft Native Unit Test for C++ - where is the Logger output going?,"<p>Trying out C++ unit testing in Visual Studio 2019. Have added a C++ <code>Native Unit Test Project</code> unit test project to my solution. Then added the following <code>Logger</code> messages:</p>
<pre><code>TEST_CLASS_INITIALIZE(ClassInitialize)
{
    Logger::WriteMessage(&quot;Setup on test class. Where will this appear?&quot;);
}

// ...

TEST_METHOD(TestMethod1)
{
    Logger::WriteMessage(&quot;Test method. Where is this message going??&quot;);
}
</code></pre>
<p>The tests are picked up by the Visual Studio <code>Test Explorer</code> and run successfully. Breakpoints are also hit if the tests are debugged. According to the <a href=""https://learn.microsoft.com/en-us/visualstudio/test/microsoft-visualstudio-testtools-cppunittestframework-api-reference?view=vs-2022#logger"" rel=""nofollow noreferrer"">Microsoft documentation on Logger</a>, output should appear in the Visual Studio <code>Output Window</code>, but the messages are not being displayed.</p>
<p>Where is <code>Logger</code> sending its' output?</p>
",https://stackoverflow.com/questions/75439723/microsoft-native-unit-test-for-c-where-is-the-logger-output-going,"['c++', 'unit-testing', 'visual-studio-2019']",103,True,0,1
Unit testing localStorage with Jasmine &amp; JS,"<p>I'm trying to get my head around unit testing <code>window.localStorage</code> and I believe I'm almost there, I just can't seem to access the actual key/value pairs when testing my final helper method.</p>
<p>I have the following methods:</p>
<pre class=""lang-js prettyprint-override""><code>export function testSet() {
  window.localStorage.setItem('testSet', '1234');
}

export function testDeletePrefix() {
  let deleted = false;
  Object.entries(window.localStorage).forEach(([key, value]) =&gt; {
  console.log(key);
  // This logs out getItem setItem removeItem clear
  if (key.startsWith(&quot;test&quot;) &amp;&amp; key !== &quot;test&quot;) {
    window.localStorage.removeItem(key);
    console.log(`Item with key '${key}' deleted from local storage.`);
    deleted = true;
  }
});
  if (!deleted) {
    console.log(`No key starting with 'test' found in local storage.`);
  }
}
</code></pre>
<p>Unit test:</p>
<pre class=""lang-js prettyprint-override""><code>setItemSpy = spyOn(window.localStorage, &quot;setItem&quot;).and.callFake(
    (key, value) =&gt; {
      store[key] = value.toString();
    }
  );

testSet();
expect(setItemSpy).toHaveBeenCalledWith(&quot;testSet&quot;, &quot;1234&quot;);
testDeletePrefix();
</code></pre>
<p>Whenever I run this test I get the output <code>No key starting with 'test' found in local storage.</code></p>
<p>So the <code>spyOn</code> has confirmed the key/value pair has been set, so why can't I access them when looping over <code>window.localStorage</code>?</p>
",https://stackoverflow.com/questions/76154244/unit-testing-localstorage-with-jasmine-js,"['javascript', 'jasmine', 'local-storage']",48,False,0,2
K8s Test - NewSimpleClientset for schemaless custom resource,"<p>I have a method which uses client-go's <code>dynamic.Interface</code> to dynamically fetch a schemaless custom resource called <code>IstioOperator</code>.</p>
<pre><code>iops, err := client.Dynamic().Resource(constants.IstioOperatorGVR).
    Namespace(brConfig.IstioNamespace).
    List(ctx, metav1.ListOptions{})
</code></pre>
<p>I want to unit test this function. For that I'll have to mock the <code>client</code> so that it returns the provided CR. I am trying to mock it using <code>NewSimpleClientset</code> from <code>k8s.io/client-go/kubernetes/fake</code> package. When I pass the runtime object while initializing <code>NewSimpleClientset</code>, it panics with the following error:</p>
<pre><code>panic: no kind is registered for the type v1alpha1.IstioOperator in scheme &quot;pkg/runtime/scheme.go:100&quot;
</code></pre>
<p>So how to register the kind <code>v1alpha1.IstioOperator</code> in the mentioned scheme for unit testing?</p>
",https://stackoverflow.com/questions/75863913/k8s-test-newsimpleclientset-for-schemaless-custom-resource,"['go', 'kubernetes', 'istio', 'client-go', 'istio-operator']",67,False,2,0
How to unit test a function that uses leaderelection.RunOrDie,"<p>Here's a (somewhat simplified) bit of code that exposes a boolean if we've become leader via K8s leader election and false otherwise:</p>
<pre><code>type SimpleLeader struct {
    amLeader atomic.Value
}

func (s *SimpleLeader) run(ctx context.Context, client coordinationv1client.LeasesGetter) {

    lock := &amp;resourcelock.LeaseLock{
        LeaseMeta: metav1.ObjectMeta{
            Name:      &quot;testname&quot;,
            Namespace: &quot;testnamespace&quot;,
        },
        Client: client,
        LockConfig: resourcelock.ResourceLockConfig{
            Identity: &quot;testidentity&quot;,
        },
    }

    leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
        Lock:            lock,
        ReleaseOnCancel: true,
        LeaseDuration:   15 * time.Second,
        RenewDeadline:   10 * time.Second,
        RetryPeriod:     2 * time.Second,
        Callbacks: leaderelection.LeaderCallbacks{
            OnStartedLeading: func(c context.Context) {
                s.amLeader.Store(true)
            },
            OnStoppedLeading: func() {
                s.amLeader.Store(false)
            },
        },
    })
}
</code></pre>
<p>My question is how one would go about unit testing this? I'm aware of <a href=""https://pkg.go.dev/k8s.io/client-go/kubernetes/fake"" rel=""nofollow noreferrer"">client-go/fake</a> which does at least allow me to call <code>run</code>.  What's not clear is how to manipulate the fake client go so as to deterministically control whether I hold the lock at any given point in time.</p>
",https://stackoverflow.com/questions/75021286/how-to-unit-test-a-function-that-uses-leaderelection-runordie,"['unit-testing', 'go', 'kubernetes', 'client-go']",63,False,2,0
Why use useStore() in vue 3 composition api?,"<p>Can you please explain what is the reason to use <code>useStore()</code> function in vue 3 component (composition-api)?</p>
<p>I'm confused, because the direct import of the store is also works, e.g.:</p>
<pre class=""lang-html prettyprint-override""><code>&lt;script setup&gt;
import { store } from '@/store';

const foo = computed(() =&gt; store.getters['foo']); // works!
&lt;/script&gt;
</code></pre>
<p>But a lot of the time I see people are using <code>useStore()</code> instead:</p>
<pre class=""lang-html prettyprint-override""><code>&lt;script setup&gt;
import { useStore } from 'vuex';

const store = useStore();

const foo = computed(() =&gt; store.getters['foo']); // also works well
&lt;/script&gt;
</code></pre>
<p><strong>Why</strong>? So far feels just as an extra line of code.
I assume I'm missing something.</p>
<p>Thank you</p>
<hr />
<p><strong>Important update</strong>:
I learned that <code>useStore()</code> needed if you are doing unit testing and want to mock the store.</p>
",https://stackoverflow.com/questions/75323049/why-use-usestore-in-vue-3-composition-api,"['javascript', 'vue.js', 'vuejs3', 'vuex', 'vue-composition-api']",792,True,4,3
How to unit test Sealed classes,"<p>I'm struggling with the unit testing of a method that has been tested thru integration testing. The thing, is that this method explicitly calls a <code>sealed</code> class, hence making it unmockable via Moq.</p>
<pre><code>public async Task&lt;DatabaseSymbol&gt; ConnectAndReturnDatabaseSchema(
    string environment,
    string cluster
)
{
    KustoConnectionStringBuilder connection = null;
    if (environment == &quot;LOCAL&quot;)
    {
        connection = new KustoConnectionStringBuilder(
            cluster,
            &quot;AXA&quot;
        ).WithAadAzCliAuthentication(false);
    }
    else
    {
        //TODO: Manage other environments
    }
    ...
}
    
</code></pre>
<p><code>KustoConnectionStringBuilder</code> is a sealed class, with no interfacing, and only a single parent class. I know solutions like <em>JustMock</em> or <em>TypeMock</em> provide solutions, but I'm not paying for a testing library. What's the best way to proceed using Moq (or another free testing library?)</p>
",https://stackoverflow.com/questions/75207756/how-to-unit-test-sealed-classes,"['c#', 'unit-testing', 'moq']",320,True,1,2
Deserialize an elastic search hit to Hit&lt;ObjectNode&gt;,"<p>I'm trying to create a <code>Hit&lt;ObjectNode&gt;</code> from a json string returned by Elastic (for unit-testing purposes). When I try to deserialize this using <code>.withJson</code> I get a <code>ClassCastException</code> with the following message: <code>&quot;class co.elastic.clients.json.JsonDataImpl cannot be cast to class com.fasterxml.jackson.databind.node.ObjectNode (co.elastic.clients.json.JsonDataImpl and com.fasterxml.jackson.databind.node.ObjectNode are in unnamed module of loader 'app')&quot;</code></p>
<p>Full code:</p>
<pre><code>String hitJson = &quot;{\&quot;_index\&quot;:\&quot;my-index\&quot;,\&quot;_id\&quot;:\&quot;ID:MYID\&quot;,\&quot;_score\&quot;:1.0,\&quot;_source\&quot;:{\&quot;productCode\&quot;:\&quot;MYID\&quot;,\&quot;productName\&quot;:\&quot;my product\&quot;,\&quot;EffDate\&quot;:\&quot;01/01/1900\&quot;,\&quot;ExpDate\&quot;:\&quot;12/31/9999\&quot;,\&quot;Status\&quot;:\&quot;Active\&quot;,\&quot;productId\&quot;:1234567,\&quot;_type\&quot;:\&quot;my type\&quot;,\&quot;type\&quot;:\&quot;my type\&quot;,\&quot;updateTime\&quot;:\&quot;2021-07-08T11:40:18Z\&quot;}}&quot;;
InputStream hitInput = new ByteArrayInputStream(hitJson.getBytes());

Hit&lt;ObjectNode&gt; aHit = Hit.of(builder -&gt; builder.withJson(hitInput));
try {
    ObjectNode source = aHit.source();
} catch (Exception ex) {
    String msg = ex.getMessage();
}
</code></pre>
<p>I can see that JsonDataImpl does have all the properties, but I'm not sure why it can't deserialize it to <code>ObjectNode</code>. I'm not sure where to go from here - all my other attemps to use <code>.withJson</code> have succeeded without issue.</p>
<p>Formatted json response for reference:</p>
<pre><code>{
    &quot;_index&quot;: &quot;my-index&quot;,
    &quot;_id&quot;: &quot;ID:MYID&quot;,
    &quot;_score&quot;: 1.0,
    &quot;_source&quot;: {
        &quot;productCode&quot;: &quot;MYID&quot;,
        &quot;productName&quot;: &quot;my product&quot;,
        &quot;EffDate&quot;: &quot;01/01/1900&quot;,
        &quot;ExpDate&quot;: &quot;12/31/9999&quot;,
        &quot;Status&quot;: &quot;Active&quot;,
        &quot;productId&quot;: 1234567,
        &quot;_type&quot;: &quot;my type&quot;,
        &quot;type&quot;: &quot;my type&quot;,
        &quot;updateTime&quot;: &quot;2021-07-08T11:40:18Z&quot;
    }
}
</code></pre>
",https://stackoverflow.com/questions/75477296/deserialize-an-elastic-search-hit-to-hitobjectnode,"['java', 'elasticsearch', 'elasticsearch-java-api']",226,False,1,0
Testing a component where map is being loaded using esri-loader,"<p>In my React application there is a map which is being loaded using esri loader. Below is the code for loading map with the help of esri-loader using React.</p>
<p>App.js</p>
<pre><code>import React, { useEffect } from &quot;react&quot;;
import { loadModules } from &quot;esri-loader&quot;;

import &quot;./App.css&quot;;

export default function App() {


  let mapView;

  useEffect(()=&gt;{
    //load the api modules
    loadModules(
  [
    'esri/Map',
    'esri/views/MapView', 
    'esri/widgets/ScaleBar',
    'esri/widgets/Home',
    &quot;esri/layers/FeatureLayer&quot;,
  ], { css:true })
.then(([Map, MapView, ScaleBar, Home, FeatureLayer])=&gt;{
  
  let featureLayer = new FeatureLayer({
    url:
               &quot;https://services.arcgis.com/xdbDcZrQnv51VAwh/arcgis/rest/services/US_City_Population/FeatureServer&quot;
  });
  
  
  let map = new Map({
    basemap: &quot;topo-vector&quot;,
    ground: &quot;world-elevation&quot;,
    layers: [featureLayer]
  });

  mapView = new MapView({
    map: map,
    container: &quot;viewDiv&quot;
  })
})

return(
  &lt;div className='App'&gt;
     &lt;div className='mainDiv&gt;
        &lt;div id='viewDiv'&gt;
        &lt;/div&gt;
     &lt;/div&gt;
  &lt;/div&gt;
)

  
</code></pre>
<p>I want to create a unit test file which will test if the map has been loaded or not. I am very new to unit testing in React. There hasn't been much which was put to use here. Would really appreciate any suggestions?</p>
",https://stackoverflow.com/questions/76216573/testing-a-component-where-map-is-being-loaded-using-esri-loader,"['reactjs', 'unit-testing', 'jestjs', 'react-testing-library', 'esri-loader']",20,False,0,0
Flutter unit testing - Binding has not yet been initialized,"<p>Used SharedPreference throwing error in Unit test. In one function I have used SharedPreference and during it's unit testing getting error as &quot;Binding has not yet been initialized&quot; and many other errors too.</p>
<p>Working unit test:
<a href=""https://i.stack.imgur.com/ukuPP.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ukuPP.png"" alt=""enter image description here"" /></a></p>
<p>After uncommenting SharedPreference code:
<a href=""https://i.stack.imgur.com/ullk0.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ullk0.png"" alt=""enter image description here"" /></a></p>
<p>Below is the code of my User.dart file</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>import 'package:shared_preferences/shared_preferences.dart';

class User {
  final String name;

  User(this.name);
  Future&lt;bool&gt; userName() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(""name"", name);
    return true;
  }
}</code></pre>
</div>
</div>
</p>
<p>and below is the code of test file (User_test.dart)</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>import 'dart:math';

import 'package:flutter_test/flutter_test.dart';
import 'package:unit_testf/user.dart';

void main() {
  test(""a unit test"", () async {
    User user = User(""flutter"");
    final result = await user.userName();
    expect(result, true);
  });
}</code></pre>
</div>
</div>
</p>
<p>Below is the errors I am getting.</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>Binding has not yet been initialized.
The ""instance"" getter on the ServicesBinding binding mixin is only available once that binding has been initialized.
Typically, this is done by calling ""WidgetsFlutterBinding.ensureInitialized()"" or ""runApp()"" (the latter calls the former). Typically this call is done in the ""void main()"" method. The ""ensureInitialized"" method is idempotent; calling it multiple times is not harmful. After calling that method, the ""instance"" getter will return the binding.
In a test, one can call ""TestWidgetsFlutterBinding.ensureInitialized()"" as the first line in the test's ""main()"" method to initialize the binding.
If ServicesBinding is a custom binding mixin, there must also be a custom binding class, like WidgetsFlutterBinding, but that mixes in the selected binding, and that is the class that must be constructed before using the ""instance"" getter.
package:flutter/src/foundation/binding.dart 284:9                               BindingBase.checkInstance.&lt;fn&gt;
package:flutter/src/foundation/binding.dart 366:6                               BindingBase.checkInstance
package:flutter/src/services/binding.dart 54:54                                 ServicesBinding.instance
package:flutter/src/services/platform_channel.dart 166:45                       BasicMessageChannel.binaryMessenger
package:flutter/src/services/platform_channel.dart 180:38                       BasicMessageChannel.send
package:shared_preferences_foundation/messages.g.dart 115:52                    UserDefaultsApi.getAll
package:shared_preferences_foundation/shared_preferences_foundation.dart 46:53  SharedPreferencesFoundation.getAll
package:shared_preferences/shared_preferences.dart 164:57                       SharedPreferences._getSharedPreferencesMap
package:shared_preferences/shared_preferences.dart 33:19                        SharedPreferences.getInstance
package:unit_testf/user.dart 8:55                                               User.userName
test/user_test.dart 9:31                                                        main.&lt;fn&gt;</code></pre>
</div>
</div>
</p>
<p>Below is the output of my flutter doctor command</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>Last login: Thu Feb 16 09:58:26 on console
anandsuthar@anands-MacBook-Air ~ % flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.3.10, on macOS 13.1 22C65 darwin-x64, locale en-GB)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2022.1)
[✓] VS Code (version 1.75.1)
[✓] Connected device (2 available)
[✓] HTTP Host Availability

• No issues found!
anandsuthar@anands-MacBook-Air ~ % </code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/75470485/flutter-unit-testing-binding-has-not-yet-been-initialized,"['flutter', 'dart', 'unit-testing', 'hybrid-mobile-app', 'dart-unittest']",477,True,0,1
Jest functional/ unit test serve assets from public folder,"<p>My react functional component returns viewers from the third-party npm package.
which renders another SPA in the iframe, all the assets required for that SPA are in my public folder.
While unit testing these assets are not getting accessed.
how to serve this asset from the public folder.</p>
<p>the iframe render in test screen look like bellow</p>
<pre><code>&lt;iframe
      id=&quot;webviewer-1&quot;
      src=&quot;js/pdftron/./ui/index.html#d=%22%2Ftest%2Fdocument.pdf%22&amp;amp;extension=pdf&amp;amp;a=1&amp;amp;css=%2Fpublicjs%2Fpdftron%2FPDFTronCustomStyle.css&amp;amp;user=undefined undefined&amp;amp;filepicker=0&amp;amp;pdfnet=0&amp;amp;enableRedaction=0&amp;amp;disableVirtualDisplayMode=0&amp;amp;enableMeasurement=0&amp;amp;pageHistory=1&amp;amp;notesInLeftPanel=0&amp;amp;autoExpandOutlines=0&amp;amp;enableAnnotationNumbering=0&amp;amp;forceClientSideInit=1&amp;amp;singleServerMode=false&amp;amp;selectAnnotationOnCreation=0&amp;amp;autoFocusNoteOnAnnotationSelection=1&amp;amp;id=1&amp;amp;basePath=%2F&amp;amp;webViewerJSVersion=8.11.0&quot;
      title=&quot;webviewer&quot;
      frameborder=&quot;0&quot;
      width=&quot;100%&quot;
      height=&quot;100%&quot;
      allowfullscreen=&quot;true&quot;
      webkitallowfullscreen=&quot;true&quot;
      mozallowfullscreen=&quot;true&quot;
    &gt;&lt;/iframe&gt;&lt;
</code></pre>
<p>My public(folder for public assets) folder contains js/pdftron folder which has all the required assets.</p>
",https://stackoverflow.com/questions/75849022/jest-functional-unit-test-serve-assets-from-public-folder,"['reactjs', 'unit-testing', 'jestjs', 'react-testing-library']",51,False,0,0
Mocking class return NULL even after set the value manually,"<p>I'm new to unit testing and try to understand how mocking works. I got the code as below, where I mock <code>PdRequest.class</code> using <code>PowerMockRunner</code>. However, it return <code>Null</code> for all the variables. I also tried to set the value manually but its the same. Is there anything that I missing? and Is it better if I just create <code>new PdRequest()</code> and set all the values manually?</p>
<p><strong>What I tried</strong>
-Try to use <code>@PrepareForTest</code> and <code>@ExtendWith</code>
-Try to put <code>initMocks(this)</code></p>
<pre><code>@RunWith(PowerMockRunner.class)
public class PerformanceServiceImplTest 
</code></pre>
<pre><code> PdRequest pdRequest = mock(PdRequest.class);
        when(pdRequest.getLoginUserId()).thenReturn(&quot;42&quot;);
        when(pdRequest.getYear()).thenReturn(&quot;Year&quot;);
        doNothing().when(pdRequest).setLoginUserId((String) any());
        doNothing().when(pdRequest).setCurrMetric((String) any());
        doNothing().when(pdRequest).setCurrentLink((BreadCrumLink) any());
        doNothing().when(pdRequest).setFullView((String) any());
        doNothing().when(pdRequest).setManagerId((String) any());
        doNothing().when(pdRequest).setMetric((String) any());
        doNothing().when(pdRequest).setPdBoard((String) any());
        doNothing().when(pdRequest).setRegionId((String) any());
        doNothing().when(pdRequest).setRoleId((String) any());
        doNothing().when(pdRequest).setRoleLevel((Integer) any());
        doNothing().when(pdRequest).setRoleName((String) any());
        doNothing().when(pdRequest).setSalesAbf((String) any());
        doNothing().when(pdRequest).setSalesMm((String) any());
        doNothing().when(pdRequest).setSalesRsme((String) any());
        doNothing().when(pdRequest).setStaffId((String) any());
        doNothing().when(pdRequest).setStaffIdList((List&lt;String&gt;) any());
        doNothing().when(pdRequest).setTeamId((String) any());
        doNothing().when(pdRequest).setYear((String) any());
        pdRequest.setCurrMetric(&quot;Curr Metric&quot;);
        pdRequest.setCurrentLink(breadCrumLink);
        pdRequest.setFullView(&quot;Full View&quot;);
        pdRequest.setLoginUserId(&quot;42&quot;);
        pdRequest.setManagerId(&quot;42&quot;);
        pdRequest.setMetric(&quot;Metric&quot;);
        pdRequest.setPdBoard(&quot;Pd Board&quot;);
        pdRequest.setRegionId(&quot;us-east-2&quot;);
        pdRequest.setRoleId(&quot;42&quot;);
        pdRequest.setRoleLevel(1);
        pdRequest.setRoleName(&quot;Role Name&quot;);
        pdRequest.setSalesAbf(&quot;Sales Abf&quot;);
        pdRequest.setSalesMm(&quot;Sales Mm&quot;);
        pdRequest.setSalesRsme(&quot;Sales Rsme&quot;);
        pdRequest.setStaffId(&quot;42&quot;);
        pdRequest.setStaffIdList(new ArrayList&lt;&gt;());
        pdRequest.setTeamId(&quot;42&quot;);
        pdRequest.setYear(&quot;Year&quot;);
</code></pre>
<p><strong>Output</strong>
<a href=""https://i.stack.imgur.com/0m61T.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0m61T.png"" alt=""Debugging object"" /></a></p>
",https://stackoverflow.com/questions/75110204/mocking-class-return-null-even-after-set-the-value-manually,"['java', 'unit-testing', 'powermock', 'powermockrunner']",46,False,0,2
Possible to have template unit test methods in MSTest?,"<p>Using <code>Visual Studio 2019</code>, C# and the <code>MSTest</code> unit testing framework (v2.2.10). Say I have the following template function defined in my C# <code>MSTest</code> project:</p>
<pre><code>[TestMethod]
[DynamicData(nameof(TestData_Template), DynamicDataSourceType.Method)]
public void String_DoesSomething_ExpectsSomeResult&lt;T&gt;(T input, string expected)
{
    // Testing a template test method in MSTest (C#)

    // Arrange, act, assert
    string expectedLibrary = SomeLibrary.SomeFunction(input);
    Assert.AreEqual(expected, expectedLibrary);
}

// Generator method
private static IEnumerable&lt;object[]&gt; TestData_Template()
{
    // Generate some dynamic test data
    yield return new object[] { (int)7, &quot;7&quot; }; // Integer
    yield return new object[] { 0.123f, &quot;0.123&quot; }; // Float
}
</code></pre>
<p>Compiles fine, but the <code>Test Explorer</code> is not picking up the test method(s). If I specialise on <code>int</code> or <code>float</code> as follows, <code>Test Explorer</code> picks up the methods and they work:</p>
<pre><code>[TestMethod]
[DynamicData(nameof(TestData_Int), DynamicDataSourceType.Method)]
public void String_DoesSomething_ExpectsSomeResult_Int(int input, string expected)
{
    // Arrange, act and assert
    string expectedLibrary = SomeLibrary.SomeFunction(input);
    Assert.AreEqual(expected, expectedLibrary);
}

private static IEnumerable&lt;object[]&gt; TestData_Int()
{
    // Dynamic test data...but this time int only
    yield return new object[] { (int)7, &quot;7&quot; };
}
</code></pre>
<p>The library method being tested (<code>SomeLibrary::SomeFunction</code> in this example) is correctly defined and works fine. I want to use a generator method which is self-contained, and not long sets of constant input data using the <code>DataRow</code> attribute (<code>MSTest</code>).</p>
<ul>
<li>Are template methods possible in (<code>MSTest</code>) unit test projects?</li>
<li>Are they possible in other C# unit testing frameworks like <code>NUnit</code> or <code>xUnit</code>?</li>
</ul>
<h3>UPDATE</h3>
<p>As suggested in one of the answers, <code>DataRow</code> can be used to provide a constant set of test input data. This is not working for me, so the answer may have been targeting a different version of <code>MSTest</code> or <code>Visual Studio</code>.</p>
<p>However, <code>DataRow</code> is not what I'm looking for. Even assuming <code>DataRow</code> works with template methods, anything except small sets of input data would be clumsy. Writing detailed comments explaining the what and why of the input data would be messy and unmaintainable.</p>
<p>I'm looking for a way to using generator methods with template unit test methods, as in the question.</p>
",https://stackoverflow.com/questions/75573116/possible-to-have-template-unit-test-methods-in-mstest,"['c#', 'unit-testing', 'visual-studio-2019', 'mstest']",166,False,1,1
Jasmine testing with circular dependent classes: Variable &#39;C&#39; is used before being assigned,"<p>I'm trying to set up unit testing for a module written in TypeScript, and I need to use Jasmine to build mocks and test the component. However, due to a circular dependence between two classes I need to utilize, I can't adequately declare them in Jasmine to make a mock.</p>
<p>While doing this, I receive an <code>Variable 'C' is used before being assigned. TS2454</code> which is legit. How can I generate mocks that are accurate without altering the model?</p>
<p><strong>model.ts</strong></p>
<pre><code>export class A {
  public constructor(
    public c: C) {
  }
}

export class B {
  public constructor(
    public c: C) {
  }
}

export class C {
  public constructor(
    public a: A,
    public b: B,
    public id: string) {
  }
}
</code></pre>
<p><strong>spec.ts</strong></p>
<pre><code>const a: A = {
  c: C
 };
const b: B = {
  c: C
 };
const c: C = {
  a: A,
  b: B,
  id: ''    
 };
</code></pre>
",https://stackoverflow.com/questions/75223901/jasmine-testing-with-circular-dependent-classes-variable-c-is-used-before-bei,"['typescript', 'unit-testing', 'karma-jasmine', 'circular-dependency']",22,False,0,0
Can I do unit testing to code that uses TimeOfDay (package:flutter/material.dart)?,"<p>I'm new to Unit Testing.</p>
<p>I want to test some <strong>DateTime</strong> and <strong>TimeOfDay</strong> calculations, but it looks as if it's not possible to write unit tests that import <strong>package:flutter/material.dart</strong> (which is needed for TimeOfDay).</p>
<p>Is that the case? If so, how can I test my code?</p>
<p>UPDATE:<br />
Well, it seems that my mistake was that I was trig to run the test using:</p>
<blockquote>
<p>dart test test/simple_test.dart</p>
</blockquote>
<p>Instead of:</p>
<blockquote>
<p>flutter test test/simple_test.dart</p>
</blockquote>
",https://stackoverflow.com/questions/76195915/can-i-do-unit-testing-to-code-that-uses-timeofday-packageflutter-material-dart,"['flutter', 'testing']",19,False,0,0
How to test custom exception with Mockito,"<p>I am trying to learn unit testing with Mockito. This is a method I wrote to authenticate the users that tries to log in:</p>
<pre><code>public class AuthenService {
    
    private UserRepo userRepo;  

    public User authenticate(String username, String password) throws UserNotFoundException {
        User user = null;
        if (userRepo.validate(username, password)) {
            user = userRepo.findUsername(username);
            return user;
        } else {
            throw new UserNotFoundException(&quot;User not found!&quot;);
        }
    }
}
</code></pre>
<p>userRepo is an interface with these two abstract methods:</p>
<pre><code>public interface UserRepo{
    
    boolean validate(String username, String password);
    
    User findUsername(String username);
    
}
</code></pre>
<p>This is my testing code:</p>
<pre><code>public class Test {

    AuthenService as;
    UserRepo ur;
    
    @BeforeEach
    public void init() {
        ur = mock(UserRepo.class);
        as = new AuthenService(ur);
    }
    
    @Test
    public void authenticate() throws UserNotFoundException {
        when(as.authenticate(&quot;abc&quot;, &quot;123&quot;)).thenThrow(new UserNotFoundException(&quot;User not found!&quot;));
    }
}
</code></pre>
<p>I suppose as.authenticate(&quot;abc&quot;, &quot;123&quot;) should throw an exception because the DB is empty right now. But I think I am wrong, and I have no idea how to fix it. Can anyone please explain to me? Thank you.</p>
",https://stackoverflow.com/questions/75025957/how-to-test-custom-exception-with-mockito,"['java', 'mockito']",89,True,2,2
How do I perform integration testing with Azure DevOps Pipelines for monitoring file flow?,"<p>I need some guidance for Integraion Testing with Azure DevOps Pipelines.</p>
<p>I'm totally new to DevOps.</p>
<p>The application I need to test monitor folders for new files, once new files are detected they are loaded and teated and then moved to another folder.
There is more to it like file format checking, treatment parameters loading and checking from a database...</p>
<p>I need to test that files are correctly loaded and treated, by checking the folder move flow and file process steps logged in log files.</p>
<p>Basically all steps we do manually after code modification.</p>
<p>I guess steps would be:</p>
<ul>
<li>clone code</li>
<li>load dependencies</li>
<li>compile</li>
<li>start the programme</li>
<li>move test files in monitored folder</li>
<li>check file presences in folders</li>
<li>check log for keywords</li>
<li>build and save/send repport</li>
</ul>
<p>For what I google, this is integration testing not Unit testing.</p>
<p>I wonder if I can use standard Testing framework (xUnit, NUnit, MSTest... ) or a special framework ?
I found reference about Celenium and Appium but they lok to be targeted towards web app/site testing.</p>
<p>I also see reference to Visual Studio test plarform, but for what I understand look to be for unit testing !?</p>
<p>Any suggestions ?</p>
<p>Thanks and regards</p>
",https://stackoverflow.com/questions/76341854/how-do-i-perform-integration-testing-with-azure-devops-pipelines-for-monitoring,"['testing', 'azure-devops', 'azure-pipelines', 'integration']",18,False,-1,0
FastAPI unit test returns 422,"<p>I am new to python and FastAPI and writing some test code for FastAPI endpoints.
I have the following function for unit testing, but when I run it I get back status code 422.
Not sure what I am doing wrong:</p>
<pre><code>    def test_create_event(self):
        my_date = datetime.date(2023, 6, 15)
        data = {'id': '1', 'title': 'Winter Cooking', 'host': 'Steven',
                'ingredients': ['Apples','Pumpkin','Pecans','Oats'], 
                'date': my_date.strftime('%m-%d-%Y'), 'participants': ['Steven','Kyle']}
        response = requests.post(self.url + '/events/', json=data)
        print(&quot;response=&quot; + str(response.status_code))
        self.assertEqual(response.status_code, 201)
</code></pre>
<p>The Event class is defined the following way:</p>
<pre><code>class Event(BaseModel):
    id: int
    title: str
    host: str
    ingredients: List[str] = []
    date: datetime
    participants: List[str] = []
</code></pre>
<p>My POST method that works is defined here:</p>
<pre><code># For event creation via POST
@events_router.post(&quot;/events/&quot;, status_code=201, response_model=Event)
def create_event(*, event_in: EventCreate) -&gt; Event:
    &quot;&quot;&quot;
    Create a new event (in memory only)
    &quot;&quot;&quot;
    #change below to be based on global variable counter
    global counter
    new_entry_id = counter
    # TODO: change date to server-side data value
    event_entry = Event(
        id=new_entry_id,
        title=event_in.title,
        host=event_in.host,
        ingredients=event_in.ingredients,
        date=event_in.date,
        participants=event_in.participants
    )
    EVENTS.append(event_entry.dict())
    counter += 1

    return event_entry
</code></pre>
<p>Thanks for any advice</p>
<p>Update:</p>
<p>The EventCreate class:</p>
<pre><code>class EventCreate(BaseModel):
    title: str
    host: str
    ingredients: List[str] = []
    date: datetime
    participants: List[str] = []
    submitter_id: int
</code></pre>
<p>I changed the code to the following:</p>
<pre><code>def test_create_event(self):
        my_date = datetime.date(2023, 6, 15)
        data = {'title': 'Winter Cooking', 'host': 'Steven',
                'ingredients': ['Apples','Pumpkin','Pecans','Oats'], 
                'date': my_date.strftime('%m-%d-%Y'), 
                'participants': ['Steven','Kyle'], 'submitter_id': 1, }
        response = requests.post(self.url + '/events/', json=data)
        print(&quot;response=&quot; + str(response.status_code))
        self.assertEqual(response.status_code, 201)
</code></pre>
<p>Still getting 422 error code</p>
",https://stackoverflow.com/questions/75914976/fastapi-unit-test-returns-422,"['python', 'json', 'fastapi']",74,True,1,1
How can I mock a request.post call so that it returns something specific when I call json() on it?,"<p>I have the following function that I am unit testing:</p>
<pre><code>class CustomDailyDownload(): 
    ....
    def authenticate(self):

        response = requests.post(self.finfo.extra['auth_url'], data=res, headers=headers)
        token = response.json()['access_token']
        return token
</code></pre>
<p>I would simply like to to mock out <code>request.post</code> so that it returns a json dictionary with a key <code>access_token</code>. So that in the next like token can be assigned properly.</p>
<p>I found this article semi helpful but couldn't get all the way: <a href=""https://stackoverflow.com/questions/15753390/how-can-i-mock-requests-and-the-response"">How can I mock requests and the response?</a>.</p>
<p>Here is what I tried:</p>
<pre><code>@mock.patch(&quot;&lt;path_to_above_funcion&gt;.requests&quot;)
def test_authenticate(mock_request):
    responses.add(responses.POST, 'https://auth.cmauth2', json={'access_token': 'eyJhbGciOiJKV0duTHRYby1kWlo', 'token_type': 'Bearer', 'expires_in': 1799}, status=200)

    finfo = MagicMock()

    mock_request.post = requests.post('https://auth.cmauth2')
    cme_ref_api = CustomDailyDownload(finfo)
    assert cme_ref_api.authenticate()== 'eyJhbGciOiRYby1kWlo'
</code></pre>
<p>When I run the above, I get the error <code>TypeError: 'Response' object is not callable</code></p>
<p>on the line: <code>response = requests.post(self.finfo.extra['auth_url'], data=res, headers=headers)</code></p>
",https://stackoverflow.com/questions/76037680/how-can-i-mock-a-request-post-call-so-that-it-returns-something-specific-when-i,"['python', 'unit-testing', 'python-requests']",43,False,0,0
Combine Makefile and docker-compose on Flask app,"<p>I write my <a href=""https://github.com/trouchet/appy"" rel=""nofollow noreferrer"">first Flask app</a> ever. I bring some good practices I learned: unit testing, fixtures, endpoints, Makefile, and docker encapsulation.</p>
<p>The commands on Makefile make my life less naggy. Therefore, it seems good to bring both together. I tried, maybe not my best effort on the <a href=""https://github.com/trouchet/appy/blob/main/Dockerfile"" rel=""nofollow noreferrer"">Dockerfile</a>. Do you mind helping me with the error log below?</p>
<pre><code>appy_app    | node:internal/modules/cjs/loader:1056
appy_app    |   throw err;
appy_app    |   ^
appy_app    | 
appy_app    | Error: Cannot find module '/usr/app/make'
appy_app    |     at Module._resolveFilename (node:internal/modules/cjs/loader:1053:15)
appy_app    |     at Module._load (node:internal/modules/cjs/loader:898:27)
appy_app    |     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:84:12)
appy_app    |     at node:internal/main/run_main_module:23:47 {
appy_app    |   code: 'MODULE_NOT_FOUND',
appy_app    |   requireStack: []
appy_app    | }
appy_app    | 
appy_app    | Node.js v19.4.0
</code></pre>
<p>As @DavidMaze remarks, I changed the first line on Dockerfile to <code>FROM python:3.6-alpine</code>, but still receive a node-related error. Weird.</p>
",https://stackoverflow.com/questions/76185602/combine-makefile-and-docker-compose-on-flask-app,['docker'],30,False,0,0
mock.patch-ing the .append method of the Python list,"<p>I am unit testing a single line of code within an if statement where I append an item onto a list if a variable has a specific value.</p>
<pre><code>foo = []
if bar == 'a':
    foo.append(bar)
</code></pre>
<p>I would like to assert that such an append has been called. I have patched methods from a variety of sources before, but not methods belonging to basic Python data types. What class would I specify as the path for the mock.patch decorator?</p>
<pre><code>@mock.patch('append')
def test_appends_bar_to_foo(mock_append):
    assert mock_append.called
</code></pre>
<p>With the above code, I get <code>TypeError: Need a valid target to patch. You supplied: 'append'</code></p>
",https://stackoverflow.com/questions/76361397/mock-patch-ing-the-append-method-of-the-python-list,"['python', 'mocking', 'pytest', 'python-unittest', 'magicmock']",42,True,0,1
Can not use lazy loading in mu unit tests C# XUnit,"<p>I'm trying to write unit tests for my service which uses lazy loading. However, I can not get lazy loading to work on my InMemory database.</p>
<pre><code>_options = new DbContextOptionsBuilder&lt;LanAdeptDbContext&gt;()
            .UseInMemoryDatabase(&quot;tournament&quot;)
            .UseLazyLoadingProxies()
            .Options;
</code></pre>
<p>Here is my test:</p>
<pre><code>// Arrange
int eventId = 1;

using (LanAdeptDbContext context = new LanAdeptDbContext(_options))
{
    TournamentService service = new TournamentService(context);

    // Act
    List&lt;Tournament&gt; result = await service.GetListTournamentAsync(eventId);

    //Assert
    int nbTournamentsForEvent =
        await context.Tournaments.CountAsync(t =&gt; t.EventId == eventId);
    Assert.Equal(result.Count, nbTournamentsForEvent);
}
</code></pre>
<p>Here is the error I'm getting for all unit tests after enabling lazy loading :</p>
<pre><code>Method not found: 'System.Collections.Generic.IList1&lt;Microsoft.EntityFrameworkCore.Metadata.Conventions.IModelInitializedConvention&gt; Microsoft.EntityFrameworkCore.Metadata.Conventions.ConventionSet.get_ModelInitializedConventions()'.
</code></pre>
<p>I have tried creating and specifying a custom internal service provider, but it did not help. There is also not a ton of information online as to how to use lazy loading in unit testing.</p>
",https://stackoverflow.com/questions/75337803/can-not-use-lazy-loading-in-mu-unit-tests-c-xunit,"['c#', 'asp.net', 'entity-framework', 'lazy-loading', 'xunit']",36,False,0,0
CI/CD Gitlab ERROR 2005 (HY000): Unknown server host &#39;mysql&#39; (-3),"<p>Lately I was implementing a gitlab CI/CD pipeline configuration for unit testing, in which I need to have a test database to run my tests on.</p>
<p>So I wrote this config as shown below running on a self hosted gitlab-runner server on a Digital ocean druplet.</p>
<p>But the pipeline failed with this error, <code>ERROR 2005 (HY000): Unknown server host 'mysql' (-3)</code>.</p>
<p>My CI/CD configuration:</p>
<pre><code>stages:
  - build
  - test

image: ahmed2zaky2/laravel-deploy-php81:latest

cache:
  key: &quot;$CI_JOB_NAME-$CI_COMMIT_REF_SLUG&quot;

build:
  stage: build
  script:
    - apk update &amp;&amp; apk add zip
    - curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
    - composer install --prefer-dist --no-ansi --no-interaction --no-progress --no-scripts
    - cp .env.testing.example .env.testing
    - cp .env.testing .env
    - php artisan key:generate
    - php artisan key:generate --env=testing
    - php artisan optimize
    - php artisan cache:clear
    - chmod 755 -R storage bootstrap/cache
  artifacts:
    paths:
      - vendor/
      - .env
      - .env.testing
  cache:
    paths:
      - vendor/
  only:
    - merge_requests
    - dev
    - main

test-unit:
  stage: test
  services:
    - name: mysql:8.0
      alias: mysql
      command: [&quot;--default-authentication-plugin=mysql_native_password&quot;]
  before_script:
    - mysql --version
    - sleep 30
    - echo &quot;SELECT 'OK';&quot; | mysql -h$DB_HOST -u$MYSQL_USER -p$MYSQL_ROOT_PASSWORD -e &quot;CREATE DATABASE ${MYSQL_DATABASE};&quot;
  script:
    - php artisan test
  variables:
    MYSQL_ROOT_PASSWORD: root
    MYSQL_USER: root
    MYSQL_PASSWORD: root
    MYSQL_DATABASE: jadwalh_test
    MYSQL_HOST: mysql
    DB_HOST: mysql
  dependencies:
    - build
  environment:
    name: development
  only:
    - dev
</code></pre>
<p>The Pipeline Failed Error</p>
<p><a href=""https://i.stack.imgur.com/domBM.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/domBM.png"" alt=""enter image description here"" /></a></p>
<p><a href=""https://i.stack.imgur.com/F5kgo.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/F5kgo.png"" alt=""enter image description here"" /></a></p>
<p>What could causes such an issue and how could we fix it, if possible.</p>
",https://stackoverflow.com/questions/76139001/ci-cd-gitlab-error-2005-hy000-unknown-server-host-mysql-3,"['mysql', 'docker', 'gitlab-ci', 'gitlab-ci-runner', 'cicd']",51,False,0,0
Jest and Angular: Cannot find module &#39;src/environments/environment&#39;,"<p>I have Angular projects with Jest in place for unit testing. I'm trying to unit test a certain service that has environment variable as private property and if I run the test, it fails with the following information - Cannot find module 'src/environments/environment' from 'src/app/resources/services/resources.service.ts'</p>
<p><a href=""https://i.stack.imgur.com/xvG5G.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/xvG5G.png"" alt=""project file structure "" /></a></p>
<pre><code> FAIL  src/app/resources/services/resources.service.test.ts
</code></pre>
<p>● Test suite failed to run</p>
<pre><code>Cannot find module 'src/environments/environment' from 'src/app/resources/services/resources.service.ts'

Require stack:
  src/app/resources/services/resources.service.ts
  src/app/resources/services/resources.service.test.ts

  1 | import { Injectable } from '@angular/core';
&gt; 2 | import { environment } from 'src/environments/environment';
    | ^
  3 | import { Observable, Subject } from 'rxjs';
  4 | import { Resource } from '../models/resources';
  5 | import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';

  at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:427:11)
  at Object.&lt;anonymous&gt; (src/app/resources/services/resources.service.ts:2:1)
  at Object.&lt;anonymous&gt; (src/app/resources/services/resources.service.test.ts:7:1)
</code></pre>
<p>Test Suites: 1 failed, 1 total<br />
Tests:       0 total<br />
Snapshots:   0 total
Time:        3.484 s</p>
<p><strong>jest.config.ts</strong>
<div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>// require('jest-preset-angular/ngcc-jest-processor');

globalThis.ngJest = {
  skipNgcc: true,
  tsconfig: 'tsconfig.spec.json', // this is the project root tsconfig
};

/** @type {import('@jest/types').Config.InitialOptions} */
module.exports = {
  preset: 'jest-preset-angular',
  setupFiles: ['&lt;rootDir&gt;/src/environment/environment'],
  setupFilesAfterEnv: ['&lt;rootDir&gt;/setup-jest.ts'],
};</code></pre>
</div>
</div>
</p>
<p><strong>setupJest.ts</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import 'jest-preset-angular/setup-jest';
import './jest-global-mocks';</code></pre>
</div>
</div>
</p>
<p>Any help will be much appreciated.</p>
",https://stackoverflow.com/questions/75338281/jest-and-angular-cannot-find-module-src-environments-environment,"['angular', 'unit-testing', 'jestjs', 'configuration']",550,False,0,0
Multiple sets of input data for Microsoft Unit Testing Framework for C++,"<p>Using Visual Studio 2019. The <code>MSTest</code> unit testing framework for C# has the <code>DataRow</code> attribute which allows test methods to be automatically called with multiple sets of constant input data. For example:</p>
<pre><code>[TestMethod]
[DataRow(11.99, 4.55)] // One or more sets of constant input test data
[DataRow(50.00, 40.00)]
public void Debit_WithValidAmount_UpdatesBalance_WithConstantData(double balance, double debit)
{
    // ...method called twice with {11.99, 4.55} and {50.00, 40.00}
}
</code></pre>
<p>Is it possible to have multiple sets of constant test input data with Microsoft's <code>Native Unit Test</code> framework, also called the <code>Microsoft Unit Testing Framework for C++</code>?</p>
<p><code>MSTest</code> also allows generator methods to create dynamic input data. For example:</p>
<pre><code>[TestMethod]
[DynamicData(nameof(MyTestData), DynamicDataSourceType.Method)]
public void Debit_WithValidAmount_UpdatesBalance_WithDynamicData(double balance, double debit)
{
    // ...method called twice with {12.99, 1.23} and {55.00, 45.00}
}

private static IEnumerable&lt;object[]&gt; MyTestData()
{
    // Generator method to create dynamic test data
    yield return new object[] { 12.99, 1.23  };
    yield return new object[] { 55.00, 45.00 };
}
</code></pre>
<p>Similar question, is it possible to use generator methods with Microsoft's <code>Native Unit Test</code> framework to create dynamic input data?</p>
",https://stackoverflow.com/questions/75448806/multiple-sets-of-input-data-for-microsoft-unit-testing-framework-for-c,"['c++', 'visual-studio', 'unit-testing', 'microsoft-unit-testing']",50,False,0,0
How to Unit Test BindingLIfecycleController state changes,"<p>I have written CustomHealthIndicator to check the producer binding is running, if not then Pause the Consumer binding. We have implemented the application using Spring-cloud-streams-kafka-binder in functional style.
Below is the snippet of code doing that:</p>
<pre><code>import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.boot.availability.ReadinessState;
import org.springframework.cloud.stream.binder.Binding;
import org.springframework.cloud.stream.binding.BindingsLifecycleController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class BindingHealthIndicator implements HealthIndicator {

    private final ApplicationContext context;
    private final ApplicationEventPublisher eventPublisher;

    private String PRODUCER_ERROR_MESSAGE = &quot;The Src topic is unavailable&quot;;

    private String CONSUMER_ERROR_MESSAGE = &quot;The Dest topic is unavailable&quot;;
    private String SUCCESS_MESSAGE = &quot;The Consumer and producer topics are Healthy&quot;;

    public BindingHealthIndicator(ApplicationContext context, ApplicationEventPublisher eventPublisher) {
        this.context = context;
        this.eventPublisher = eventPublisher;
    }

    @Override
    public Health health() {
        BindingsLifecycleController bindingsController = context.getBean(BindingsLifecycleController.class);
        Boolean producerBindingStatus;
        try {
            Binding producerBinding = bindingsController.queryState(&quot;consumeAndProcessAllAccountUpdate-out-0&quot;);
            producerBindingStatus = producerBinding.isRunning();
        } catch(Exception ex) {
            bindingsController.changeState(&quot;consumeAndProcessAllAccountUpdate-in-0&quot;, BindingsLifecycleController.State.PAUSED);
            AvailabilityChangeEvent.publish(this.eventPublisher, PRODUCER_ERROR_MESSAGE, ReadinessState.REFUSING_TRAFFIC);
            log.error(PRODUCER_ERROR_MESSAGE);
            return Health.down().withDetail(&quot;description&quot;, PRODUCER_ERROR_MESSAGE).build();
        }
        Binding consumerBinding = bindingsController.queryState(&quot;consumeAndProcessAllAccountUpdate-in-0&quot;);
        Boolean consumerBindingStatus = consumerBinding.isRunning();

        if(!(producerBindingStatus)) {
            log.error(PRODUCER_ERROR_MESSAGE);
            bindingsController.changeState(&quot;consumeAndProcessAllAccountUpdate-in-0&quot;, BindingsLifecycleController.State.PAUSED);
            AvailabilityChangeEvent.publish(this.eventPublisher, PRODUCER_ERROR_MESSAGE, ReadinessState.REFUSING_TRAFFIC);
            return Health.down().withDetail(&quot;description&quot;, PRODUCER_ERROR_MESSAGE).build();
        }
        if(!(consumerBindingStatus)) {
            log.error(CONSUMER_ERROR_MESSAGE);
            AvailabilityChangeEvent.publish(this.eventPublisher, CONSUMER_ERROR_MESSAGE, ReadinessState.REFUSING_TRAFFIC);
            return Health.down().withDetail(&quot;description&quot;, CONSUMER_ERROR_MESSAGE).build();
        }
        bindingsController.changeState(&quot;consumeAndProcessAllAccountUpdate-in-0&quot;, BindingsLifecycleController.State.RESUMED);
        AvailabilityChangeEvent.publish(this.eventPublisher, SUCCESS_MESSAGE, ReadinessState.ACCEPTING_TRAFFIC);
        return Health.up().withDetail(&quot;description&quot;, SUCCESS_MESSAGE).build();
    }
}

</code></pre>
<p>I want to simulate through Unit testing that the producer binder to be having issues or to have the isRunning return false, and check if consumer is PAUSED, could you please suggest the correct approach to be followed?</p>
",https://stackoverflow.com/questions/75538861/how-to-unit-test-bindinglifecyclecontroller-state-changes,"['spring-cloud-stream', 'spring-cloud-stream-binder-kafka']",70,False,0,0
String Hashed in both Kotlin and Golang,"<p>In service A I have a string that get hashed like this:</p>
<pre><code>fun String.toHash(): Long {
    var hashCode = this.hashCode().toLong()
    if (hashCode &lt; 0L) {
        hashCode *= -1
    }
    return hashCode
}
</code></pre>
<p>I want to replicate this code in service B written in Golang so for the same word I get the exact same hash. For what I understand from Kotlin's documentation the hash applied returns a 64bit integer. So in Go I am doing this:</p>
<pre><code>func hash(s string) int64 {
    h := fnv.New64()
    h.Write([]byte(s))
    v := h.Sum64()
    return int64(v)
}
</code></pre>
<p>But while unit testing this I do not get the same value. I get:</p>
<pre><code>func Test_hash(t *testing.T) {
    tests := []struct {
        input  string
        output int64
    }{
        {input: &quot;papafritas&quot;, output: 1079370635},
    }
    for _, test := range tests {
        got := hash(test.input)
        assert.Equal(t, test.output, got)
    }
}
</code></pre>
<p>Result:</p>
<pre><code>7841672725449611742
</code></pre>
<p>Am I doing something wrong?</p>
",https://stackoverflow.com/questions/75365845/string-hashed-in-both-kotlin-and-golang,"['kotlin', 'go', 'hash']",131,True,0,1
No idea why setUpAll() is not running before test(),"<p>I followed this tutorial <a href=""https://betterprogramming.pub/flutter-unit-testing-the-beginners-guide-35105164722e"" rel=""nofollow noreferrer"">https://betterprogramming.pub/flutter-unit-testing-the-beginners-guide-35105164722e</a> for the implementation of setUpAll(){}</p>
<p>Initial code is able to pass flutter test but not the one implemented with setUpAll().</p>
<p>Based on flutter code documentation of the function setUpAll(), this function will run before test(), so in theory, _taskProvider should be initialized, but it doesnt seem like that is the case for my program.</p>
<p>The error shows:</p>
<pre><code>test task provider test addTask [E]                                                                                                                      
  LateInitializationError: Local '_taskProvider' has not been initialized.
  dart:_internal                     LateError._throwLocalNotInitialized
  test/task_provider_test.dart 22:7  main.&lt;fn&gt;.&lt;fn&gt;
</code></pre>
<p>// Code without setUpAll()</p>
<pre><code>import 'package:flutter_test/flutter_test.dart';
import 'package:to_do_app_new/providers/task_provider.dart';

void main() {
  group(&quot;test task provider&quot;, () {
    test('test addTask', () {
      TaskProvider _taskProvider = TaskProvider();
      Task _task = Task(title: &quot;MY TO DO ITEM #1&quot;, description: &quot;GET GOOD&quot;);

      _taskProvider.addTask(_task);

      expect(_task.title, _taskProvider.items[0].title);
      expect(_task.description, _taskProvider.items[0].description);
    });
  });
}
</code></pre>
<p>// Code with setUpAll()</p>
<pre><code>import 'package:flutter_test/flutter_test.dart';
import 'package:to_do_app_new/providers/task_provider.dart';

late TaskProvider _taskProvider;
late Task _task;
void main() {
  group(&quot;test task provider&quot;, () {
    setUpAll() {
      _taskProvider = TaskProvider();
      _task = Task(title: &quot;MY TO DO ITEM #1&quot;, description: &quot;GET GOOD&quot;);
    }

      test('test addTask', () {
      _taskProvider.addTask(_task);

      expect(_task.title, _taskProvider.items[0].title);
      expect(_task.description, _taskProvider.items[0].description);
    });
  });
}
</code></pre>
<p>// task_provider.dart file</p>
<pre><code>import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';

class Task {
  bool completed;
  String title;
  String description;
  final String uuid;

  Task({this.completed = false, required this.title, required this.description})
      : uuid = const Uuid().v4();

  @override
  bool operator ==(covariant Task other) =&gt; uuid == other.uuid;
  @override
  int get hashCode =&gt; uuid.hashCode;

  setTitle(String title) {
    this.title = title;
  }
}

class TaskProvider extends ChangeNotifier {
  final List&lt;Task&gt; _items = [];

  findTask(Task task) {
    _items.firstWhere((i) =&gt; i.uuid == task.uuid);

  }

  UnmodifiableListView&lt;Task&gt; get items =&gt; UnmodifiableListView(_items);

  void addTask(Task task) {
    _items.add(task);
    notifyListeners();
  }
}
</code></pre>
",https://stackoverflow.com/questions/75431831/no-idea-why-setupall-is-not-running-before-test,['flutter'],187,True,0,1
how to use youtube_player_iframe package in flutter?,"<p>When I use <code>youtube_player_iframe</code> package I am getting and error that is &quot;A platform implementation for <code>webview_flutter</code> has not been set. Please ensure that an implementation of <code>WebViewPlatform</code> has been set to <code>WebViewPlatform.instance</code> before use. For unit testing, <code>WebViewPlatform.instance</code> can be set with your own test implementation.</p>
<blockquote>
<p>'package:webview_flutter_platform_interface/src/platform_webview_controller.dart':
platform_webview_controller.dart:1
Failed assertion: line 25 pos 7: 'WebViewPlatform.instance != null'&quot;.</p>
</blockquote>
<p>Can you help me to solve this problem.</p>
<p>When I use <code>youtube_player_iframe</code> package it should output youtube videos.
I hope you will be solve this issue.</p>
",https://stackoverflow.com/questions/75583751/how-to-use-youtube-player-iframe-package-in-flutter,['flutter'],85,False,1,0
Jest has detected the following 1 open handle potentially keeping Jest from exiting TCPWRAP,"<p>we are using Jest for unit-testing. we use sequelize ORM. we initially has a class that initialized and exported sequelize like so:</p>
<p>database.ts:</p>
<pre><code>export const sequelize = ...
</code></pre>
<p>Jest gave us no issues with this code. we were calling <code>sequelize.close()</code> after completion of all tests.</p>
<p>Then we had to revise the code like so (since we have multiple modules that plug into our main application):</p>
<p>database.ts</p>
<pre><code>export { sequelize } from 'common'
</code></pre>
<p>Now Jest gives us this warning at end of tests:</p>
<pre><code>Jest has detected the following 1 open handle potentially keeping Jest from exiting:

  ●  TCPWRAP

    &gt; 1 | export { sequelize } from 'common'
        | ^
      2 |

      at Connection.connect (node_modules/pg/lib/connection.js:43:17)
      at Client._connect (node_modules/pg/lib/client.js:113:11)
      at Client.connect (node_modules/pg/lib/client.js:162:12)
      at BoundPool.newClient (node_modules/pg-pool/index.js:232:12)
      at BoundPool.connect (node_modules/pg-pool/index.js:207:10)
      at BoundPool.query (node_modules/pg-pool/index.js:394:10)
      at Object.&lt;anonymous&gt; (node_modules/common/src/index.ts:14:6)
      at Object.&lt;anonymous&gt; (src/database/sequelize.ts:1:1)
      at Object.&lt;anonymous&gt; (src/database/index.ts:4:1)
      at Object.&lt;anonymous&gt; (test/initdb.ts:1:1)
      at Object.&lt;anonymous&gt; (test/foo.spec.ts:1:1)
</code></pre>
<p>any idea why and how we can fix this?</p>
",https://stackoverflow.com/questions/76186666/jest-has-detected-the-following-1-open-handle-potentially-keeping-jest-from-exit,['jestjs'],24,False,0,0
&lt;TemplateResponse&gt; object does not have attribute data in Unit test in django,"<p>Hi guys im trying to run some unit testing based on this view here in django but it gives me the error <strong>AttributeError: 'TemplateResponse' object has no attribute 'data'</strong>.
I tried to print the content or context from the TemplateResponse object but it does not retrieve the object date in order to assertEqual (compare) the data.</p>
<p>I also tried to return a response object in the view but still getting the same error.</p>
<pre><code>class PostList(generics.ListAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = JobPostSerializer

    def get_queryset(self):
        user = self.request.user
        if user.is_superuser:
            return JobPost.objects.all()
        else:
            return JobPost.objects.filter(author=user)
</code></pre>
<p>This is the unit test snippet code.</p>
<pre><code>class PostListTestCase(APITestCase):
    def setUp(self):
        self.author = NewUser.objects.create_user(
            email='testuser@testuser.com',
            user_name='test11',
            first_name=&quot;test11&quot;,
            password='Family123!')
        self.superuser = NewUser.objects.create_superuser( email='admin@admin.com',
            user_name='admin',
            first_name=&quot;admin&quot;,
            password='Family123!')
        self.post1 = JobPost.objects.create(title=&quot;Job Post 1&quot;,
            place=&quot;Test Place 1&quot;,
            description=&quot;Test description 1&quot;,
            job_date=&quot;2023-05-20&quot;,
            status=&quot;undone&quot;,
            slug=&quot;job-post-1&quot;,
            reward=1,
            author=self.author,)
        self.post2 = JobPost.objects.create( title=&quot;Job Post 2&quot;,
            place=&quot;Test Place 2&quot;,
            description=&quot;Test description 2&quot;,
            job_date=&quot;2023-05-22&quot;,
            status=&quot;done&quot;,
            slug=&quot;job-post-2&quot;,
            reward=1,
            author=self.superuser,)

    def test_get_queryset_superuser(self):
        self.client.login(email='testuser@testuser.com', password='Family123!')
        response = self.client.get('')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        queryset = JobPost.objects.all()
        serializer = JobPostSerializer(queryset, many=True)
        self.assertEqual(response.data, serializer.data)

    def test_get_queryset_author(self):
        self.client.login(email='admin@admin.com', password='Family123!')
        response = self.client.get('')
        print(response)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        queryset = JobPost.objects.filter(author=self.author)
        serializer = JobPostSerializer(queryset, many=True)
        self.assertEqual(response.data, serializer.data)

</code></pre>
",https://stackoverflow.com/questions/76064325/templateresponse-object-does-not-have-attribute-data-in-unit-test-in-django,"['python', 'django', 'unit-testing']",33,False,0,0
How can i mock database calls without a library?,"<p>i've been trying to wrap my head around unit testing, dependency injection, tdd and all that stuff and i've been stuck on testing functions that make database calls, for example.</p>
<p>Let's say you have a PostgresStore struct that takes in a Database interface, which has a Query() method.</p>
<pre class=""lang-golang prettyprint-override""><code>type PostgresStore struct {
    db Database
}

type Database interface {
    Query(query string, args ...interface{}) (*sql.Rows, error)
}
</code></pre>
<p>And your PostgresStore has a GetPatients method, which calls database query.</p>
<pre class=""lang-golang prettyprint-override""><code>func (p *PostgresStore) GetPatients() ([]Patient, error) {
    rows, err := p.db.Query(&quot;SELECT id, name, age, insurance FROM patients&quot;)
    if err != nil {
        return nil, err
    }
    defer rows.Close()
    items := []Patient{}
    for rows.Next() {
        var i Patient
        if err := rows.Scan(
            &amp;i.ID,
            &amp;i.Name,
            &amp;i.Surname,
            &amp;i.Age,
            &amp;i.InsuranceCompany,
        ); err != nil {
            return nil, err
        }
        items = append(items, i)
    }
    if err := rows.Close(); err != nil {
        return nil, err
    }
    if err := rows.Err(); err != nil {
        return nil, err
    }
    return items, nil
}
</code></pre>
<p>In the real implementation, you would just pass a *sql.DB as Database argument, but how would you guys write a unit test with a fake database struct?</p>
",https://stackoverflow.com/questions/75373245/how-can-i-mock-database-calls-without-a-library,"['database', 'go', 'mocking']",223,True,2,1
Unit Testing of Published object in Swift,"<p>I'm struggling with unit testing of Published object.</p>
<p>I have a viewmodel class as below</p>
<pre><code>class MovieListViewModel {
    @Published public private(set) var arrayOfMovies: [Movie] = []
    @Published private var arraofFavoriteMoviesID: [FavouriteMovieID] = []

     init(request: NetworkServiceProtocol) {
        addSubscribers()
        callServicesInSequence()
    }

    func addSubscribers() {
        $arrayOfMovies.combineLatest($arraofFavoriteMoviesID)
            .debounce(for: 0.0, scheduler: DispatchQueue.main)
            .sink { [weak self] (_, _) in
                self?.fetchWachedMovies()
                self?.fetchTobeWatchedMovies()
                self?.fetchFavoriteMovies()
            }
            .store(in: &amp;subscriptions)
    }

    func callServicesInSequence() {/*..service request...*}
}
</code></pre>
<p>Here addSubscribers() listen for any changes happening in <code>arrayOfMovies</code> or <code>arraofFavoriteMoviesID</code> and works perfectly is the app.</p>
<p>But when I tried to mock and write unit test cases. Any chnages happening in <code>arrayOfMovies</code> or <code>arraofFavoriteMoviesID</code> does not make any effect (addSubscribers's body never get called).</p>
<p>Can any one please guide me what am I doing wrong while writing unit test cases for Combine/Published objects.</p>
<p>Please let me know if more clarification required.</p>
",https://stackoverflow.com/questions/75162546/unit-testing-of-published-object-in-swift,"['ios', 'swift', 'xcode', 'combine']",398,True,1,1
error NS1000: Member InvokeMethodAsync can not be intercepted,"<p>I am trying to unit test my dotnet function that uses dapr client for service-to-service calls. I mocked the dapr Client but am not able to use the <code>InvokeMethodAsync</code> for the test. I get the error</p>
<blockquote>
<p>error NS1000: Member InvokeMethodAsync can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted.</p>
</blockquote>
<p>My service function:</p>
<pre><code>public async Task&lt;TransactionResponse&gt; GetTransactionDetails(Transaction transaction){
    // Fetch transaction details from another service
    var response = await _daprClient.InvokeMethodAsync&lt;TransactionResponse&gt;(HttpMethod.Get, &quot;svc-transactions&quot;, transaction.id);

    return response;
}
</code></pre>
<p>The way I try to mock this in unit test:</p>
<pre><code>// Set up the Dapr client to return the expected response
_daprClient
    .InvokeMethodAsync&lt;TransactionResponse&gt;(HttpMethod.Get, &quot;svc-transactions&quot;, &quot;123&quot;)
    .Returns(transactionResponse);
</code></pre>
<p>I am using xUnit for unit testing along with NSubstitute for mocking in .net 7.0</p>
",https://stackoverflow.com/questions/75729181/error-ns1000-member-invokemethodasync-can-not-be-intercepted,"['asp.net', 'unit-testing', 'testing', 'xunit', 'nsubstitute']",45,True,1,1
Code Instrumentation - code coverage in angular project without unit test,"<p>I have angular project and using Karma and Jasmine for Unit testing to generate the code coverage. I am now trying to my instrument code so that we can get the coverage report while manual testing how much code is covered.
I am not getting any references for integrating it in angular project.</p>
<p>I explored Instanbul provides the feature to code instrument with using nyc and babel but could not figured out how can i integrate it in existing Angular 14 project.
Please help me.</p>
",https://stackoverflow.com/questions/76195187/code-instrumentation-code-coverage-in-angular-project-without-unit-test,"['angular', 'code-coverage', 'instrumentation', 'istanbul']",31,False,1,0
Ktor testing routes with &#39;authenticate(){}&#39;,"<p>What is the appropriate way of unit testing such routes?</p>
<pre class=""lang-kotlin prettyprint-override""><code>fun Application.install() {
    routing {
        route(&quot;point&quot;) {
            authenticate(AUTH_SESSION) {
                post(&quot;/test&quot;) { testController.test(context) }
            }
        }
    }
}
</code></pre>
<p>The problem is such routes require auth info. This code results in 401 error:</p>
<pre class=""lang-kotlin prettyprint-override""><code>@Test
fun `test auth route`() = testApplication {
    val client = client()
    client.post(&quot;/point/test&quot;)
}
</code></pre>
<p>I use GoogleOneTap auth for a mobile application. From GoogleOneTap jwt token I generate User session with a Bearer. That session expires after some time.
So, such a test user requires manual auth each time session expires? If so, it's not appropriate for a CI.</p>
<p>Should I implement a simple auth with user-password and call auth before each call under <code>authenticate(AUTH_SESSION)</code>?</p>
",https://stackoverflow.com/questions/75498620/ktor-testing-routes-with-authenticate,"['authentication', 'testing', 'ktor']",114,False,1,0
Unit testing service method in Spring Boot,"<p>I have been doing unit testing with JUnit 5 and Mockito for the following code that I am going to show you, but it is not working correctly. I want to evaluate the successful case.</p>
<pre><code>public Maybe &lt; MyResponse&gt; generate(String numberValue) {
  return Maybe.just(numberValue)
        .filter(number -&gt; number.length() == Constants.REQUEST_REQUIRED) //R_R = 16
        .flatMap(number -&gt; MyUtils.generate())
        .map(MyMapper::createResponse)
        .switchIfEmpty(Maybe.error(MyExceptioManager.throwException400(...)));
}
</code></pre>
<p>I tried converting the static methods to instance methods and then invoked them with @Mock, but it didn't work. How can I do this?</p>
<p>I did this:</p>
<pre><code>@Test
void generate() {
    String numberValue = &quot;1234567891234567&quot;;
    // when(myUtils.generate()).thenReturn(any()); 
    when(numberValue.length()).thenReturn(eq(16));
    when(myMapper.createResponse(anyString())).thenReturn(any(MyResponse.class));

    myService.generate(numberValue )
             .test()
             .assertNoErrors()
             .assertComplete()
             .assertValue(myResponse -&gt; myResponse.getCode().equals(&quot;1234&quot;));
}
</code></pre>
<p>error:</p>
<blockquote>
<p>org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);</p>
</blockquote>
",https://stackoverflow.com/questions/75857012/unit-testing-service-method-in-spring-boot,"['java', 'spring', 'mockito', 'rx-java', 'junit5']",70,False,0,1
Reinitialization of dataclass object does not reinitialize nested dataclass objects,"<p>I'm having trouble reinitializing nested dataclass object.</p>
<p>I have 2 nested dataclasses set up like so:</p>
<pre><code>from dataclasses import dataclass, field
from typing import Dict

@dataclass
class MyNestedClass():
    field1: str = &quot;&quot;
    field2: int = 0
    field3: Dict[str, float] = field(default_factory=dict)

@dataclass
class MyClass():
    field1: str = &quot;&quot;
    field2: int = 0
    field3: Dict[str, float] = field(default_factory=dict)
    field4: MyNestedClass = MyNestedClass()
</code></pre>
<p>As part of a unit testing procedure, I would like to initialize a new <code>MyClass</code> object and then run a test.  However, I've noticed something odd.  When I reinitialize my <code>MyClass</code> object, it somehow remembers the contents of field4.  For example:</p>
<pre><code>my_obj = MyClass()
print(my_obj)

my_obj.field2 = 1
my_obj.field3 = {'something': 2.5}
my_obj.field4.field1 = &quot;B&quot;
my_obj.field4.field2 = 2
my_obj.field4.field3 = {'something else': 3.14}
print(my_obj)

my_obj = MyClass()
print(my_obj)
</code></pre>
<p>yields</p>
<pre><code>MyClass(field1='', field2=0, field3={}, field4=MyNestedClass(field1='', field2=0, field3={}))
MyClass(field1='', field2=1, field3={'something': 2.5}, field4=MyNestedClass(field1='B', field2=2, field3={'something else': 3.14}))
MyClass(field1='', field2=0, field3={}, field4=MyNestedClass(field1='B', field2=2, field3={'something else': 3.14}))
</code></pre>
<p>does the autogenerated dataclass constructor for <code>MyClass</code> not call the constructor for <code>MyNestedClass</code> by default?  If not, what is it doing instead and what is the correct way to do this?</p>
",https://stackoverflow.com/questions/76335101/reinitialization-of-dataclass-object-does-not-reinitialize-nested-dataclass-obje,"['python', 'nested', 'initialization', 'reinitialization']",26,True,0,1
"ghttp multiple ressponses for same method, path","<p>I am unit-testing client code using ghttp (gomega) where I have N paths, path1, path2 to pathN. I use server.RouteToHandler().</p>
<p>I also have a requirement that 2nd time the same method and path is called, I need to have a different response.
I could have used AppendHandlers(), but then the order might also not be the same every iteration.</p>
<p>Calls could be in the following order</p>
<ol>
<li>path1, path2, path3, path1, path2, path3</li>
<li>path1, path1, path2, path3, path2, path3</li>
</ol>
<pre><code>server.RouteToHandler(&quot;POST&quot;, path1,
        ghttp.CombineHandlers(
            ghttp.VerifyRequest(&quot;POST&quot;, path1),
            ghttp.RespondWithJSONEncoded(httpStatusCreatedCode, createResp1),
        ))
server.RouteToHandler(&quot;POST&quot;, path2,
        ghttp.CombineHandlers(
            ghttp.VerifyRequest(&quot;POST&quot;, path2),
            ghttp.RespondWithJSONEncoded(httpStatusCreatedCode, createResp2),
        ))
</code></pre>
<p>How do I achieve this?</p>
<p>Thanks,
/M</p>
",https://stackoverflow.com/questions/75170155/ghttp-multiple-ressponses-for-same-method-path,"['go', 'gomega']",22,False,0,0
Define pyspark table with column type as timestamp,"<p>I need to create a PySpark dataframe for some unit testing. One of the columns in the dataframe needs to be of the type <code>TimestampType</code>. I have the following code to define the dataframe:</p>
<pre><code>spark = (SparkSession
            .builder
            .master(&quot;local[*]&quot;)
            .appName(&quot;Unit-tests&quot;)
            .getOrCreate())

data = [
            (&quot;2023-04-25 00:00:00&quot;, &quot;A&quot;, 100.5),
            (&quot;2023-04-26 00:00:00&quot;, &quot;A&quot;, 110.0),
            (&quot;2023-04-28 00:00:00&quot;, &quot;A&quot;, 105.0),
            (&quot;2023-04-27 00:00:00&quot;, &quot;B&quot;, 50.5),
            (&quot;2023-04-29 00:00:00&quot;, &quot;B&quot;, 55.5),
        ]

schema = StructType([
            StructField(&quot;time&quot;, TimestampType(), True), \
            StructField(&quot;id&quot;, StringType(), True), \
            StructField(&quot;value&quot;, DoubleType(), True)
        ])

df = spark.createDataFrame(
            data=data,
            schema=schema
        )
</code></pre>
<p>However, this gives me an TypeError:
<code>field time: TimestampType() can not accept object '2023-04-25 00:00:00' in type</code>.</p>
<p>I know a work around which is to initially define the <code>time</code> column as a <code>StringType</code> and then afterwards cast it to a <code>TimestampType</code> by adding this line of code:</p>
<p><code>df.withColumn(&quot;time&quot;, col(&quot;time&quot;).cast(TimestampType()))</code></p>
<p>But this seems like a rather cumbersome way of doing it. How can I define it directly in the schema?</p>
",https://stackoverflow.com/questions/76129060/define-pyspark-table-with-column-type-as-timestamp,"['python', 'pyspark']",29,True,0,1
how to check which unit test has covered specific line of code in visual studio,"<p>How to check which unit test has covered specific line of code in visual studio</p>
<p>e.g.</p>
<p>My solution has multiple class libraries.</p>
<p>I am analyzing code coverage for all tests from Test menu in VS.</p>
<p>For some methods, it is showing green, which means that code is covered in unit testing.</p>
<pre><code>public void someclassMethod()
{
  _service.Method();
}
</code></pre>
<p>I want to check unit tests for this _service.Method() (which is marked as green means covered code)</p>
<p>Is there any way to find out which code is covered in which unit test project?</p>
",https://stackoverflow.com/questions/75850623/how-to-check-which-unit-test-has-covered-specific-line-of-code-in-visual-studio,"['.net', 'visual-studio', 'unit-testing', 'asp.net-core', 'mstest']",116,True,0,1
How to created Unit testing report in the Scalatest?,"<p>I have created unit test for a Scala application in Databricks notebook . My Unit test code will be like below</p>
<pre><code>class unitTestClass extends Funsuite
</code></pre>
<p><code>{</code>
<code>test (&quot;Test1 returns expected output&quot;)</code>
<code>{..code..}</code>
<code>test (&quot;Test2 returns expected output&quot;)</code>
<code>{..code..}</code>
<code>}</code></p>
<p>and I run the test by below command in Databricks
<code>(new unitTestClass).execute()</code></p>
<p>After executing ,I can see the logs for each test in console.</p>
<p>I am trying get details like the status of the Unit testing like PASS(if all the tests passed)/FAIL(if any of the tests failed) and no of tests passed /no of tests failed like summary</p>
<p>What can I do? Please suggest</p>
",https://stackoverflow.com/questions/75398278/how-to-created-unit-testing-report-in-the-scalatest,"['scala', 'databricks', 'scalatest']",45,False,0,0
gmock/gtest giving error while compiling the code,"<p>I am new to gtest/gmock. I am trying to implement unit testing for C++ Program.but when i try to compile it. i got linking error with gmock. this specific error is related <code>testing::internal::GetCurrentOsStackTraceExceptTop</code>.</p>
<p><strong>Installation of gtest/gmock:</strong><br />
Step 1: <code>sudo apt-get install libgtest-dev</code><br />
Step 2: download the git repo of google test from here: <a href=""https://github.com/google/googletest"" rel=""nofollow noreferrer"">https://github.com/google/googletest</a><br />
Step 3: sudo apt install cmake<br />
Step 4: run these commands {~googletest$}</p>
<pre><code>sudo cmake CMakeLists.txt  
sudo make 
</code></pre>
<p>Step 5: copy files in /usr/lib<br />
Step 6: copy gtest/gmock include folder into /usr/local/include</p>
<pre><code> version of the Google Test library that is installed on my system is 1.10.0-2. 
</code></pre>
<p>test.cpp</p>
<pre><code>#include &lt;gmock/gmock.h&gt;
#include &lt;gtest/gtest.h&gt;
#include &lt;gmock/gmock-actions.h&gt;
#include &lt;iostream&gt;
#include &quot;timeEvent.h&quot;

using ::testing::_;
using ::testing::Return;

class MockStat {
 public:
  MOCK_METHOD2(stat, int(const char* pathname, struct stat* buf));
};

TEST(MyTest, PositiveCase) {
  MockStat mock_stat;
  struct stat fileStat;
  fileStat.st_mtime = 111;
  fileStat.st_ctime = 222;
  
  EXPECT_CALL(mock_stat, stat(&quot;/var/lib/systemd/timesync/clock&quot;, &amp;fileStat))
      .WillOnce(Return(0));
  
  auto latest_clock = get_latest_clock_entry();
  EXPECT_EQ(latest_clock.tv_sec, 111);
  EXPECT_EQ(latest_clock.tv_nsec, 0);
}
</code></pre>
<p>compile: <code>g++ test.cpp library.cpp -lgtest -lgtest_main -lpthread -lboost_thread -pthread -lboost_filesystem -lgtest -lgmock -lgmock_main</code></p>
<p>Error:</p>
<pre><code>g++ update.cpp library.cpp -lgtest -lgtest_main -lpthread -lboost_thread -pthread -lboost_filesystem -lgtest -lgmock -lgmock_main -lstdc++
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib/libgmock.a(gmock-all.cc.o): in function `testing::internal::Log(testing::internal::LogSeverity, std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const&amp;, int)':
gmock-all.cc:(.text+0x121a): undefined reference to `testing::internal::GetCurrentOsStackTraceExceptTop[abi:cxx11](int)'
collect2: error: ld returned 1 exit status
</code></pre>
",https://stackoverflow.com/questions/75247534/gmock-gtest-giving-error-while-compiling-the-code,"['c++', 'unit-testing', 'googletest', 'googlemock']",450,True,0,3
Mockery/PhpUnit: Mocking a response from a parent method of the same name,"<p>I have a situation like the example classes below where I have a child class that overrides a parent method. In certain situations it will return the original result from the parent class.</p>
<p>How do I go about unit testing this in Mockery?</p>
<p>I was going to create a partial and then define the result from the parent call (<code>shouldRecieve('getName')-&gt;andReturn('parent')</code>), but obviously that then mocks out the method I want to test.</p>
<p>Is there a way to mock the result of the parent implementation of the method?</p>
<pre class=""lang-php prettyprint-override""><code>class Parent {
    public function getName() {
        /*** Lots of other complicated calls to other 
             services that I don't want to mock. 
        ***/

        return 'Parent';
    }
}

class Child {
    public function getName(bool $someParameter) {
        if ($someParameter) {
            return 'child';
        }

        return parent::getName();
    }
</code></pre>
",https://stackoverflow.com/questions/75071049/mockery-phpunit-mocking-a-response-from-a-parent-method-of-the-same-name,"['phpunit', 'mockery']",129,False,0,1
How to mock an IEnumerable that needs to be casted via LINQ (by .Cast&lt;T&gt;)?,"<p>I have to deal with a third-party legacy interface that extends <code>IEnumerable</code>:</p>
<pre class=""lang-cs prettyprint-override""><code>public interface IFoo : IEnumerable
{
    public IBar this[int index] { get; }
    public int Count { get; }
}
</code></pre>
<p>In my code I do the following:</p>
<pre class=""lang-cs prettyprint-override""><code>IFoo foo;
foo.Cast&lt;IBar&gt;().Select( // do something...
</code></pre>
<p>During unit testing, I have to mock the interfaces <code>IFoo</code> and <code>IBar</code> (via FakeItEasy):</p>
<pre class=""lang-cs prettyprint-override""><code>[Fact]
public void Test()
{
    var enumerator = A.Fake&lt;IEnumerator&gt;();
    A.CallTo(() =&gt; enumerator.MoveNext()).ReturnsNextFromSequence(false, true);

    var foo = A.Fake&lt;IFoo&gt;();
    var bar = A.Fake&lt;IBar&gt;();

    A.CallTo(() =&gt; foo.Count).Returns(1);
    A.CallTo(() =&gt; foo.GetEnumerator()).Returns(enumerator);
    A.CallTo(() =&gt; foo[An&lt;int&gt;.Ignored]).Returns(bar);

    _output.WriteLine(foo.Count); // 1
    _output.WriteLine(foo[0]);    // Faked IBar

    _output.WriteLine(foo.Cast&lt;IBar&gt;().ToList().Count); // 0
    _output.WriteLine(foo.Cast&lt;IBar&gt;().ToList()[0]);    // System.ArgumentOutOfRangeException
}
</code></pre>
<p>I also tried the following option, but without success:</p>
<pre class=""lang-cs prettyprint-override""><code>[Fact]
public void Test()
{
    var foo = A.Fake&lt;IFoo&gt;();
    var bar = A.Fake&lt;IBar&gt;();
    var barList = new List&lt;IBar&gt; {bar};

    A.CallTo(() =&gt; foo.Count).Returns(barList.Count);
    A.CallTo(() =&gt; foo.GetEnumerator()).Returns(barList.GetEnumerator());
    A.CallTo(() =&gt; foo[An&lt;int&gt;.Ignored]).Returns(bar);

    _output.WriteLine(foo.Count); // 1
    _output.WriteLine(foo[0]);    // Faked IBar

    _output.WriteLine(foo.Cast&lt;IBar&gt;().ToList().Count); // 0
    _output.WriteLine(foo.Cast&lt;IBar&gt;().ToList()[0]);    // System.ArgumentOutOfRangeException
}
</code></pre>
<p>I don't understand what the problem is. Why is the collection being erased? Why does this happen exactly when called <code>.Cast&lt;T&gt;()</code>? As far as I know, there are no such problems with other LINQ methods. Is it possible to solve this?</p>
<p>Thank you in advance!</p>
",https://stackoverflow.com/questions/75726321/how-to-mock-an-ienumerable-that-needs-to-be-casted-via-linq-by-castt,"['c#', '.net', 'unit-testing', 'mocking', 'ienumerable']",44,False,0,0
import static org.assertj.core.api.Assertions.assertThat not suggested by IntelliJ,"<p>Newbie, big project, copy/paste unit testing task.
Using IntelliJ Ultimate, when trying to import assertThat(), I get to choose only between:</p>
<pre><code>import static com.mysema.commons.lang.Assert.assertThat;
</code></pre>
<p>or</p>
<pre><code>import static org.hamcrest.MatcherAssert.assertThat;

</code></pre>
<p>But what i need as an option =&gt;</p>
<pre><code>import static org.assertj.core.api.Assertions.assertThat;
</code></pre>
<p>Co-workers have no problem with imports on the same project on their machines.
No error, when i just copy/paste import from another class. But IntelliJ doesn't suggest imports I need!
Any ideas?</p>
<p>Tried to:</p>
<ol>
<li>invalidate caches</li>
<li>restore default settings</li>
<li>reload all gradle projects</li>
<li>delete .gradle and .idea folders</li>
<li>clean/build project directory</li>
<li>restart pc...
No result</li>
</ol>
",https://stackoverflow.com/questions/74992035/import-static-org-assertj-core-api-assertions-assertthat-not-suggested-by-intell,"['unit-testing', 'intellij-idea', 'assertj']",400,True,1,1
Mock loading a dataframe during testing the function,"<p>I am fairy new to unit testing in Python and have been using pytest. I have been using fixtures for some unit tests but there is a simple function (see below) that I want to test which has me baffled.</p>
<p>It simply reads parquet file from s3 and as there are duplicate rows in the source data it dedupes on a given list of columns.</p>
<p>So in the unit test I just want to mock loading the data from s3 as I dont want to perform this read. Any pointers on how to approach this?</p>
<pre><code>def load_parquet(bucket_name: str,
           bucket_prefix: str,
           folder: str,
           columns_required: list,
           log_date_start: date,
           log_date_end=date):
'''Function to load event data for given date

Args:
    bucket_name: S3 bucket
    bucket_prefix: S3 bucket input path to load parquet
    folder: S3 folder
    log_date_start: Start of logdate
    log_date_end: End of logdate

Returns:
    Dataframe with required columns and deduped
'''


s3_path = f's3://{bucket_name}/{bucket_prefix}/{folder}/'
df = wr.s3.read_parquet(path=s3_path,
                            columns=columns_required,
                            partition_filter=lambda x: log_date_start &lt;= x[&quot;date&quot;] &lt;= log_date_end,
                            dataset=True,
                            use_threads=True)

# Partition filter creates unnecessary columns and drop any duplicates
df_deduped = df[columns_required].drop_duplicates()

return df_deduped
</code></pre>
",https://stackoverflow.com/questions/75349313/mock-loading-a-dataframe-during-testing-the-function,"['python', 'unit-testing', 'mocking', 'pytest']",199,False,1,0
Azure DevOps API issue when completing new pull request,"<p>I'm trying to create a new ADO pull request and complete it immediately (for unit testing purposes) but there seems to be an issue where if I try to complete it right after it was created, it simply doesn't complete it.</p>
<p>On the other hand, if I add some timeout between the PR creation and completion (the commented line in the code below) it does work.</p>
<p>Any idea why this could be happening and how to resolve it?</p>
<p>This is an example code of what I've been testing.</p>
<pre><code>// CREATE PR
const prRequestUrl = `https://system:${personalAccessToken}@dev.azure.com/${organization}/${project}/_apis/git/repositories/${repo}/pullRequests?api-version=7.0`;
const prRequestBody = {
  sourceRefName: 'refs/heads/source',
  targetRefName: 'refs/heads/target',
  title: 'PR title',
  description: 'PR description',
};
const prData = (await axios.post(prRequestUrl, prRequestBody)).data;

// This fixes the issue
// await new Promise((resolve) =&gt; setTimeout(resolve, 1000));

// COMPLETE PR
const approvePrRequestUrl = `https://system:${personalAccessToken}@dev.azure.com/${organization}/${project}/_apis/git/repositories/${repo}/pullRequests/${prData.pullRequestId}/?api-version=7.0`;
const approvePrRequestBody = {
  lastMergeSourceCommit: prData.lastMergeSourceCommit,
  completionOptions: {
    deleteSourceBranch: false,
  },
  status: 'completed',
};
await axios.patch(
  approvePrRequestUrl,
  approvePrRequestBody
);
</code></pre>
",https://stackoverflow.com/questions/75950105/azure-devops-api-issue-when-completing-new-pull-request,"['javascript', 'typescript', 'git', 'azure-devops', 'azure-devops-rest-api']",92,True,1,2
Mocking os.path.exists and os.makedirs returning AssertionError,"<p>I have a function like below.</p>
<pre><code># in retrieve_data.py

import os

def create_output_csv_file_path_and_name(output_folder='outputs') -&gt; str:
    &quot;&quot;&quot;
    Creates an output folder in the project root if it doesn't already exist.
    Then returns the path and name of the output CSV file, which will be used
    to write the data.
    &quot;&quot;&quot;
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
        logging.info(f&quot;New folder created for output file: &quot; f&quot;{output_folder}&quot;)

    return os.path.join(output_folder, 'results.csv')
</code></pre>
<p>I also created a unit test file like below.</p>
<pre><code># in test_retrieve_data.py

class OutputCSVFilePathAndNameCreationTest(unittest.TestCase):

    @patch('path.to.retrieve_data.os.path.exists')
    @patch('path.to.retrieve_data.os.makedirs')
    def test_create_output_csv_file_path_and_name_calls_exists_and_makedirs_once_when_output_folder_is_not_created_yet(
            self,
            os_path_exists_mock,
            os_makedirs_mock
    ):
        os_path_exists_mock.return_value = False
        retrieve_cradle_profile_details.create_output_csv_file_path_and_name()
        os_path_exists_mock.assert_called_once()
        os_makedirs_mock.assert_called_once()
</code></pre>
<p>But when I run the above unit test, I get the following error.</p>
<pre><code>def assert_called_once(self):
    &quot;&quot;&quot;assert that the mock was called only once.
    &quot;&quot;&quot;
    if not self.call_count == 1:
        msg = (&quot;Expected '%s' to have been called once. Called %s times.%s&quot;
               % (self._mock_name or 'mock',
                  self.call_count,
                  self._calls_repr()))
         raise AssertionError(msg)
         AssertionError: Expected 'makedirs' to have been called once. Called 0 times.
</code></pre>
<p>I tried poking around with <code>pdb.set_trace()</code> in <code>create_output_csv_file_path_and_name</code> method and I'm sure it is receiving a mocked object for <code>os.path.exists()</code>, but the code never go pasts that <code>os.path.exists(output_folder)</code> check (<code>output_folder</code> was already created in the program folder but I do not use it for unit testing purpose and want to keep it alone). What could I possibly be doing wrong here to mock <code>os.path.exists()</code> and <code>os.makedirs()</code>? Thank you in advance for your answers!</p>
",https://stackoverflow.com/questions/75090518/mocking-os-path-exists-and-os-makedirs-returning-assertionerror,"['python', 'python-3.x', 'python-unittest', 'python-mock']",179,True,0,1
Angular Unit Test: How to pass FormGroupDirective in a function?,"<p>I am trying to unit test a function which is taking a parameter of type <code>FormGroupDirective</code>. I am able to test all logic but cannot understand what should be taken as parameter to call the <code>resetForm()</code> function. Below is my code which I am testing.</p>
<pre class=""lang-html prettyprint-override""><code>&lt;form [formGroup]=&quot;logForm&quot; #formDirective=&quot;ngForm&quot; (submit)=&quot;onSave(formDirective)&quot;&gt;...&lt;/form&gt;
</code></pre>
<pre class=""lang-js prettyprint-override""><code>onSave(formDirective: FormGroupDirective) {
  this._http.save(this.logForm.value).subscribe({
    next: response =&gt; {
      this._notification.show({ message: response.message, action: 'SUCCESS', panelClass: 'success' });
      formDirective.resetForm();
      this.logForm.reset();
      this.trailerHeading = 'Trailer';
      this.showAllTrailers = false;
      this.trailerList = [];
    }
  });
}
</code></pre>
<p>While unit testing I've passed <code>null</code> as value while calling <code>onSave(...)</code> method. Which is correctly throwing error while executing <code>formDirective.resetForm()</code>.</p>
<p>The test case that I wrote is:</p>
<pre class=""lang-js prettyprint-override""><code>import { HttpClientTestingModule } from &quot;@angular/common/http/testing&quot;;
import { CUSTOM_ELEMENTS_SCHEMA } from &quot;@angular/core&quot;;
import { ComponentFixture, TestBed, waitForAsync } from &quot;@angular/core/testing&quot;;
import { FormsModule, ReactiveFormsModule } from &quot;@angular/forms&quot;;
import { BrowserAnimationsModule } from &quot;@angular/platform-browser/animations&quot;;
import { RouterTestingModule } from &quot;@angular/router/testing&quot;;
import { HttpClientService } from &quot;@service/http-client.service&quot;;
import { of } from &quot;rxjs&quot;;
import { MaterialModule } from &quot;src/app/material/material.module&quot;;
import { TrailerLogComponent } from &quot;./trailer-log.component&quot;;

describe('TrailerLogComponent', () =&gt; {

    let component: TrailerLogComponent, fixture: ComponentFixture&lt;TrailerLogComponent&gt;,
        _httpService: HttpClientService;

    beforeEach(waitForAsync(() =&gt; {
        TestBed.configureTestingModule({
            imports: [MaterialModule, RouterTestingModule, FormsModule, ReactiveFormsModule, HttpClientTestingModule, BrowserAnimationsModule],
            declarations: [TrailerLogComponent],
            providers: [HttpClientService],
            schemas: [CUSTOM_ELEMENTS_SCHEMA],
            teardown: { destroyAfterEach: false }
        }).compileComponents();
        _httpService = TestBed.inject(HttpClientService);
        fixture = TestBed.createComponent(TrailerLogComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    }));

    it('should save the trailer log form', () =&gt; {
        const response: { message: string } = { message: '' };
        spyOn(_httpService, 'save').and.returnValue(of(response));
        component.onSave(null); // what should I pass here??
        fixture.detectChanges();
        expect(component.trailerHeading).toEqual('Trailer');
        expect(component.showAllTrailers).toBeFalsy();
        expect(component.trailerList.length).toEqual(0);
    });
});
</code></pre>
<p>The error is getting thrown when <code>component.onSave(null)</code> is called as I am passing null.</p>
<p>What should I pass here instead of NULL to make it work properly?</p>
",https://stackoverflow.com/questions/75812349/angular-unit-test-how-to-pass-formgroupdirective-in-a-function,"['angular', 'typescript', 'unit-testing', 'jasmine', 'angular-reactive-forms']",82,True,0,2
How to mock appSelector with dummy data in React redux-toolkit tests,"<p>I have the following react function component:</p>
<pre class=""lang-js prettyprint-override""><code>
const AssetsPage = () =&gt; {

    const [filteredAssets, setFilteredAssets] = useState&lt;Asset[]&gt;([]);
    const assetsState = useAppSelector(selectAssets);
    ...
    
    useEffect(() =&gt; {
        setFilteredAssets(
            assetsState.assets
        );
    }, [assetsState.assets])

    useEffect(() =&gt; {
        store.dispatch(fetchAssetsAsync(null));
    }, [])

    
    const columns: GridColDef[] = [
        ...some column definitions...
    ];

  

    return (
        &lt;&gt;
            &lt;Typography variant=&quot;h2&quot; ml={2}&gt;
                {t(&quot;Asset.Title&quot;)}
            &lt;/Typography&gt;
            &lt;DataTable
              rows={filteredAssets}
              columns={columns}
              rowId=&quot;globalId&quot;
            /&gt;
        &lt;/&gt;
    )
}

export default AssetsPage
</code></pre>
<p>And the corresponding slice:</p>
<pre class=""lang-js prettyprint-override""><code>import {Asset} from &quot;../../models/Asset&quot;;
import {createAsyncThunkWithErrorHandling} from &quot;../../utils/thunkHelper&quot;;
import {createSlice} from &quot;@reduxjs/toolkit&quot;;
import {RootState} from &quot;../../app/store&quot;;
import {createAsset, deleteAsset, getAssets, updateAsset} from &quot;../../api/assets&quot;;

const initialState = {
    isLoaded: false,
    assets: [] as Asset[],
}

...

export const fetchAssetsAsync = createAsyncThunkWithErrorHandling(
    &quot;assets/fetch&quot;,
    async (payload: string) =&gt; {
        return await getAssets(payload);
    }
)
...

export const oeeAssetsSlice = createSlice({
    name: &quot;assets&quot;,
    initialState,
    reducers: {},
    extraReducers: (builder) =&gt; {
        builder.addCase(fetchAssetsAsync.fulfilled, (state, action) =&gt; {
            state.isLoaded = true;
            state.assets = [
                ...action.payload,
            ];
        });
       ...
    }

})
export const selectAssets = (state: RootState) =&gt; state.assets;


export default oeeAssetsSlice.reducer;

</code></pre>
<p>This works just fine, it loads data from the backend (or, if I replace the <code>fetchAssetsAsync</code> implementation with static data, it loads it properly.)</p>
<p>I am trying to do some unit testing. Rendering the empty table works fine: but I cannot inject data to the <code>assetsState</code> no matter how I try.</p>
<pre class=""lang-js prettyprint-override""><code>import {fireEvent, render, screen, waitFor} from &quot;@testing-library/react&quot;;
import {Provider} from &quot;react-redux&quot;;
import {RootState, store} from &quot;../../../app/store&quot;;
import AssetsPage from &quot;./AssetsPage&quot;;
import {createTheme} from &quot;@mui/material/styles&quot;;
import {ThemeOptions} from &quot;../../ThemeOptions/ThemeOptions&quot;;
import {ThemeProvider} from &quot;@mui/material&quot;;
import oeeAssetsReducer, {selectAssets} from &quot;../../../features/assets/oeeAssetsSlice&quot;;
import {useAppSelector} from &quot;../../../app/hooks&quot;;
import appReducer from &quot;../../../features/app/appSlice&quot;;
import userReducer from &quot;../../../features/user/userSlice&quot;;

describe(&quot;AssetListPage&quot;, () =&gt; {
    const theme = createTheme(ThemeOptions);

    // This test works fine.
    test(&quot;renders the empty component&quot;, async () =&gt; {
        render(
            &lt;ThemeProvider theme={theme}&gt;
                &lt;Provider store={store}&gt;
                    &lt;AssetsPage/&gt;
                &lt;/Provider&gt;
            &lt;/ThemeProvider&gt;
        );
        expect(screen.getByText(&quot;No rows&quot;)).toBeInTheDocument();
    });


    // todo: this doesnt work.
   const asset = {
        globalId: &quot;asset-1&quot;,
        description: &quot;test asset&quot;,
        businessUnitCode: &quot;bu-1&quot;,
        localId: &quot;123&quot;,
        enabledFlag: 1,
    };

    jest.mock(&quot;../../../app/hooks&quot;, () =&gt; ({
        useAppSelector: (selectAssets: any) =&gt; ({
            assetsState: {
                isLoaded: true,
                assets: [asset]
            }
        })
    }));


    jest.mock(&quot;react-i18next&quot;, () =&gt; ({
        useTranslation: () =&gt; ({
            t: (key: string) =&gt; key
        })
    }));

    test(&quot;renders the component with one data line&quot;, async () =&gt; {

       render(&lt;ThemeProvider theme={theme}&gt;
            &lt;Provider store={store}&gt;
                &lt;AssetsPage/&gt;
            &lt;/Provider&gt;
        &lt;/ThemeProvider&gt;
        );

        render(
            &lt;ThemeProvider theme={theme}&gt;
                &lt;Provider store={store}&gt;
                    &lt;AssetsPage/&gt;
                &lt;/Provider&gt;
            &lt;/ThemeProvider&gt;
        );

        expect(screen.getByText(&quot;Asset.GlobalAssetId&quot;)).toBeInTheDocument();
        expect(screen.getByText(&quot;Asset.Description&quot;)).toBeInTheDocument();
        expect(screen.getByText(&quot;Asset.BusinessUnit&quot;)).toBeInTheDocument();
        expect(screen.getByText(&quot;Asset.LocalId&quot;)).toBeInTheDocument();  // it renders the &quot;empty table&quot; instead
        expect(screen.getByText(&quot;Asset.Disable&quot;)).toBeInTheDocument();
        expect(screen.getByText(&quot;Asset.Actions&quot;)).toBeInTheDocument();
    })
  
});

</code></pre>
<p>The test always renders a table without any data. What am I missing here? I cannot install Enzyme, tried feeding this to chatGPT, but nothing worked so far.</p>
",https://stackoverflow.com/questions/75627242/how-to-mock-appselector-with-dummy-data-in-react-redux-toolkit-tests,"['reactjs', 'typescript', 'redux-toolkit']",95,True,0,1
Swift UI Application falling on Unit test cases,"<p>I create the app into Swift UI . I wrote the Unit testing case . I have local json into test folder . I am expecting to pass but it showing it found the record 0 instead of returning total record . Here is the error message ..</p>
<p><strong>testTotalCountWithSuccess(): XCTAssertEqual failed: (&quot;0&quot;) is not equal to (&quot;40&quot;) - Total record is  matched</strong>
Here is code for Content view ..</p>
<pre><code>import SwiftUI

struct ContentView: View {

    @EnvironmentObject private var viewModel: FruitListViewModel
    @State private var filteredFruits: [Fruits] = []
    @State var searchText = &quot;&quot;

    var body: some View {
        NavigationView {
            List {
                ForEach(fruits) { fruit in
                    NavigationLink(destination: FruitDetailsView(fruit: fruit)) {
                        RowView(name: fruit.name, genus: fruit.genus, family: fruit.family)
                    }
                }
            }
            .searchable(text: $searchText)
            .onChange(of: searchText, perform: performSearch)
            .task {
                viewModel.fetchFruit()
            }
            .navigationTitle(&quot;Fruits List&quot;)
        }

        .onAppear {

            viewModel.fetchFruit()
        }
    }
    private func performSearch(keyword: String) {
        filteredFruits = viewModel.fruits.filter { fruit in
        fruit.name.contains(keyword)
        }
    }
    private var fruits: [Fruits] {
        filteredFruits.isEmpty ? viewModel.fruits: filteredFruits
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code></pre>
<p>Here is the view model ..</p>
<pre><code>protocol FruitListViewModelType {
    func fetchFruit()
}

class FruitListViewModel: FruitListViewModelType, ObservableObject {

    private let service:Service!
    @Published private(set) var fruits = [Fruits]()

    init(service:Service = ServiceImpl()) {
        self.service = service
    }

    func fetchFruit() {
        let client = ServiceClient(baseUrl:EndPoints.baseUrl.rawValue, path:Path.cakeList.rawValue, params:&quot;&quot;, method:&quot;get&quot;)

        service.fetchData(client:client, type:[Fruits].self) { [weak self] (result)  in
            switch result {
            case .success(let result):
                DispatchQueue.main.async {
                    self?.fruits = result
                }

            case .failure(let error):
                DispatchQueue.main.async {
                    print(error.localizedDescription)
                    self?.fruits = []
                }
            }
        }
    }
}
</code></pre>
<p>Here is the my Mock api class .</p>
<pre><code>import Foundation
@testable import FruitsDemoSwiftUI

class MockService: Service, JsonDecodable {
    
    var responseFileName = &quot;&quot;

    func fetchData&lt;T&gt;(client: ServiceClient, type: T.Type, completionHandler: @escaping Completion&lt;T&gt;) where T : Decodable, T : Encodable {
        // Obtain Reference to Bundle
        let bundle = Bundle(for:MockService.self)

        guard let url = bundle.url(forResource:responseFileName, withExtension:&quot;json&quot;),
              let data = try? Data(contentsOf: url),
              let output = decode(input:data, type:T.self)
        else {
            completionHandler(.failure(ServiceError.parsinFailed(message:&quot;Failed to get response&quot;)))
            return
        }
        completionHandler(.success(output))
    }
}
</code></pre>
<p>Here is the unit test code ..</p>
<pre><code>import XCTest
@testable import FruitsDemoSwiftUI

final class FruitsDemoSwiftUITests: XCTestCase {

    var mockService: MockService!
    var viewModel: FruitListViewModel!

    override func setUp() {
        mockService = MockService()
        viewModel = FruitListViewModel(service: mockService)
    }

    func testTotalCountWithSuccess() {
        mockService.responseFileName = &quot;FruitSuccessResponse&quot;
        viewModel.fetchFruit()
        let resultCount = viewModel.fruits.count
        XCTAssertEqual(resultCount ,40, &quot;Total record is  matched&quot;)// it shroud return 40 record but it return 0.
    }
}
</code></pre>
<p>Here is the link for Json ..</p>
<p><strong><a href=""https://fruityvice.com/api/fruit/all"" rel=""nofollow noreferrer"">https://fruityvice.com/api/fruit/all</a></strong></p>
<p>Here is the screenshot ..
<a href=""https://i.stack.imgur.com/Ks0Ku.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Ks0Ku.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/75663308/swift-ui-application-falling-on-unit-test-cases,"['swift', 'unit-testing', 'swiftui', 'mvvm']",111,True,0,1
detect unit tests that took long time to respond,"<p>i'm new to unit testing , i have a lot of unit tests, how can i find tests that took long time to respond ?</p>
<p>i try this:</p>
<pre><code>dotnet test -l &quot;console;verbosity=detailed&quot;
</code></pre>
<p>its good but i need to filter the tests than take more than 2 milisec!</p>
<p>1- how to filter the tests that took more than 2milisec?</p>
<p>2- additionally , do you know a command line or any external tools that help me to create a report like that? (for example : a tools to generate some report that show some metrics and analysis )</p>
<p>thanks a lot</p>
",https://stackoverflow.com/questions/75131620/detect-unit-tests-that-took-long-time-to-respond,"['unit-testing', 'testing', 'xunit', '.net-7.0', 'dotnet-test']",19,False,0,0
Jest unit tests throws &quot;Unknown option&quot; in build process,"<p>I'm trying to execute Jest unit testing on a PWA made with Vue 2 but throws me an error when I try to build it. The error when i run <code>npm run build</code> is the following:
<a href=""https://i.stack.imgur.com/0QCT0.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0QCT0.png"" alt=""Error screenshot"" /></a>
The error prevents me to build and run the app.
The conflict is in the &quot;test&quot; property of the .babelrc file but if I remove this property, my tests stop working but the build works correctly.</p>
<p>My .babelrc file:</p>
<pre><code>{
  &quot;presets&quot;: [
    [&quot;env&quot;, {
      &quot;modules&quot;: false,
      &quot;targets&quot;: {
        &quot;browsers&quot;: [&quot;&gt; 1%&quot;, &quot;last 2 versions&quot;, &quot;not ie &lt;= 8&quot;]
      }
    }],
    &quot;stage-2&quot;
  ],
  &quot;plugins&quot;: [&quot;transform-runtime&quot;],
  &quot;env&quot;: {
    &quot;test&quot;: {
      &quot;presets&quot;: [&quot;env&quot;, &quot;stage-2&quot;],
      &quot;plugins&quot;: [ &quot;istanbul&quot; ]
    }
  },
  &quot;test&quot;: [
    &quot;jest&quot;
  ]
}

</code></pre>
<p>My babel.config.js:</p>
<pre><code>module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset'
  ]
};

</code></pre>
<p>And my package.json:</p>
<pre><code>{
  &quot;name&quot;: &quot;ponce&quot;,
  &quot;version&quot;: &quot;1.3.1&quot;,
  &quot;description&quot;: &quot;ponce&quot;,
  &quot;private&quot;: true,
  &quot;scripts&quot;: {
    &quot;dev&quot;: &quot;node build/dev-server.js&quot;,
    &quot;start&quot;: &quot;node build/dev-server.js&quot;,
    &quot;build&quot;: &quot;node build/build.js&quot;,
    &quot;lint&quot;: &quot;eslint --ext .js,.vue src&quot;,
    &quot;android-init&quot;: &quot;npx cap copy &amp;&amp; npx cap add android&quot;,
    &quot;android&quot;: &quot;npm run build &amp;&amp; npx cap copy &amp;&amp; npx cap copy android &amp;&amp; npx cap open android&quot;,
    &quot;test&quot;: &quot;jest&quot;
  },
  &quot;dependencies&quot;: {
    &quot;@capacitor/android&quot;: &quot;^2.3.0&quot;,
    &quot;@capacitor/cli&quot;: &quot;^2.4.0&quot;,
    &quot;@capacitor/core&quot;: &quot;^2.4.0&quot;,
    &quot;apollo-cache-inmemory&quot;: &quot;^1.6.5&quot;,
    &quot;apollo-cache-persist&quot;: &quot;^0.1.1&quot;,
    &quot;apollo-client&quot;: &quot;^2.6.8&quot;,
    &quot;apollo-link&quot;: &quot;^1.2.13&quot;,
    &quot;apollo-link-http&quot;: &quot;^1.5.16&quot;,
    &quot;buffer-browserify&quot;: &quot;^0.2.5&quot;,
    &quot;c3&quot;: &quot;^0.7.15&quot;,
    &quot;child_process&quot;: &quot;^1.0.2&quot;,
    &quot;cordova-plugin-device&quot;: &quot;^2.0.3&quot;,
    &quot;cordova-plugin-network-information&quot;: &quot;^3.0.0&quot;,
    &quot;cordova-plugin-socket-tcp&quot;: &quot;^1.6.0&quot;,
    &quot;cordova-plugin-x-socialsharing&quot;: &quot;^6.0.1&quot;,
    &quot;es6-promise-plugin&quot;: &quot;^4.2.2&quot;,
    &quot;fs&quot;: &quot;^0.0.1-security&quot;,
    &quot;graphql-tag&quot;: &quot;^2.10.3&quot;,
    &quot;luxon&quot;: &quot;^1.24.1&quot;,
    &quot;mixpanel-browser&quot;: &quot;^2.45.0&quot;,
    &quot;node-gyp&quot;: &quot;^7.1.0&quot;,
    &quot;socket.io-client&quot;: &quot;^2.3.0&quot;,
    &quot;vue&quot;: &quot;^2.5.16&quot;,
    &quot;vue-apollo&quot;: &quot;^3.0.3&quot;,
    &quot;vue-browser-geolocation&quot;: &quot;^1.8.0&quot;,
    &quot;vue-datetime&quot;: &quot;^1.0.0-beta.13&quot;,
    &quot;vue-router&quot;: &quot;^2.8.1&quot;,
    &quot;vue2-google-maps&quot;: &quot;^0.10.7&quot;,
    &quot;vue2-timepicker&quot;: &quot;^1.1.3&quot;,
    &quot;vuetify&quot;: &quot;^1.0.14&quot;,
    &quot;vuex&quot;: &quot;^2.5.0&quot;,
    &quot;vuex-persist&quot;: &quot;^2.2.0&quot;,
    &quot;weekstart&quot;: &quot;^1.0.1&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@vue/cli-plugin-babel&quot;: &quot;^5.0.8&quot;,
    &quot;autoprefixer&quot;: &quot;^7.1.2&quot;,
    &quot;babel-core&quot;: &quot;^6.22.1&quot;,
    &quot;babel-eslint&quot;: &quot;^7.1.1&quot;,
    &quot;babel-loader&quot;: &quot;^7.1.1&quot;,
    &quot;babel-plugin-transform-runtime&quot;: &quot;^6.22.0&quot;,
    &quot;babel-preset-env&quot;: &quot;^1.3.2&quot;,
    &quot;babel-preset-stage-2&quot;: &quot;^6.22.0&quot;,
    &quot;babel-register&quot;: &quot;^6.22.0&quot;,
    &quot;chalk&quot;: &quot;^2.0.1&quot;,
    &quot;connect-history-api-fallback&quot;: &quot;^1.3.0&quot;,
    &quot;copy-webpack-plugin&quot;: &quot;^4.0.1&quot;,
    &quot;css-loader&quot;: &quot;^0.28.0&quot;,
    &quot;cssnano&quot;: &quot;^3.10.0&quot;,
    &quot;eslint&quot;: &quot;^3.19.0&quot;,
    &quot;eslint-config-standard&quot;: &quot;^6.2.1&quot;,
    &quot;eslint-friendly-formatter&quot;: &quot;^3.0.0&quot;,
    &quot;eslint-loader&quot;: &quot;^1.7.1&quot;,
    &quot;eslint-plugin-html&quot;: &quot;^3.1.0&quot;,
    &quot;eslint-plugin-promise&quot;: &quot;^3.4.0&quot;,
    &quot;eslint-plugin-standard&quot;: &quot;^2.0.1&quot;,
    &quot;eventsource-polyfill&quot;: &quot;^0.9.6&quot;,
    &quot;express&quot;: &quot;^4.14.1&quot;,
    &quot;extract-text-webpack-plugin&quot;: &quot;^2.0.0&quot;,
    &quot;file-loader&quot;: &quot;^0.11.1&quot;,
    &quot;friendly-errors-webpack-plugin&quot;: &quot;^1.1.3&quot;,
    &quot;html-webpack-plugin&quot;: &quot;^2.28.0&quot;,
    &quot;http-proxy-middleware&quot;: &quot;^0.17.3&quot;,
    &quot;jest&quot;: &quot;^29.5.0&quot;,
    &quot;material-design-icons-iconfont&quot;: &quot;^6.1.0&quot;,
    &quot;opn&quot;: &quot;^5.1.0&quot;,
    &quot;optimize-css-assets-webpack-plugin&quot;: &quot;^2.0.0&quot;,
    &quot;ora&quot;: &quot;^1.2.0&quot;,
    &quot;rimraf&quot;: &quot;^2.6.0&quot;,
    &quot;semver&quot;: &quot;^5.3.0&quot;,
    &quot;shelljs&quot;: &quot;^0.7.6&quot;,
    &quot;stylus&quot;: &quot;^0.54.5&quot;,
    &quot;stylus-loader&quot;: &quot;^3.0.1&quot;,
    &quot;sw-precache-webpack-plugin&quot;: &quot;^0.11.4&quot;,
    &quot;uglify-es&quot;: &quot;^3.0.25&quot;,
    &quot;url-loader&quot;: &quot;^0.5.8&quot;,
    &quot;vue-cli-plugin-apollo&quot;: &quot;^0.21.3&quot;,
    &quot;vue-loader&quot;: &quot;^12.1.0&quot;,
    &quot;vue-style-loader&quot;: &quot;^3.0.1&quot;,
    &quot;vue-template-compiler&quot;: &quot;^2.3.3&quot;,
    &quot;webpack&quot;: &quot;^2.6.1&quot;,
    &quot;webpack-bundle-analyzer&quot;: &quot;^2.2.1&quot;,
    &quot;webpack-dev-middleware&quot;: &quot;^1.10.0&quot;,
    &quot;webpack-hot-middleware&quot;: &quot;^2.18.0&quot;,
    &quot;webpack-merge&quot;: &quot;^4.1.0&quot;
  },
  &quot;engines&quot;: {
    &quot;node&quot;: &quot;&gt;= 4.0.0&quot;,
    &quot;npm&quot;: &quot;&gt;= 3.0.0&quot;
  },
  &quot;browserslist&quot;: [
    &quot;&gt; 1%&quot;,
    &quot;last 2 versions&quot;,
    &quot;not ie &lt;= 8&quot;
  ]
}
</code></pre>
<p>I tried to look in the documentation but there it recognizes the option &quot;test&quot; in the .babelrc file.</p>
",https://stackoverflow.com/questions/76237196/jest-unit-tests-throws-unknown-option-in-build-process,"['vue.js', 'vuejs2', 'jestjs', 'babeljs', 'babel-jest']",39,False,0,0
How to deep mock Prisma Client in JavaScript (not TypeScript)?,"<p>I'm want to unit test Next.js API route with Prisma in JavaScript. Unfortunately, the <a href=""https://www.prisma.io/docs/guides/testing/unit-testing"" rel=""nofollow noreferrer"">Prisma's unit testing guide</a> is written for Typescript.</p>
<p>I have jest.config.js which will setup the mock in jest.setup.js</p>
<pre><code>const nextJest = require(&quot;next/jest&quot;);

const createJestConfig = nextJest({
  dir: &quot;./&quot;,
});

const config = {
  setupFilesAfterEnv: [&quot;&lt;rootDir&gt;/jest.setup.js&quot;],
  moduleDirectories: [&quot;node_modules&quot;, &quot;&lt;rootDir&gt;/&quot;],
  moduleNameMapper: {
    &quot;@/(.*)$&quot;: &quot;&lt;rootDir&gt;/$1&quot;,
  },
};

module.exports = createJestConfig(config);
</code></pre>
<p>and this is how I configured the mock in jest.setup.js</p>
<pre><code>import prisma from &quot;@/utils/client&quot;;

jest.mock(&quot;@/utils/client&quot;, () =&gt; ({
  __esModule: true,
  default: {
    user: {
      findMany: jest.fn(),
    },
    // ... and each and everyone of the entities
  },
}));

export const prismaMock = prisma;
</code></pre>
<p>and the following test case passed</p>
<pre><code>describe(&quot;Calculator&quot;, () =&gt; {
  it(&quot;renders a calculator&quot;, async () =&gt; {
    await prismaMock.user.findMany.mockResolvedValue([&quot;abc]);
    const { req, res } = createMocks();
    await handler(req, res);
    expect(res._getStatusCode()).toBe(200);
    expect(res._getData()).toBe('[&quot;abc&quot;]');
  });
});
</code></pre>
<p>With this approach, I have to mock each and everyone of the models and function in jest.setup.js. Is there a way to mock all the models and functions automatically? Is there a similar JavaScript library which provides mockDeep from jest-mock-extended?</p>
",https://stackoverflow.com/questions/75383274/how-to-deep-mock-prisma-client-in-javascript-not-typescript,"['jestjs', 'prisma']",19,False,0,0
Visual Studio Unit Test Debugging in Python not working,"<p>I am trying to debug Python unit tests in Visual Studio 2022 Community Edition. I am able to display the unit tests in Test Explorer and run them. The issue is that when trying to debug the unit tests, the debugger doesn't hit the breakpoints. I am following this instruction for unit test Python in Visual Studio: <a href=""https://learn.microsoft.com/en-us/visualstudio/python/unit-testing-python-in-visual-studio?view=vs-2022"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/visualstudio/python/unit-testing-python-in-visual-studio?view=vs-2022</a>
Any advice on how to configure Visual Studio to be able to debug python unit tests?</p>
",https://stackoverflow.com/questions/75734988/visual-studio-unit-test-debugging-in-python-not-working,"['python', 'visual-studio', 'unit-testing', 'visual-studio-2022']",59,False,0,0
Testing a method without instantiating class,"<p>I followed this approach <a href=""https://stackoverflow.com/questions/27105491/how-can-i-unit-test-a-method-without-instantiating-the-class"">here</a>, but the issue is that this requires me to duplicate code.</p>
<p>I can override the class in my test, but then I also have to copy and paste the method from my original script to the test script which defeats the purpose of unit testing. Someone could change the original method, but not the one used in the unit test.</p>
<p><code>main.py</code></p>
<pre><code>class ClassToTest(object):
    def __init__(x, y, z, many_dependencies):
        self.x = x
        self.y = y
        self.z = z
        self.many_dependencies = many_dependencies

    def method_to_test(self, y):
        self.x = y
        return 5
</code></pre>
<p><code>test_main.py</code></p>
<pre><code>from main import ClassToTest 

class ClassToTest(object):
    # I want to override this only
    def __init__(self):
        pass

    # I don't want to copy and paste this into my test script
    def method_to_test(self, y):
        self.x = y
        return 5

fake_instance = mock.Mock()
ClassToTest.__init__(fake_instance)
x = ClassToTest.method_to_test(fake_instance, 3)
assert x == 5
assert fake_instance.x == 3
</code></pre>
<p>Is there a way to import the class, override the init method and test the original method without pasting it into the test itself?</p>
",https://stackoverflow.com/questions/76005058/testing-a-method-without-instantiating-class,"['python', 'unit-testing']",38,True,-1,1
How to properly mock client.Publish.GetAsync(request) in Aquarius SDK unit test?,"<p>I wrote the bellow method on the AquariusService class which is called Aquarius SDK:</p>
<pre><code>public async Task&lt;TimeAlignedDataServiceResponse&gt; GetTimeSeriesPointsAsync(IAquariusClient client,
                                                                                   List&lt;Guid&gt; timeSeriesId,
                                                                                   DateTimeOffset? fromDate,
                                                                                   DateTimeOffset? toDate)
        {
            var request = new TimeAlignedDataServiceRequest
            {
                TimeSeriesUniqueIds = timeSeriesId,
                QueryFrom = fromDate,
                QueryTo = toDate
            };

            TimeAlignedDataServiceResponse response = await client.Publish.GetAsync(request);

            return response;
        }
</code></pre>
<hr />
<p>And then wrote a unit test for the method based on the unit test documents on the (<a href=""https://github.com/AquaticInformatics/aquarius-sdk-net/wiki/Unit-testing-your-integration"" rel=""nofollow noreferrer"">https://github.com/AquaticInformatics/aquarius-sdk-net/wiki/Unit-testing-your-integration</a>):</p>
<pre><code>public class AquariusServiceTests
    {
       
        private IAquariusClient _mockClient;
        private IServiceClient _mockPublishClient;
        private IServiceClient _mockProvisioningClient;
        private IServiceClient _mockAcquisitionClient;

        public AquariusServiceTests()
        {
            
            SetupMockClient();

        }

        private void SetupMockClient()
        {
            _mockClient = Substitute.For&lt;IAquariusClient&gt;();

            _mockPublishClient = Substitute.For&lt;IServiceClient&gt;();
            _mockProvisioningClient = Substitute.For&lt;IServiceClient&gt;();
            _mockAcquisitionClient = Substitute.For&lt;IServiceClient&gt;();


            _mockClient.Publish.Returns(_mockPublishClient);
            _mockClient.Provisioning.Returns(_mockProvisioningClient);
            _mockClient.Acquisition.Returns(_mockAcquisitionClient);
        }

        [Fact]
        public async Task GetTimeSeriesPointsAsync_Should_Return_Response()
        {
            List&lt;Guid&gt; timeseriesIds = new() { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };

            List&lt;TimeAlignedPoint&gt; points = new(1);

            TimeAlignedDataServiceRequest request = new()
            {
                TimeSeriesUniqueIds = new List&lt;Guid&gt; { Guid.NewGuid() },
                QueryFrom = DateTime.Now,
                QueryTo = DateTime.Now.AddHours(1)
            };

            TimeAlignedDataServiceResponse response = new() 
             { 
                NumPoints = 1, 
                Points = points, 
                ResponseTime = new DateTimeOffset(), 
                ResponseVersion = 1, 
                Summary = &quot;summary&quot;,
                TimeRange= new TimeRange(),
                TimeSeries=new List&lt;TimeAlignedTimeSeriesInfo&gt;()
            };

            ILogger&lt;AquariusService&gt; _fakeLogger = Substitute.For&lt;ILogger&lt;AquariusService&gt;&gt;();
            IAquariusService _sut = new AquariusService(_fakeLogger);

            _mockPublishClient.Get(request).Returns(response);

            var actual = await _sut.GetTimeSeriesPointsAsync(_mockClient, timeseriesIds, DateTime.Now, DateTime.Now.AddHours(1));
            Assert.IsAssignableFrom&lt;TimeAlignedDataServiceResponse&gt;(actual);

            //Exception 

            //_mockPublishClient.GetAsync(request).ThrowsForAnyArgs(new ArgumentNullException());
            //var actual = await Record.ExceptionAsync(() =&gt; _sut.GetTimeSeriesPointsAsync(_mockClient, timeseriesIds, DateTime.Now, DateTime.Now.AddHours(1)));
            //var error = Assert.IsType&lt;ArgumentNullException&gt;(actual);
        }

       
    }
</code></pre>
<hr />
<p>The issue is the response on GetTimeSeriesPointsAsync() will be null instead of the given response. Actually can't mock the client.Publish.GetAsync(request) correctly while the mock of the exception works fine.
How can I mock client.Publish.GetAsync(request) on the GetTimeSeriesPointsAsync method correctly and return a response instead of null on the test result?</p>
",https://stackoverflow.com/questions/76327967/how-to-properly-mock-client-publish-getasyncrequest-in-aquarius-sdk-unit-test,"['c#', 'unit-testing', '.net-core', 'sdk', 'xunit.net']",70,True,0,1
Consequences on Flutter unit testing requiring all model objects to extend equatable,"<p>When testing for object data equality, models need to override both operator==() &amp; hashCode(), and possibly be immutable if equatable was used.</p>
<p>What would be the consequences in general in term of memory optimization &amp; instantiation time?
Should I consider the idea of creating separate models for testing, leaving the real models intact?</p>
<p>Currently I'm overriding the operator==() &amp; hashCode() methods when needed for every real model.
But I fear this will leave a negative impact on the app performance.</p>
<p>Please share your experience with unit testing in Dart/Flutter.</p>
",https://stackoverflow.com/questions/76218294/consequences-on-flutter-unit-testing-requiring-all-model-objects-to-extend-equat,"['flutter', 'dart', 'unit-testing', 'model', 'pojo']",22,False,0,0
Unit testing notebooks in databricks,"<p>I have created test_example.py inside test1 folder  inside repo /Workspace/Repos/temp/test1/sample.py as follow:</p>
<pre><code>def test_addition():
    assert 1 + 2 == 3

def test_subtraction():
    assert 5 - 3 == 2
</code></pre>
<p>I have created sample.py inside test1 folder inside repo /Workspace/Repos/temp/test1/sample.py as follow:
import pytest</p>
<pre><code>test_file_path = '/Workspace/Repos/temp/test1/test_example.py'

# Run the test file with the specified arguments
retcode = pytest.main([test_file_path, '-v', '-p', 'no:cacheprovider'])

# Check the return code to see if the tests passed or failed
assert retcode ==0, 'the pytest invocation failed.see the log above for details.'

</code></pre>
<p>I would like to test all files from test1 folder which have all unit testing files:</p>
<p>but getting error :</p>
<p>OSError: [Errno 95] Operation not supported: '/Workspace/Repos/temp/test1/<strong>pycache</strong>'
=========================== short test summary info ============================
ERROR test_example.py - OSError: [Errno 95] Operation not supported: '/Worksp...
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
=============================== 1 error in 1.06s ===============================
Out[2]: &lt;ExitCode.INTERRUPTED: 2&gt;</p>
",https://stackoverflow.com/questions/75823688/unit-testing-notebooks-in-databricks,"['unit-testing', 'databricks']",29,False,0,0
django unique constraint fails,"<p><a href=""https://i.stack.imgur.com/BESuW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/BESuW.png"" alt=""enter image description here"" /></a>I am creating a book model, and with that model, there is a isbn variable that should have the unique constraint set to true which should stop there from being duplicate isbn values in my database. however when unit testing this model, the test_isbn_must_be_unique() test fails to raise the validation error even though I have set unique to be true in the book model.</p>
<p>I was expecting the test to pass since I had set unique to be true in the list of constraints for the isbn variable. however, the test fails.</p>
<pre><code>`# models.py file
from django.core.validators import RegexValidator
from django.db import models
from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    username = models.CharField(
        max_length=30,
        unique=True,
        validators=[RegexValidator(
            regex=r'^@\w{3,}$',
            message='Username must consist of @ followed by at least three alphanumericals'
        )]
    )
    first_name = models.CharField(max_length=50, blank=False)
    last_name = models.CharField(max_length=50, blank=False)
    email = models.EmailField(unique=True, blank=False)
    bio = models.CharField(max_length=520, blank=True)


class Book(models.Model):
    isbn = models.CharField(max_length=13, unique=True, null=False, blank=False)
    book_title = models.TextField(blank=False, max_length=500)
    book_author = models.CharField(blank=False, max_length=255)
    year_of_publication = models.CharField(max_length=13, blank=False)
    publishers = models.CharField(blank=False, max_length=255)
    image_url_s = models.CharField(blank=False, max_length=255)
    image_url_m = models.CharField(blank=False, max_length=255)
    image_url_l = models.CharField(blank=False, max_length=255)`
</code></pre>
<pre><code>`&quot;Testing Book Model&quot;
from django.test import TestCase
from django.core.exceptions import ValidationError
from clubs.models import Book


class BookModelTestCase(TestCase):
    def setUp(self):
        super(TestCase, self).setUp()
        self.book = Book(
            isbn='0195153448',
            book_title='Classical Mythology',
            book_author='Mark P. O. Morford',
            year_of_publication='2002',
            publishers='Oxford University Press',
            image_url_s='http://images.amazon.com/images/P/0195153448.01.THUMBZZZ.jpg',
            image_url_m='http://images.amazon.com/images/P/0195153448.01.MZZZZZZZ.jpg',
            image_url_l='http://images.amazon.com/images/P/0195153448.01.LZZZZZZZ.jpg'
        )

    def test_valid_book(self):
        self._assert_book_is_valid()

    def test_isbn_must_not_be_blank(self):
        self.book.isbn = None
        self._assert_book_is_invalid()

    def test_isbn_must_not_be_over_13_numbers(self):
        self.book.isbn = '1' * 14
        with self.assertRaises(ValidationError):
            self.book.full_clean()

    def test_isbn_can_be_13_numbers(self):
        self.book.isbn = '1' * 13
        self._assert_book_is_valid()

    def test_isbn_must_be_unique(self):
        second_book = self._create_second_book()
        self.book.isbn = second_book.isbn
        self._assert_book_is_invalid()
    def _create_second_book(self):
        book = Book(
            isbn='0002005018',
            book_title='Clara Callan',
            book_author='Richard Bruce Wright',
            year_of_publication='2001',
            publishers='HarperFlamingo Canada',
            image_url_s='http://images.amazon.com/images/P/0002005018.01.THUMBZZZ.jpg',
            image_url_m='http://images.amazon.com/images/P/0002005018.01.MZZZZZZZ.jpg',
            image_url_l='http://images.amazon.com/images/P/0002005018.01.LZZZZZZZ.jpg'
        )
        return book

    def _assert_book_is_valid(self):
        try:
            self.book.full_clean()
        except ValidationError:
            self.fail('user should be valid')

    def _assert_book_is_invalid(self):
        with self.assertRaises(ValidationError):
            self.book.full_clean()
`
</code></pre>
",https://stackoverflow.com/questions/75375684/django-unique-constraint-fails,"['python', 'django', 'unit-testing', 'validation']",38,False,0,0
Best practices for testing Controllers in Spring Boot: Should I assert actual values in the response body or just its presence?,"<p>In my Spring Boot application, I have a layered architecture with Controllers, Services, and Repositories, each with their corresponding DTOs/Models. I am writing unit tests for my Controllers and am unsure about the extent to which I should assert the response body.</p>
<p>Here's a simplified scenario to illustrate my question:</p>
<p>Suppose I have a BookController with a GET /books/{id} endpoint that fetches a book's details. The response body contains a BookDTO with fields like id, title, author, etc.</p>
<pre><code>@GetMapping(&quot;/books/{id}&quot;)
public ResponseEntity&lt;BookDTO&gt; getBook(@PathVariable Long id) {
    BookDTO bookDTO = bookService.getBook(id);
    return new ResponseEntity&lt;&gt;(bookDTO, HttpStatus.OK);
}

</code></pre>
<p>When unit testing this GET endpoint, I am currently verifying the HTTP status and asserting the actual values in the BookDTO response body, like this:</p>
<pre><code>@Test
void getBookTest() throws Exception {
    // mock service method
    when(bookService.getBook(anyLong())).thenReturn(new BookDTO(1L, &quot;Title&quot;, &quot;Author&quot;));

    // perform request and verify status
    mockMvc.perform(get(&quot;/books/1&quot;))
            .andExpect(status().isOk())
            .andExpect(jsonPath(&quot;$.id&quot;).value(1L))
            .andExpect(jsonPath(&quot;$.title&quot;).value(&quot;Title&quot;))
            .andExpect(jsonPath(&quot;$.author&quot;).value(&quot;Author&quot;));
}

</code></pre>
<p>While this test is thorough, it's also tightly coupled to the structure of BookDTO. If BookDTO changes (e.g., a field is added, removed, or renamed), I'll need to update all tests that assert its values, which seems not very maintainable.</p>
<p>I am considering a different approach where I only assert the presence of the response body, not its exact contents. I would then write separate unit tests for BookDTO to ensure it behaves correctly.</p>
<p>My question is: In terms of best practices for unit testing Controllers in Spring Boot, should I assert the actual values in the response body, or just the presence of the body? I understand that it may depend on the specific context, but I'd appreciate any general guidelines or considerations. Thanks!</p>
",https://stackoverflow.com/questions/76284047/best-practices-for-testing-controllers-in-spring-boot-should-i-assert-actual-va,"['java', 'spring', 'spring-boot', 'unit-testing']",54,True,0,2
Test functional route resolver,"<p>Class based route resolvers have been recently deprecated in Angular in favor of functional resolvers. See the documentation <a href=""https://angular.io/api/router/ResolveFn"" rel=""nofollow noreferrer"">here</a>.</p>
<p>Does anyone have examples of unit testing these functional resolvers?</p>
<p>I'm not finding any examples in the Angular docs, and the Angular test environment is difficult to configure. So for example, how would one unit test the example function in the docs?</p>
<pre><code>export const heroResolver: ResolveFn&lt;Hero&gt; =
    (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) =&gt; {
      return inject(HeroService).getHero(route.paramMap.get('id')!);
    };
</code></pre>
<p>I'm using a resolver that's basically identical to this in that it calls some service to fetch an entity by ID. When trying to configure call the resolver in Jest, I get the following error:</p>
<pre><code>NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `EnvironmentInjector#runInContext`. Find more at https://angular.io/errors/NG0203
</code></pre>
",https://stackoverflow.com/questions/75702015/test-functional-route-resolver,"['angular', 'jestjs']",1090,True,2,2
How to do a view unit test for &lt;MudSelect&gt;?,"<p>I am working a balzor webassembly project,
I tried to write a unit test for  by using Bunit, Xunit,and Moq</p>
<pre><code>&lt;MudSelect T=&quot;string&quot; AnchorOrigin=&quot;Origin.BottomCenter&quot; Label=&quot;Status&quot; MultiSelection=&quot;true&quot; SelectAll=&quot;true&quot; SelectAllText=&quot;All&quot; SelectedValuesChanged=&quot;SelcetOption&quot; Variant=&quot;Variant.Outlined&quot; Margin=&quot;Margin.Dense&quot;&gt;
                            @foreach (var state in StatusOption)
                            {

                                &lt;div&gt;  @state &lt;/div&gt;    // This line is printed  #1
                                 &lt;MudSelectItem T=&quot;string&quot; Value=&quot;@state&quot;  id=&quot;@($&quot;participant-status-{state}&quot;)&quot; &gt;@state&lt;/MudSelectItem&gt;        // but this line is not printed #2

                            }
                        &lt;/MudSelect&gt;
</code></pre>
<p>#1 printed when unit testing</p>
<pre><code>                    &lt;div&gt;New Enquiry&lt;/div&gt;
                    &lt;div&gt;Onboarding Follow-Up&lt;/div&gt;
                    &lt;div&gt;Meeting Scheduled&lt;/div&gt;
                    &lt;div&gt;New Client&lt;/div&gt;
                    &lt;div&gt;Active&lt;/div&gt;
                    &lt;div&gt;Inactive&lt;/div&gt;
                    &lt;div&gt;Not Attending&lt;/div&gt;
                    &lt;div&gt;Pending Action From Client&lt;/div&gt;
                    &lt;div&gt;Pending Action From Organization&lt;/div&gt;
                    &lt;div&gt;Exited&lt;/div&gt;
                    &lt;div&gt;Deceased&lt;/div&gt;
                    &lt;div&gt;Cancelled&lt;/div&gt;
</code></pre>
<p>#2 does not print anything . Why?</p>
<p>The StatusOption array passed to the component correctly.</p>
<pre><code>public string[] StatusOption = {  &quot;New Enquiry&quot;,&quot;Onboarding Follow-Up&quot;, &quot;Meeting Scheduled&quot;,&quot;New Client&quot;&quot;};
</code></pre>
<p>I guess, the MudSelectItem component is typically used as an option inside a MudSelect component, which is a dropdown menu. When the user clicks on the placeholder of the MudSelect component, the list of MudSelectItem options will appear.</p>
<p>That is why #2 may not printed when component render.</p>
<p>Anyone has idea to check this filter view (i.e MudSelect )??</p>
",https://stackoverflow.com/questions/75187949/how-to-do-a-view-unit-test-for-mudselect,"['.net', 'unit-testing', 'xunit', 'mudblazor', 'bunit']",284,False,2,0
How can I ignore obsolete type errors when running Live Unit Testing in VS 2022 enterprise?,"<p>I have a solution with about 58 projects, including 10 test projects. There's only one I'm interested in running, that relates to my team's work.</p>
<p>I can run the test project manually from the Test Explorer, and it builds with all tests passing fine.</p>
<p>However, when I set up Live Unit Testing, the build fails due to obsolete types being used in some another projects. I don't want to replace all the type references since that code is managed by other teams.</p>
<p>Here are my <a href=""https://i.stack.imgur.com/k8UBm.png"" rel=""nofollow noreferrer"">VS2022 LUT settings</a>.</p>
<p>I have only added the test project I'm interested in to the LUT playlist. I also tried replacing some of the obsolete types (I only had 3 errors initially) but the compiler then found dozens more...</p>
<p>I increased the logging level on LUT to verbose, but that didn't give anything useful. There aren't any other settings I can see for LUT to ignore certain projects or errors.</p>
<p>I have looked up the MS documentation on the [obsolete] attribute, but I'm not sure why I get the error on LUT and not on regular test or debug builds.</p>
<p>The .csproj of a project that fails has this line: <code>&lt;TreatWarningsAsErrors&gt;True&lt;/TreatWarningsAsErrors&gt;</code> and setting it to <code>False</code> allows LUT to build it. But I don't want to have to change dozens of .csprojs just for running some tests.</p>
<p>Is there any other way to mark errors as warnings for live unit testing?</p>
",https://stackoverflow.com/questions/75453955/how-can-i-ignore-obsolete-type-errors-when-running-live-unit-testing-in-vs-2022,"['c#', 'visual-studio', 'compiler-errors', 'visual-studio-2022', 'live-unit-tests']",131,True,2,1
MSTest unit test on .NET Core only provides seven encodings. How can I reach the ANSI one?,"<p>I'm unit testing a .NET Core solution in Visual Studio 2022 on Windows.</p>
<p>In my solution I want to output an ANSI string stored in a byte buffer, but that doesn't seem to work.</p>
<p>This is an extract of the byte buffer:</p>
<pre class=""lang-cs prettyprint-override""><code>byte[] test = new byte[] {65, 32, 150, 32, 66};
</code></pre>
<p>The text to extract is: <code>A – B</code>.</p>
<p>This is what I tried so far:</p>
<pre class=""lang-cs prettyprint-override""><code>Encoding.ASCII.GetString(buffer);

A ? B


Encoding.Latin1.GetString(buffer);

A \u0096 B


Encoding.UTF8.GetString(buffer);

A � B


Encoding.UTF8.GetString(buffer);


Encoding.GetEncoding(1252).GetString(buffer)
'Encoding.GetEncoding(1252).GetString(buffer)' raised an exception of type'System.NotSupportedException'
    Data: {System.Collections.ListDictionaryInternal}
    HResult: -2146233067
    HelpLink: null
    InnerException: null
    Message: &quot;No data is available for encoding 1252. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.&quot;
    Source: &quot;System.Private.CoreLib&quot;
    StackTrace: &quot;   bei System.Text.Encoding.GetEncoding(Int32 codepage)&quot;
    TargetSite: {System.Text.Encoding GetEncoding(Int32)}

</code></pre>
<p>Only the following code pages are available while I'm running the Visual Studio 2022 debugger:</p>
<pre class=""lang-cs prettyprint-override""><code>Encoding.GetEncodings().Length

7
</code></pre>
<div class=""s-table-container"">
<table class=""s-table"">
<thead>
<tr>
<th>Code Page</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1200</td>
<td>utf-16</td>
</tr>
<tr>
<td>1201</td>
<td>utf-16BE</td>
</tr>
<tr>
<td>12000</td>
<td>utf-32</td>
</tr>
<tr>
<td>12001</td>
<td>utf-32BE</td>
</tr>
<tr>
<td>20127</td>
<td>us-ascii</td>
</tr>
<tr>
<td>28591</td>
<td>iso-8859-1</td>
</tr>
<tr>
<td>65001</td>
<td>utf-8</td>
</tr>
</tbody>
</table>
</div><br/>
<p>How can I correctly decode the above text?</p>
<br/>
",https://stackoverflow.com/questions/75903900/mstest-unit-test-on-net-core-only-provides-seven-encodings-how-can-i-reach-the,"['c#', '.net', '.net-core', 'character-encoding', 'visual-studio-2022']",29,False,1,0
How can I turn React Testing Library &quot;not wrapped in act&quot; warnings into Jest unit tests errors,"<p>We are unit testing our react app using Jest and React Testing Library. And we get some of this &quot;classic&quot; errors :</p>
<pre><code>console.error
      Warning: A suspended resource finished loading inside a test, but the event was not wrapped in act(...).
      
      When testing, code that resolves suspended data should be wrapped into act(...):
      
      act(() =&gt; {
        /* finish loading suspended data */
      });
      /* assert on the output */
</code></pre>
<p>But some Some developers simply ignore the error of this type. So, as time passes, the tests output is bloated with warning like that. And our tests feel less confident.</p>
<p>Is there a config in Jest or in React Testing Library that turns this kind of warning in error and makes the unit tests fail ?
I search in Google and found a lot of (good) articles to solve the warning but not to turn it into real error.</p>
",https://stackoverflow.com/questions/75210531/how-can-i-turn-react-testing-library-not-wrapped-in-act-warnings-into-jest-uni,"['reactjs', 'unit-testing', 'jestjs', 'react-testing-library']",144,True,1,1
TestNG libs not downloaded while using gradle,"<p>I am new to gradle and have rarely used maven also before. I have built a Automation Framework using TestNG and adding wrapper around TestNG. Now I want to make it as a gradle project. I am using the below content in the build.gradle.</p>
<pre><code>plugins {
    // Apply the java-library plugin for API and implementation separation.
    id 'java-library'
}

//mainClassName = &quot;mainclass&quot;

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

dependencies {
    implementation group: 'javax.json', name: 'javax.json-api', version: '1.1.4'
    implementation group: 'org.testng', name: 'testng', version: '7.7.1'
}
</code></pre>
<p>In this case only javax-json-api.jar is downloaded and added to the 'Projects and External Dependencies' section in Eclipse. TestNG doesn't get downloaded and Eclipse shows me the compilation errors. I tried compile and testImplementation as well, nothing worked.</p>
<p>Note: I am not using TestNG for unit testing here. I am trying to build a Function Test Framework.</p>
",https://stackoverflow.com/questions/75599920/testng-libs-not-downloaded-while-using-gradle,"['gradle', 'build.gradle', 'testng', 'maven-central']",55,True,1,1
How can I import classes into other files?,"<p>I've got a file structure like this:</p>
<pre><code>/app/sense/abstract/__init__.py
/app/sense/abstract/sensor.py
/app/sense/__init__.py
/app/sense/gps.py
/app/components.py
/app/main.py
/tests/unit/__init__.py
/tests/unit/context.py
/tests/unit/test_sense.py
</code></pre>
<p><code>sensor.py</code> defines an abstract base class Sensor used by <code>gps.py</code> to shape a GPS class.</p>
<p>The intent of <code>components.py</code> is to facilitate
importing all classes in the subfolders in one line. The only line of code so far is:</p>
<pre><code>from .sense.gps import GPS
</code></pre>
<p>The intent of <code>context.py</code> is to allow me to import classes for unit testing. It currently has the following lines of code:</p>
<pre><code>from pathlib import Path
import sys

path = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, path)

import app.components as avc
</code></pre>
<p>And finally the <code>test_sense.py</code> class includes code to test whether the <code>GPS</code> implements <code>Sensor</code>.</p>
<p>The problem I'm having is that: whenever I try to run the <code>test_sense.py</code> file, I get <code>ModuleNotFoundError</code>, saying 'app' doesnt exist. How can I get around that?</p>
",https://stackoverflow.com/questions/75899689/how-can-i-import-classes-into-other-files,"['python', 'python-3.x', 'python-import']",27,True,1,1
Unit testing Annotation Processor: compare Java source code files without relying on internal compiler modules,"<p>I'm writing unit tests for a Java Annotation Processor that generates more Java source code.  I am currently using <code>com.google.testing.compile:compile-testing</code> to run assertions on the expected and generated source code, and this is currently working fine.  The problem is this library depends on the JDK's internal compiler, and access to it is restricted in Java 17.</p>
<p><a href=""https://github.com/google/compile-testing/issues/222"" rel=""nofollow noreferrer"">https://github.com/google/compile-testing/issues/222</a></p>
<p>I'm trying to get rid of any code and libraries that requires access to restricted internal JDK modules.  Is there another unit testing library that can compare Java source code that does not rely on internal JDK modules?</p>
",https://stackoverflow.com/questions/75795661/unit-testing-annotation-processor-compare-java-source-code-files-without-relyin,"['java', 'unit-testing']",16,False,0,0
Incompatible jest and react-native-paper libraries,"<p>I have a react native expo project which uses react-native-paper. When I tried to add unit testing with Jest I encountered a problem. Jest tests don't work with the configuration provided by expo docs. I have the following error:</p>
<blockquote>
<p>Jest encountered an unexpected token</p>
</blockquote>
<p>This is my package.json:</p>
<pre><code>&quot;scripts&quot;: {
    &quot;start&quot;: &quot;expo start&quot;,
    &quot;android&quot;: &quot;expo start --android&quot;,
    &quot;ios&quot;: &quot;expo start --ios&quot;,
    &quot;web&quot;: &quot;expo start --web&quot;,
    &quot;test&quot;: &quot;jest&quot;
  },
  &quot;dependencies&quot;: {
    &quot;@emotion/react&quot;: &quot;^11.10.6&quot;,
    &quot;@emotion/styled&quot;: &quot;^11.10.6&quot;,
    &quot;@expo/vector-icons&quot;: &quot;^13.0.0&quot;,
    &quot;@mui/icons-material&quot;: &quot;^5.11.11&quot;,
    &quot;@mui/material&quot;: &quot;^5.11.15&quot;,
    &quot;@react-native-community/datetimepicker&quot;: &quot;6.7.3&quot;,
    &quot;@react-native-picker/picker&quot;: &quot;2.4.8&quot;,
    &quot;@react-navigation/bottom-tabs&quot;: &quot;^6.5.7&quot;,
    &quot;@react-navigation/material-top-tabs&quot;: &quot;^6.6.2&quot;,
    &quot;@react-navigation/native&quot;: &quot;^6.1.6&quot;,
    &quot;@react-navigation/native-stack&quot;: &quot;^6.9.12&quot;,
    &quot;@testing-library/react&quot;: &quot;^14.0.0&quot;,
    &quot;dotenv&quot;: &quot;^16.0.3&quot;,
    &quot;expo&quot;: &quot;~48.0.9&quot;,
    &quot;expo-status-bar&quot;: &quot;~1.4.4&quot;,
    &quot;jest&quot;: &quot;^29.2.1&quot;,
    &quot;jest-expo&quot;: &quot;^48.0.2&quot;,
    &quot;react&quot;: &quot;18.2.0&quot;,
    &quot;react-native&quot;: &quot;0.71.6&quot;,
    &quot;react-native-paper&quot;: &quot;^5.7.0&quot;,
    &quot;react-native-picker-select&quot;: &quot;^8.0.4&quot;,
    &quot;react-native-safe-area-context&quot;: &quot;4.5.0&quot;,
    &quot;react-native-tab-view&quot;: &quot;^3.5.1&quot;,
    &quot;react-native-vector-icons&quot;: &quot;^9.2.0&quot;,
    &quot;react-native-wheel-picker-expo&quot;: &quot;^0.5.4&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@babel/core&quot;: &quot;^7.20.0&quot;
  },
  &quot;jest&quot;: {
    &quot;preset&quot;: &quot;jest-expo&quot;
  },
  &quot;private&quot;: true
}
</code></pre>
<p>I was able to fix this issue by adding a babel.config.js file with some configurations but this broke react-native-paper giving an error with MaterialCommunityIcons.</p>
<pre><code>module.exports = {
  presets: ['babel-preset-expo'],
  env: {
    test: {
      plugins: [
        ['@babel/plugin-transform-modules-commonjs', { loose: true }],
      ],
    },
  },
};
</code></pre>
<p>So after deleting the babel.config.js I'm back were I started trying to make both react-native-paper and jest work.</p>
",https://stackoverflow.com/questions/76081988/incompatible-jest-and-react-native-paper-libraries,"['android', 'react-native', 'jestjs', 'expo', 'react-native-paper']",40,False,0,0
Problem with unit testing of Billing Library 5 in Android,"<p>I'm using wrapper for BillingClient and after migration from Billing Library 4.0 to 5.0 there is an issue with unit testing of specific builder - <code>BillingFlowParams.SubscriptionUpdateParams</code> builder.</p>
<p>Specific wrapper's method that is having issue looks like this:</p>
<pre><code>fun upgradeSubscription(sub: Purchase, product: Product, activity: Activity) {
    val newOfferToken = product.productDetails.getOffer()?.offerToken ?: return
    val updateParams = BillingFlowParams.SubscriptionUpdateParams.newBuilder()
        .setOldPurchaseToken(sub.purchaseToken)
        .setReplaceProrationMode(MODE)
        .build()
    val productDetailsParamsList = listOf(
        ProductDetailsParams.newBuilder()
            .setProductDetails(product.productDetails)
            .setOfferToken(newOfferToken)
            .build()
    )
    val billingFlowParams = BillingFlowParams.newBuilder()
        .setProductDetailsParamsList(productDetailsParamsList)
        .setSubscriptionUpdateParams(updateParams)
        .build()
    client.launchBillingFlow(activity, billingFlowParams)
}
</code></pre>
<p>and my test method looks like this:</p>
<pre><code>@Test
fun `should test upgradeSubscription`() { 
    mockkStatic(BillingFlowParams::class)
    val params = slot&lt;BillingFlowParams&gt;()
    val activity = mockkClass(Activity::class)
    val sub = getMockedPurchase()

    billingWrapper.upgradeSubscription(sub, product, activity)

    verify { client.launchBillingFlow(storeActivity, capture(params)) }
}
</code></pre>
<p>Test fails at <code>.build()</code> line of <code>BillingFlowParams.SubscriptionUpdateParams</code>'s builder with such exception:</p>
<blockquote>
<p>java.lang.IllegalArgumentException: Please provide Old SKU purchase
information(token/id) or original external transaction id, not both.</p>
</blockquote>
<p>Meanwhile in real-life usage it works fine. So I'm wondering how to fix this problem with the unit test.</p>
<p>I've found <a href=""https://github.com/android/play-billing-samples/issues/546"" rel=""nofollow noreferrer"">the same question</a>, but unfortunately it still has no answer and no solution.</p>
",https://stackoverflow.com/questions/75391157/problem-with-unit-testing-of-billing-library-5-in-android,"['unit-testing', 'android-billing', 'play-billing-library']",137,False,0,0
How can I test MySql createConnection response using jest?,"<p>I just started unit testing and now I find myself in the position where I wish to test if the connection was created successfully or if the response of the function is successful.
(I am aware that this part is debatable in which is it e2e or unit but I still wish to carry out this test)</p>
<p>The following is my current test:</p>
<pre><code>test(&quot;Create connection&quot;, async ()=&gt;{

  const connectionOptions = {

    host:process.env.Database_host,
    user:process.env.Database_User,
    password:process.env.Database_Password,
    database:process.env.database_Name

  }
  const connection = await mysql.createConnection(connectionOptions);

  
  
})
</code></pre>
<p>Questions:</p>
<ul>
<li>How should I proceed from here ?</li>
<li>Should I create this test in another way?</li>
<li>If I was not using jest, how can I verify that the response of the function was successful?</li>
</ul>
<p>Notes: I'm using TypeScript</p>
",https://stackoverflow.com/questions/75592416/how-can-i-test-mysql-createconnection-response-using-jest,"['typescript', 'jestjs', 'ts-jest', 'mysql2']",36,False,0,0
Integrating Type Tests into Unit Tests with Typescript,"<p>I have grown very used to creating &quot;type tests&quot; in my Typescript projects which depend on narrow typing and I do this using the <code>@type-challenges/utils</code> type utilities. So for instance here is a test I have in one of my repos:</p>
<pre><code>describe(&quot;example of a type test&quot;, () =&gt; {

  it(&quot;SetRemoval&lt;TSet, TRemoval&gt;&quot;, () =&gt; {
    type Set1 = [&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;];
    type Set2 = [&quot;bat-shit-crazy&quot;, &quot;never mind&quot;];

    type T1 = SetRemoval&lt;Set1, &quot;foo&quot;&gt;;
    type T2 = SetRemoval&lt;Set1, [&quot;foo&quot;]&gt;;
    type T3 = SetRemoval&lt;[...Set1, ...Set2], [&quot;foo&quot;, &quot;never mind&quot;]&gt;;    
    
    type cases = [
      Expect&lt;Equal&lt;T1, readonly [&quot;bar&quot;, &quot;baz&quot;]&gt;&gt;,
      Expect&lt;Equal&lt;T2, readonly [&quot;bar&quot;, &quot;baz&quot;]&gt;&gt;,
      Expect&lt;Equal&lt;T3, readonly [&quot;bar&quot;, &quot;baz&quot;, &quot;bat-shit-crazy&quot;]&gt;&gt;,
    ];
    const cases: cases = [ true, true, true ];
  });

});
</code></pre>
<p>What this type utility is not important only that you can see the &quot;shape&quot; of how a test of the type system can be incorporated into a traditional unit testing framework.</p>
<p>The great thing about this type of testing is that:</p>
<ol>
<li>type errors become immediately visible in any editor which highlights type errors</li>
<li>using <code>tsc</code> over the test files can be used to ensure no type errors exist across tests</li>
</ol>
<p>Today I use <strong>Vitest</strong> primarily for unit testing but before that I used Jest, Mocha, and UVU. Most of these test runners will fully ignore type errors and UVU refused to run if there was a type error anywhere in the file. Neither condition is ideal as your &quot;type tests&quot; are either summarized as passing or you lose a lot of test coverage (aka, all tests in a file) whenever there is a type error.</p>
<p>What I would <strong>like</strong> is the ability to simply test the type validity of a &quot;block&quot; of code rather than a file's. I'm sure this can be <em>created</em> and I've been known to re-create the wheel from time to time but secretly hoping that someone knows of some tooling to do this that already exists in the wild.</p>
",https://stackoverflow.com/questions/75112269/integrating-type-tests-into-unit-tests-with-typescript,"['typescript', 'unit-testing']",35,False,1,0
DynamicTestModule throws error on angular unit testing,"<p>I'm currently creating a unit testing with Karma and Jasmine as:</p>
<pre><code>describe('ProfileListComponent', () =&gt;  {
let component: ProfileListComponent;

beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
        imports: [
            [RouterModule.forRoot([])],
            FormsModule
        ],
        declarations: [
            ProfileListComponent,
            ProfilesFiltersComponent,
            DatatableComponent,
            ProfileImagePopoverComponent,
            NgbHighlight,
            NgbRating,
            PaginationFooterComponent
        ],
        providers: []
    }).compileComponents();

    TestBed.configureTestingModule({
        declarations: [ ProfileListComponent ]
    })
    .createComponent(ProfileListComponent);
}));


it('should be 4', async(() =&gt; {
    expect(component.add(2,2)).toEqual(4);
}))

});
</code></pre>
<p>The profile list component has many childs, which is why I imported them on <code>declarations</code>. The <code>ProfilesFiltersComponent</code> uses angular Forms as:</p>
<p><strong>HTML:</strong></p>


<p><strong>TS</strong></p>
<pre><code>export class ProfilesFiltersComponent implements OnInit {
 filterForm: FormGroup;
}
</code></pre>
<p>So, the testing asking me for the form group as:</p>
<blockquote>
<p>Can't bind to 'formGroup' since it isn't a known property of 'form'</p>
</blockquote>
<p>So I added it to <code>declarations</code> on the testing as:</p>
<pre><code> declarations: [
    ...
    FormGroup
    ]
</code></pre>
<p>But now it is throwing a new error:</p>
<blockquote>
<p>Failed: Unexpected value 'FormGroup' declared by the module
'DynamicTestModule'. Please add a @Pipe/@Directive/@Component
annotation.</p>
</blockquote>
<p>That I have no idea how to solve; what am I doing wrong?</p>
",https://stackoverflow.com/questions/75154122/dynamictestmodule-throws-error-on-angular-unit-testing,"['angular', 'typescript', 'jasmine', 'karma-jasmine']",53,False,0,1
How to mock non exported const variables with jest,"<p>I have below file with one non exported constant variable.<br />
I am trying to mock the variable value for the purpose of unit testing functions.<br />
This file is common and used across the project, so it is affecting UT of other files as well.</p>
<pre><code>// state.js

// I want to mock value of this variable
const appState = {};

// There are around 20+ functions which generates some values 
// and store in the appState when application runs

export function generateFoo() {
   // Call HTTP request and get result 
   const result = getHttp('/path/foo');
   appState.foo = {
      someValue: 10
   };
}

// Then I have functions which reads + calculate and return 
// Properties fro mthe appState  

export function getFoo() {
   const foo = appState.foo;
   // Do some calculation and return 
   foo.someValue = foo.someValue + 10;
   return foo;
}

</code></pre>
<p>What I am trying is, set some default value to <code>appState</code> when running the unit test.<br />
But I am not able to do that.</p>
<p>Solutions that I did try.</p>
<p><strong>Solution #1</strong></p>
<pre><code>const rewire = require('rewire');
const stateRewire = rewire('state.js');
const appState = {
   someValue: 10,
};
stateRewire.__set__('appState', appState);
await stateRewire();

// I get error: TypeError: Assignment to constant variable. 
</code></pre>
<p><strong>Solutions #2</strong></p>
<pre><code>jest.mock('state', () =&gt; {
  const originalModule = jest.requireActual('state.js');
  return {
    __esModule: true,
    ...originalModule,
    appState: {
      someValue: 10,
    }
  };
});

// It does not refer to mock and gets the original `appState`
</code></pre>
<p><strong>Solutions #3</strong></p>
<pre><code>jest.doMock('state', () =&gt; {
  const originalModule = jest.requireActual('state.js');

  return {
    __esModule: true,
    appState: {
      someValue: 10,
    },
    ...originalModule
  };
});
</code></pre>
<p>I did refer to all the posts in <code>stackoverflow</code> but none of them did help.<br />
Anyone did face this?</p>
",https://stackoverflow.com/questions/75684627/how-to-mock-non-exported-const-variables-with-jest,"['javascript', 'unit-testing', 'jestjs', 'rewire']",93,False,0,0
How to get code coverage report from manual testing,"<p>I wanted to generate Istanbul report in Angular of manual testing. Means suppose we have a button and that button is having a function call in TS. So from UI if I am clicking on button, then that click method of TS was called, and API call happend(if any). So this kind of report I wanted to generate in istanbul.</p>
<p>I tried with <code>ng test --code-coverage</code>, but it gives the report of unit test what we have written.</p>
<p>But I wanted to have manual test code coverage.</p>
<p>So can I achieve this?</p>
<p>I am using jasmine and karma for unit testing.</p>
",https://stackoverflow.com/questions/75473448/how-to-get-code-coverage-report-from-manual-testing,"['javascript', 'angular', 'typescript', 'jasmine', 'karma-jasmine']",23,False,0,0
Chai-mocha giving different results for same test cases when being run multiple times,"<p>I am new to unit testing and I started learning Chai-Mocha to test my NodeJs API. But I have been constantly facing an issue which is hindering my project. When I run the command &quot;npm test&quot; multiple times for same test cases, some times the test cases pass , sometimes they fail. Literally for the exact same code. Here is the test file.</p>
<pre><code>process.env.NODE_ENV = &quot;test&quot;;

const chai = require(&quot;chai&quot;);
const expect = chai.expect;
const should = chai.should();
const chaiHttp = require(&quot;chai-http&quot;);
const server = require(&quot;../index&quot;);
const mongoose = require(&quot;mongoose&quot;);
const Book = require(&quot;../API/models/Book&quot;);
const User = require(&quot;../API/models/User&quot;);
const jwt = require(&quot;jsonwebtoken&quot;);
const dotenv = require(&quot;dotenv&quot;);

dotenv.config();

const key = process.env.SECRET_KEY;

chai.use(chaiHttp);

describe(&quot;Books Test Cases&quot;, function () {
  before((done) =&gt; {
    mongoose.connect(process.env.MONGO_URL, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    const db = mongoose.connection;

    db.on(&quot;error&quot;, console.error.bind(console, &quot;connection error!!&quot;));
    db.once(&quot;open&quot;, () =&gt; {
      console.log(&quot;Successfull Connection!!!&quot;);
      done();
    });
  });

  let tokenAdmin;
  let tokenUser;
  let bookId;

  it(&quot;Should signup a new user on POST /auth/signup&quot;, (done) =&gt; {
    const newUser = {
      email: &quot;testavg1@gmail.com&quot;,
      username: &quot;avg1User&quot;,
      password: &quot;pass1234&quot;,
      isAdmin: false,
    };

    chai
      .request(server)
      .post(&quot;/api/auth/signup&quot;)
      .send(newUser)
      .end((err, res) =&gt; {
        res.should.have.status(201);
      });
    done();
  });

  it(&quot;Should signup an admin on POST /auth/signup&quot;, (done) =&gt; {
    const newUser = {
      email: &quot;admintest@gmail.com&quot;,
      username: &quot;admintest&quot;,
      password: &quot;pass1234&quot;,
      isAdmin: true,
    };

    chai
      .request(server)
      .post(&quot;/api/auth/signup&quot;)
      .send(newUser)
      .end((err, res) =&gt; {
        res.should.have.status(201);
      });
    done();
  });

  it(&quot;Should login the admin and fill the token on POST /auth/login&quot;, (done) =&gt; {
    const loginDetails = {
      email: &quot;admintest@gmail.com&quot;,
      password: &quot;pass1234&quot;,
    };
    chai
      .request(server)
      .post(&quot;/api/auth/login&quot;)
      .send(loginDetails)
      .end((err, res) =&gt; {
        res.body.should.have.property(&quot;accessToken&quot;);
        tokenAdmin = res.body.accessToken;
        done();
      });
  });

  it(&quot;Should allow the admin to add a new book on /books POST&quot;, (done) =&gt; {
    const newBook = {
      authorName: &quot;TestName 1&quot;,
      coverName: &quot;Test covername 1&quot;,
      genre: &quot;testGenre&quot;,
    };
    chai
      .request(server)
      .post(&quot;/api/books/&quot;)
      .set({ Authorization: `Bearer ${tokenAdmin}` })
      .send(newBook)
      .end((err, res) =&gt; {
        res.should.have.status(201);
        res.body.should.be.an(&quot;object&quot;);
        res.body.data.should.include({
          authorName: &quot;TestName 1&quot;,
          coverName: &quot;Test covername 1&quot;,
          genre: &quot;testGenre&quot;,
        });
      });
    done();
  });

  it(&quot;Should get the desired book and fill the book id&quot;, async () =&gt; {
    const tempBook = await Book.findOne({
      coverName: &quot;Test covername 1&quot;,
      authorName: &quot;TestName 1&quot;,
    });
    console.log(tempBook, &quot;hehe&quot;);
    bookId = tempBook._id.toString();
    expect(tempBook).to.be.an(&quot;object&quot;);
    expect(tempBook).to.have.property(&quot;_id&quot;);
  });

  it(&quot;Should get a book by id on GET /books/:id endpoint&quot;, (done) =&gt; {
    chai
      .request(server)
      .get(`/api/books/${bookId}`)
      .end((err, res) =&gt; {
        res.should.have.status(200);
        res.body.should.be.an(&quot;object&quot;);
        // console.log(res.body, &quot;hellooo&quot;);
      });
    done();
  });

  it(&quot;Should allow admin to modify a book details on /update/:id &quot;, (done) =&gt; {
    const updatedBook = {
      authorName: &quot;TestName updated&quot;,
      coverName: &quot;Test covername updated&quot;,
      genre: &quot;testGenre&quot;,
    };
    chai
      .request(server)
      .patch(`/api/books/update/${bookId}`)
      .set({ Authorization: `Bearer ${tokenAdmin}` })
      .send(updatedBook)
      .end((err, res) =&gt; {
        res.should.have.status(200);
        res.body.should.include({ message: &quot;The book has been updated!&quot; });
        done();
      });
  });

  it(&quot;Should login the normal user and fill the token on POST /auth/login&quot;, (done) =&gt; {
    const loginDetails = {
      email: &quot;testavg1@gmail.com&quot;,
      password: &quot;pass1234&quot;,
    };
    chai
      .request(server)
      .post(&quot;/api/auth/login&quot;)
      .send(loginDetails)
      .end((err, res) =&gt; {
        res.body.should.have.property(&quot;accessToken&quot;);
        tokenUser = res.body.accessToken;
        done();
      });
  });

  it(&quot;Should deny a normal user to add a new book on POST /books&quot;, (done) =&gt; {
    const newBook = {
      authorName: &quot;TestName 2&quot;,
      coverName: &quot;Test covername 2&quot;,
      genre: &quot;Test genre 2&quot;,
    };
    chai
      .request(server)
      .post(&quot;/api/books/&quot;)
      .set({ Authorization: `Bearer ${tokenUser}` })
      .send(newBook)
      .end((err, res) =&gt; {
        res.should.have.status(403);
        res.body.should.be.an(&quot;string&quot;);
        res.body.should.be.eql(&quot;Only admin can add a book!&quot;);
        done();
      });
  });

  it(&quot;Should deny a normal user to update a book&quot;, (done) =&gt; {
    const updatedBook = {
      authorName: &quot;TestName updated&quot;,
      coverName: &quot;Test covername updated&quot;,
      genre: &quot;testGenre&quot;,
    };
    chai
      .request(server)
      .patch(`/api/books/update/${bookId}`)
      .set({ Authorization: `Bearer ${tokenUser}` })
      .send(updatedBook)
      .end((err, res) =&gt; {
        res.should.have.status(403);
        res.body.should.be.an(&quot;string&quot;);
        res.body.should.be.eql(&quot;Only admin can update a book!&quot;);
        done();
      });
  });

  it(&quot;Should get the list of all books in library on GET /books&quot;, (done) =&gt; {
    chai
      .request(server)
      .get(&quot;/api/books/&quot;)
      .end((err, res) =&gt; {
        res.should.have.status(200);
        res.body.should.be.a(&quot;array&quot;);
        console.log(res.body);
        done();
      });
  });

  it(&quot;Should get the list of all books of a genre in library on GET /books/Genre/:genre &quot;, (done) =&gt; {
    chai
      .request(server)
      .get(&quot;/api/books/Genre/testGenre&quot;)
      .end((err, res) =&gt; {
        res.should.have.status(200);
        res.body.should.be.a(&quot;array&quot;);
        console.log(res.body);
        done();
      });
  });

  after((done) =&gt; {
    // Remove all books after all test cases
    Book.deleteMany({}, (err) =&gt; {
      if (err) {
        throw err;
      }
      done();
    });
  });

  after((done) =&gt; {
    // Remove all users after all test cases
    User.deleteMany({}, (err) =&gt; {
      if (err) {
        throw err;
      }
      done();
    });
  });
});



</code></pre>
<p>I was expecting it to give same result each time, but it gives wrong or correct output randomly. All the test cases should pass when it executes properly but sometimes some test cases randomly fail</p>
",https://stackoverflow.com/questions/75235137/chai-mocha-giving-different-results-for-same-test-cases-when-being-run-multiple,"['node.js', 'unit-testing', 'testing', 'mocha.js', 'chai']",50,False,0,0
How to write test cases using react-testing-library with the change of useState?,"<p>I'm new to unit testing. Currently, I'm working on a react-typescript project that requires me to unit test each component. Here, I'm testing with the if condition and rendering another component in my app in response to the change in useState value.</p>
<p>Here is my app.tsx</p>
<pre><code>import ControllerComponent from './controller-component/controller-component';
export interface ControllerWidgetProps {
  title?: string,
  ....
}
export function ControllerWidget(
  props: ControllerWidgetProps
) {
const [value1,setValue1]=useState(-1);
...

return (
    &lt;Card&gt;       
     &lt;Typography &gt;         
         {props.title}
       &lt;/Typography&gt;
      &lt;Grid container spacing={1} pt={0} pb={0} sx={{marginTop:-2,marginLeft:-2}}&gt;      
      &lt;Grid  item xs={12} md={2}&gt;      
      &lt;Box&gt;             
       {(value1 == -1)? (
               &lt;ControllerComponent name=&quot;xyz&quot;  image=&quot;group 55.png&quot;  /&gt; ) : (value1 == 1 ) ? (
              &lt;ControllerComponent name=&quot;abc&quot;  image=&quot;group 56.png&quot; /&gt;):( value1 == 2)) ?(
              &lt;ControllerComponent name=&quot;pqr&quot;  image=&quot;group 57.png&quot;/):(&lt;&gt;&lt;/&gt;)}
             &lt;/&gt;         
))}

export default UiControllerWidget;
</code></pre>
<p>Here with the values of <code>value1</code> I am passing different props to the <code>contollerComponent</code>. So, I just need to test whether the desired props passed with the change of values of <code>value1</code>.</p>
<p>Here is my test file</p>
<pre><code>describe('UiControllerWidget', () =&gt; {
  it('should render successfully', () =&gt; {
  const { baseElement } = render(
    &lt;Provider store={store} &gt;  &lt;UiControllerWidget title={''} /&gt;  &lt;/Provider&gt;);
  expect(baseElement).toBeTruthy();
});

});
</code></pre>
<p>Can someone help with this case? How to test whether correct component render with <code>value1</code>?.Thank you in advance!</p>
",https://stackoverflow.com/questions/75443946/how-to-write-test-cases-using-react-testing-library-with-the-change-of-usestate,"['reactjs', 'unit-testing', 'react-hooks', 'react-testing-library', 'ts-jest']",26,False,0,0
How to test eventListeners on input field and mock value using Jest,"<p>I'm pretty new with unit testing and would like to dive into testing, mostly testing eventListeners.</p>
<p>I'm trying to test if the value of an input text field matches the values in a mock array, as in simulating the user typing and returning a list of suggestions.</p>
<p>Here's my code:</p>
<pre><code>const mockResultsData = [
    'Paris',
    'Lisbon',
    'Madrid',
    'Milan',
    'Malta',
];

let spy;
beforeAll(() =&gt; {
    spy = jest.spyOn(document, 'addEventListener');
});

describe(&quot;Check if user input value contains results&quot;, () =&gt; {
    let mockElement;
    beforeAll(() =&gt; {
        //create the mock element
        mockElement = document.createElement('input');
        document.body.appendChild(mockElement);
        spy.mockReturnValue(mockElement.value = 'Paris');
    });

    it('should contain matched results from user search', () =&gt; {
        expect(mockResultsData).toContain(mockElement.value);
    });
});
</code></pre>
<p>So far the tests pass but how can I add the 'input' event to the test? Do I always need to define a value on the input.value? How can I set it as if the user is typing 'MA' and it should test if 'Madrid' and 'Malta' is in the array?</p>
",https://stackoverflow.com/questions/76185726/how-to-test-eventlisteners-on-input-field-and-mock-value-using-jest,"['javascript', 'unit-testing', 'jestjs']",28,False,0,0
Flutter mocking http call response,"<p>I have this ApiConnect class that uses a http client to connect to dummy api,</p>
<pre><code>  static final ApiConnect instance = ApiConnect._();
  dynamic _reqBody;

  ApiConnect._() {
    baseUrl = EndPoints.baseUrl;
    logPrint = print;
    timeout = EndPoints.timeout;

    httpClient.addRequestModifier&lt;dynamic&gt;((request) {
      logPrint('************** Request **************');
      _printKV('uri', request.url);
      _printKV('method', request.method);
      _printKV('followRedirects', request.followRedirects);
      logPrint('headers:');
      request.headers.forEach((key, v) =&gt; _printKV(' $key', v));
      logPrint('data:');
      if (_reqBody is Map) {
        _reqBody?.forEach((key, v) =&gt; _printKV(' $key', v));
      } else {
        _printAll(_reqBody.toString());
      }
      logPrint('*************************************');
      return request;
    });

    httpClient.addResponseModifier((request, response) {
      logPrint('************** Response **************');
      _printKV('uri', response.request!.url);
      _printKV('statusCode', response.statusCode!);
      if (response.headers != null) {
        logPrint('headers:');
        response.headers?.forEach((key, v) =&gt; _printKV(' $key', v));
      }
      logPrint('Response Text:');
      _printAll(response.bodyString);
      logPrint('*************************************');
      return response;
    });
  }

  late void Function(Object object) logPrint;

  @override
  Future&lt;Response&lt;T&gt;&gt; get&lt;T&gt;(
    String url, {
    Map&lt;String, String&gt;? headers,
    String? contentType,
    Map&lt;String, dynamic&gt;? query,
    Decoder&lt;T&gt;? decoder,
  }) {
    _checkIfDisposed();

    Map&lt;String, String&gt; _headers = headers ?? &lt;String, String&gt;{};
    // _headers[&quot;Authorization&quot;] = &quot;Bearer &quot; + HiveAdapter.getAccessToken();

    _reqBody = query;
    return httpClient.get&lt;T&gt;(
      url,
      headers: _headers,
      contentType: contentType,
      query: query,
      decoder: decoder,
    )..whenComplete(() =&gt; _reqBody = null);
  }
</code></pre>
<p>and here is how i call this function on</p>
<pre><code>import 'package:trial/app/data/api/api_connect.dart';
import 'package:trial/app/data/model/user.dart';
import 'package:trial/app/utils/constants.dart';

class HomeProvider {
  HomeProvider();

  ApiConnect api = ApiConnect.instance;

  Future&lt;List&lt;User&gt;&gt; getUser() async {
    List&lt;User&gt; user = &lt;User&gt;[];
    api.get(EndPoints.user, headers: {&quot;app-id&quot;: &quot;myAppID&quot;}).then((response) {
      response.body['data'].forEach((value) {
        user.add(User.fromJson(value));
      });
    }).catchError((error) {
      print(error.toString());
    });
    return user;
  }
}
</code></pre>
<p>Now I would like to have a unit test if this function works properly,</p>
<p>Here is my test file:</p>
<pre><code>

import 'package:flutter_test/flutter_test.dart';
import 'package:get/get_connect/http/src/response/response.dart';
import 'package:mockito/mockito.dart';
import 'package:trial/app/data/api/api_connect.dart';
import 'package:trial/app/data/api/api_error.dart';
import 'package:trial/app/data/model/user.dart';
import 'package:trial/app/data/provider/home_provider.dart';
import 'package:trial/app/utils/constants.dart';

class MockApiConnect extends Mock implements ApiConnect {}

void main() {
  group('HomeProvider', () {
    late HomeProvider homeProvider;
    late MockApiConnect mockApiConnect;

    setUp(() {
      mockApiConnect = MockApiConnect();
      homeProvider = HomeProvider();
      homeProvider.api = mockApiConnect;
    });

    test('getUser returns list of users on success', () async {
      // arrange
      final response = {
        'data': [
          {'id': 1, 'firstName': 'John Doe'},
          {'id': 2, 'firstName': 'Jane Doe'}
        ]
      };
      when(mockApiConnect.get(EndPoints.baseUrl, headers: {&quot;app-id&quot;: &quot;myAppID&quot;})).thenAnswer(
        (_) async =&gt; Response(body: response, statusCode: 200),
      );

      // act
      final result = await homeProvider.getUser();

      // assert
      expect(result, isA&lt;List&lt;User&gt;&gt;());
      expect(result.length, equals(2));
      expect(result[0].id, equals(1));
      expect(result[0].firstName, equals('John Doe'));
      expect(result[1].id, equals(2));
      expect(result[1].firstName, equals('Jane Doe'));
    });
  });
}

</code></pre>
<p>But on testing, it shows this error:</p>
<pre><code>type 'Null' is not a subtype of type 'Future&lt;Response&lt;dynamic&gt;&gt;'
test/file_test.dart 12:7   MockApiConnect.get
test/file_test.dart 33:27  main.&lt;fn&gt;.&lt;fn&gt;
</code></pre>
<p>I have been dealing with this problem for a week now, google search already on page 12 and asked chatgpt about it but it makes me go through circles.
I am fairly new to unit testing and I am having a hard time testing http calls on flutter. Thank you in advance.</p>
",https://stackoverflow.com/questions/75947184/flutter-mocking-http-call-response,"['flutter', 'dart', 'unit-testing', 'http', 'mocking']",77,False,0,0
How to verify OceanBase Community Edition Patch through Unit Testing before submitting pull request?,"<p>I am working on contributing code to the OceanBase community edition and have created a patch. I am using the latest version of the OceanBase community edition and am working in a CentOS environment. I have prepared the code for unit testing and would like to verify my patch before submitting a pull request on GitHub.</p>
<p>Are there any pre-build scripts or shell commands available for running unit tests? Or, should I go through the CMake process first?</p>
<p>I want to ensure that everything runs smoothly during the unit test phase before submitting my patch. Thank you for your help.</p>
",https://stackoverflow.com/questions/76125776/how-to-verify-oceanbase-community-edition-patch-through-unit-testing-before-subm,"['github', 'cmake', 'pull-request', 'oceanbase']",15,False,0,0
how can i do a unit testing of axios.create mock with vitest?,"<p>i am learning unit testing in vue with typescript and i want to test this function</p>
<pre><code>const getCLients =async (): Promise&lt;Client[]&gt; =&gt; {
        const {data} = await clientsApi.get('/clients')
        return data
}
</code></pre>
<p>But i got an error due to the clientsApi. My clients api is aun axios instance and looks like this:</p>
<pre><code>import axios from 'axios'

const clientsApi = axios.create({
   baseURL:import.meta.env.VITE_API_URL
})
export default clientsApi
</code></pre>
<p>my error is this:</p>
<blockquote>
<p>TypeError: Cannot read properties of undefined (reading 'get')
❯ getCLients ../src/clients/composables/useClients.ts:14:41</p>
</blockquote>
<blockquote>
<p>14|         const {data} = await clientsApi.get('/clients')</p>
</blockquote>
<p>In my tests i have done the axios mock:</p>
<pre><code>vi.mock('axios')
const mockedAxios = axios as jest.Mocked&lt;typeof axios&gt;;

mockedAxios.get.mockResolvedValue({
            data: mockClients,
})
</code></pre>
<p>I suposed that i had to make a mock of the axios.create but i have tried with a lot of ways but i always got the same typoe error. I need your help, how could you solve this?</p>
",https://stackoverflow.com/questions/75093486/how-can-i-do-a-unit-testing-of-axios-create-mock-with-vitest,"['typescript', 'axios', 'vuejs3', 'vitest', 'axios-mock-adapter']",1319,True,3,1
"Why can&#39;t I access .env variables when unit testing Firebase (Cloud) Functions with firebase-functions-test, mocha, and Emulator Suite?","<p>I have a Firebase Project using Functions, Storage, and Auth that I would like to do some rudimentary unit testing using mocha and the Emulator Suite (already working for local development).</p>
<p>I've read the documentation front to back several times and I don't seem to understand how to set this up. My specific challenge currently is that I cannot seem to get a simple function that returns a defined environment variable to return properly due to the environment variables not loading.</p>
<p>My setup is as follows:</p>
<p><em>functions/index.js</em></p>
<pre class=""lang-js prettyprint-override""><code>const functions = require(&quot;firebase-functions&quot;)
const admin = require('firebase-admin')
admin.initializeApp()
const { getFunctions } = require('firebase-admin/functions')
...
exports.requiresEnvVariable = functions.https.onCall((data, context) =&gt; {
  return process.env.MYENV_VARIABLE || ':('
})
  
</code></pre>
<p><em>functions/tests/test.spec.js</em></p>
<pre class=""lang-js prettyprint-override""><code>const { expect } = require(&quot;chai&quot;)
const sinon = require(&quot;sinon&quot;)
const admin = require(&quot;firebase-admin&quot;)
  
console.log(process.env.GCLOUD_PROJECT)
  
const test = require(&quot;firebase-functions-test&quot;)({
  projectId: process.env.GCLOUD_PROJECT
}, 'serviceAccount.json')

// I've played with calling this here and stubbing, asmentioned in the docs. Nothing seems to work.
//admin.initializeApp()
//adminInitStub = sinon.stub(admin, 'initializeApp')

const myFunctions = require(&quot;../index&quot;)

describe(&quot;Unit tests&quot;, () =&gt; {
  it(&quot;A good and cool test description&quot;, async () =&gt; { 
    const wrapped = test.wrap(myFunctions.getTToken)
    const data = {}
    const result = await wrapped(data)
    expect('yayitworked').to.eql(result)
  })
})
</code></pre>
<p>functions/package.json</p>
<pre class=""lang-js prettyprint-override""><code>{
  &quot;name&quot;: &quot;functions&quot;,
  &quot;description&quot;: &quot;Cloud Functions for Firebase&quot;,
  &quot;scripts&quot;: {
    &quot;serve&quot;: &quot;firebase emulators:start --only functions&quot;,
    &quot;shell&quot;: &quot;firebase functions:shell&quot;,
    &quot;start&quot;: &quot;npm run shell&quot;,
    &quot;deploy&quot;: &quot;firebase deploy --only functions&quot;,
    &quot;logs&quot;: &quot;firebase functions:log&quot;,
    &quot;tests&quot;: &quot;mocha --exit tests/*.spec.js&quot;
  },
  &quot;engines&quot;: {
    &quot;node&quot;: &quot;18&quot;
  },
  &quot;main&quot;: &quot;index.js&quot;,
  &quot;dependencies&quot;: {
    &quot;axios&quot;: &quot;^1.1.3&quot;,
    &quot;cors&quot;: &quot;^2.8.5&quot;,
    &quot;firebase-admin&quot;: &quot;^11.4.1&quot;,
    &quot;firebase-functions&quot;: &quot;^4.1.1&quot;,
  },
  &quot;devDependencies&quot;: {
    &quot;chai&quot;: &quot;^4.3.7&quot;,
    &quot;firebase-functions-test&quot;: &quot;^3.0.0&quot;,
    &quot;mocha&quot;: &quot;^10.2.0&quot;,
    &quot;sinon&quot;: &quot;^15.0.1&quot;
  },
  &quot;private&quot;: true
}

</code></pre>
<p>functions/.env</p>
<pre><code>MYENV_VARIABLE=yayitworked
</code></pre>
<p>And I run from the <em>functions</em> folder:</p>
<pre class=""lang-bash prettyprint-override""><code>firebase emulators:exec 'npm run tests'
</code></pre>
<p>giving <code>AssertionError: expected ':(' to deeply equal 'yayitworked'</code></p>
<p>Why can I not access the environment variables?</p>
",https://stackoverflow.com/questions/75113680/why-cant-i-access-env-variables-when-unit-testing-firebase-cloud-functions-w,"['firebase', 'unit-testing']",214,True,1,1
Unit Testing for dynamodb-onetable,"<p>I am new to Unit Testing and wanted to stub dynamodb-onetable library. I was trying to stub getData() from getDetails.ts file but it shows that &quot;<strong>OneTableArgError: Missing Name Property</strong>&quot;. Because this getProjectDetails() contain new Table() class.
How to stub dynamodb-onetable so that I can get data in dataDetails variable. I was doing something like this in getEmp.spec.ts</p>
<p>dataDetailsStub = sinon.stub(DataService , &quot;getData&quot;);</p>
<pre><code>------lambda.ts
     import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
     import Dynamo from 'dynamodb-onetable/Dynamo';
     export const client = new Dynamo({
                            client: new DynamoDBClient({
                            region: REGION,   }),
                           });

-------DataService.ts
import { client } from '../lambda';
const workspaceTable = new Table({
  client,
  name: TableName,
  schema,
  logger: true,
  partial: false,
});
const projectDetail = workspaceTable.getModel('empDetail');

export default class **DataService** {
  static getData = async (empId: string, type: string) =&gt; {
    const params = {
      projectId,
      type
    };
    const response = await empDetail.find(params);
    logger.trace('response', { response });
    return response;   };
 }


------getDetails.ts
    const dataDetails= await DataService.getData(
      empId,
      'EMPLOYEE-SAVEDATA'
    );
</code></pre>
<p>I was trying to stub the DataService.getData() but getting error saying &quot;OneTableArgError: Missing &quot;name&quot; property&quot;. I want to get data in dataDetailsStub whatever i am sending while mocking the getData()</p>
<pre><code>const dataDetailsStub = sinon.stub(DataService , &quot;getData&quot;).return({emp object});
</code></pre>
<p>Can anyone help me out on this. I'm really got stuck in this. Thanks in advance</p>
",https://stackoverflow.com/questions/75385216/unit-testing-for-dynamodb-onetable,"['javascript', 'typescript', 'amazon-dynamodb']",109,False,1,0
How to await on an Subject.next in RXJS?,"<p>I've a component that I'm currently unit-testing.
This component takes a service as input. This services provides an observable.</p>
<pre><code>export class SomeComponent implements OnInit{
    private _subscription:Subscription;

    constructor(private someService:SomeService){
    }
    
    ngOnInit(){
        this.subscription = this.someService.someObservable.subscribe(async v=&gt;await this.doSomethingWithValue(v));
    }
    
    ngOnDestroy(){
        this.subscription.unsubscribe();
    }
    
    async doSomethingWithValue(v){
        await this.someService.doSomeAsyncCall();
        //...   
    }   
}

export class SomeService{
    public someObservable:Observable&lt;string&gt;;
    
    constructor(){
        this.someObservable = //subscription to multiple other services, transformations and consolidation.
    }
    
    async doSomeAsyncCall(){
        await something...
    }
}
</code></pre>
<p>To unit test it, I need to mock this observable(currently using <code>ng-mocks</code>, but same issue would also happen with other tests.</p>
<pre><code>it('should update correctly when XYZ', async ()=&gt; {
    
    const notifications = new Subject&lt;string&gt;();
    MockInstance(SomeService, 'someObservable', notifications.asObservable());  
    const component = MockRender(SomeComponent).point.componentInstance;
    
    notifications.next('something');
    
    expect(something);//This is being called before the `doSomethingWithValue` get called
    
})
</code></pre>
<p>My issue is that my <code>expect</code> being instantly after the <code>notification.next</code>, before the execution of <code>doSomethingWithValue</code>.</p>
<p>I cannot wait on <code>notifications.next(...)</code>, because it doesn't returns observable or promise.</p>
<p>How would you ensure all async call behind any <code>Subject</code> have been properly awaited? This happens with a test but also could happens in non-test code.</p>
<p>And obviously, the goal is not to wait on a random amount of time that would not always work.</p>
",https://stackoverflow.com/questions/75541965/how-to-await-on-an-subject-next-in-rxjs,"['angular', 'async-await', 'rxjs', 'observable']",28,True,1,1
iOS unit testing async function not called,"<p>How to test that an async function is not called in iOS unit testing?</p>
<p>I know how to test that an async function IS called: by using XCTestExpectation and expectation fulfill. But how to test that a function is not called?</p>
<p>Context: There are four potential async function within a launcher, and with the specific argument, one of these functions should be called and the other three shouldn't. I know how to write a unit test to make sure that the function that needs to be called is called, but don't know how to write a test to test if the other three functions are not touched. Thanks for helping!</p>
",https://stackoverflow.com/questions/75679458/ios-unit-testing-async-function-not-called,"['ios', 'swift']",42,True,0,1
UISwitch Unit test with sendActions(for: .valueChanged),"<p><strong>GOAL:</strong> I'm currently unit testing the behavior of my UISwitch when it is pressed.</p>
<p><strong>ISSUE:</strong> My issue I that the <code>sendActions(for: .valueChanged)</code> that I use to programmatically change the UISwitch's state is not working as I imagined. It doesn't make it change from <code>false</code> to <code>true</code> (in my example).</p>
<p><strong>WHAT DID I DO ?:</strong> I'm using the following path:</p>
<ol>
<li>I declared my UISwitch as <code>true</code></li>
<li>I used <code>sendActions(for: .valueChanged)</code> for changing it to <code>false</code></li>
<li>I finally used <code>XCTAssertEqual()</code> to check if it correctly equal to <code>false</code> as expected. (I also could have used <code>XCTAssertFalse()</code> to check directly if it was <code>false</code>.</li>
</ol>
<p>Ps: I correctly passed <code>loadViewIfNeeded()</code> in my <code>setUPWithError()</code></p>
<p><strong>QUESTION:</strong> How can I test my UISwitch ??</p>
<p><strong>CODE:</strong> Here is my code:</p>
<pre><code>    var sut: ViewController!
    
    override func setUpWithError() throws {
        super.setUp()
        let storyboard = UIStoryboard(name: &quot;Main&quot;, bundle: nil)
        sut = storyboard.instantiateViewController(withIdentifier: &quot;ViewController&quot;) as? ViewController
        sut.loadViewIfNeeded()
    }

    func testGenderButton_ShouldUpdateValueWhenPressed() {
        sut.genderSwitch.isOn = true
        sut.genderSwitch.sendActions(for: .valueChanged)
        XCTAssertEqual(sut.genderSwitch.isOn, false, &quot;\(sut.genderSwitch.isOn) should be equal to false&quot;)
    }
</code></pre>
",https://stackoverflow.com/questions/75738665/uiswitch-unit-test-with-sendactionsfor-valuechanged,"['swift', 'unit-testing', 'uikit', 'xctest', 'uiswitch']",110,True,-1,2
Python unittest mocking not working as expected,"<p>I got this project structure:</p>
<pre><code>my_project 
├── __init__.py
├── app.py
├── helpers
│   └── __init__.py
└── tests
    ├── __init__.py
    ├── integration
    │   ├── __init__.py
    │   └── test_app.py
    └── unit
        ├── __init__.py
        └── test_helpers.py
</code></pre>
<p>So far, unit testing for <code>helpers</code> hasn't been complicated, i'd patch 3rd parties and some functions within helpers.</p>
<p>The integration testing in <code>tests/integration/test_app.py</code> is being a bit of a blocking point because the patching isn't doing what i need it do to.
For example, I got a method like this:</p>
<p>helpers/<strong>init</strong>.py:</p>
<pre class=""lang-py prettyprint-override""><code>def compute_completeness_metric(
        vendor,
        product,
        fields,
        endpoint):
    body = {&quot;vendor&quot;: vendor, &quot;product&quot;: product, &quot;fields&quot;: fields}
    response_json = requests.post(
        &quot;http://example.com&quot;, json=body)
    if response_json.status_code != 200:
        response_json = &quot;Can't compute&quot;
    else:
        response_json = response_json.json()
    return response_json
</code></pre>
<p>Now, in app.py, I call it the following way:</p>
<pre class=""lang-py prettyprint-override""><code>from helpers import compute_completeness_metric
def main(req: func.HttpRequest) -&gt; func.HttpResponse:
    final_results = {}
    final_results = compute_completeness_metric(vendor, product, fields, endpoint)
...
</code></pre>
<p>And when testing, I try to patch it the following way:</p>
<pre class=""lang-py prettyprint-override""><code>    @patch('data_quality.helpers.compute_completeness_metric')
    def test_app(self, mock_compute_completeness_metric):
      mock_compute_completeness_metric.return_value = &quot;blablabla&quot;
</code></pre>
<p>But the mocked methods do not return what they're supposed to return, instead execute themselves as if they weren't mocked.</p>
<p>Am I missing something? Should I be mocking the methods within <code>get_rule_data_models()</code> ?</p>
<p>TIA!</p>
",https://stackoverflow.com/questions/75158187/python-unittest-mocking-not-working-as-expected,"['python', 'unit-testing', 'integration-testing', 'python-unittest']",47,True,0,1
Nest Js Jest Unit Testing: Providing a mock implementation not used from controller,"<p>I have already a mock class implemented as a part of my previous work, which I want to provide as a part of my Jest Unit Testing.</p>
<p>Let me explain in code, that's better:</p>
<p>My Controller code:</p>
<pre class=""lang-js prettyprint-override""><code>export class VpcController {
  constructor(private readonly vpcService: VpcService) {}
  @Get
    list() {
    return this.vpcService.list();
  }
}
</code></pre>
<p>My controller Jest Unit Test:</p>
<pre class=""lang-js prettyprint-override""><code>class VpcServiceMockFactory {
  private list() {
    return jest.fn().mockResolvedValue([TEMPLATE_VPC]);
  }

  getMock() {
    const repoService: RepositoryService = new RepositoryService();
    const vpsServiceMock: VpcServiceMock = new VpcServiceMock(repoService);
    vpsServiceMock.create(TEMPLATE_VPC.name);

    // This works
    // return {
    //   list: this.list(),
    // }

    // This does not work
    return {
      list: vpsServiceMock.list(),
      get: vpsServiceMock.get(TEMPLATE_VPC.id),
      // create: vpsServiceMock.create('new-vpc'),
      // update: vpsServiceMock.update(TEMPLATE_VPC.id, 'updated-name'),
      // delete: vpsServiceMock.delete(TEMPLATE_VPC.id),
    }
  }
}
describe('VpcControllerTest', () =&gt; {
  let controller: VpcController;
  let spyService: VpcService;

  beforeEach(async () =&gt; {
    // Mock Services
    const MockVpcServiceProvider = {
      provide: VpcService,
      useFactory: () =&gt; new VpcServiceMockFactory().getMock()
    }

    // Class-unter-test instantiation
    const module: TestingModule = await Test.createTestingModule({
      controllers: [VpcController],
      providers: [VpcService, MockVpcServiceProvider],
    }).compile()

    // Get the instance handlers
    controller = module.get&lt;VpcController&gt;(VpcController);
    spyService = module.get&lt;VpcService&gt;(VpcService);
  });

  it('Get collection of VPCs', async () =&gt; {
    // Execute the method
    const result = await controller.list();

    // Assertion
    expect(spyService.list).toHaveBeenCalled();
    expect(result.length).toBe(1);
    expect(result[0].name).toBe('zopa');
  });
}
</code></pre>
<p>My VpcServiceMock class:</p>
<pre class=""lang-js prettyprint-override""><code>export class VpcServiceMock {
  constructor(private repository: RepositoryService) {}
  list() {
    return this.repository.list&lt;VpcModel&gt;(VPC);
  }
}
</code></pre>
<p>My RepositoryService class:</p>
<pre class=""lang-js prettyprint-override""><code>  async list&lt;T&gt;(type: VPC): Promise&lt;T[]&gt; {
    return &lt;T[]&gt;this.aSimpleJsonObject[type];
  }

</code></pre>
<p>However when I am running it, it is showing this error:</p>
<pre><code>  ● VpcControllerTest › Test-2: Get collection of VPCs                                                                                                             
                                                                                                                                                                   
    TypeError: this.vpcService.list is not a function

      38 |   @ApiForbiddenResponse({ description: 'Unauthorized Request' })
      39 |   list() {
    &gt; 40 |     return this.vpcService.list();
         |                            ^
      41 |   }
      42 |
      43 |   @Get(':id')

      at VpcController.list (src/vpc/vpc.controller.ts:40:28)
      at Object.&lt;anonymous&gt; (src/vpc/vpc.controller.spec.ts:87:37)

</code></pre>
<p>So the only way I can make it work:</p>
<p>If I provide a mock implementation in the Jest Unit test's <code>VpcServiceMockFactory</code> class (like I showed in the commented out code there as <code>// This works</code>).</p>
<p>Definitely I am missing something here, which I am not able to figure out.</p>
",https://stackoverflow.com/questions/75168621/nest-js-jest-unit-testing-providing-a-mock-implementation-not-used-from-control,"['jestjs', 'nest', 'ts-jest']",258,False,-1,1
Expression Expected Error encountered in JUnit5 Test,"<p>I am new in unit testing and I am stuck with this error. I wonder if anyone here got an insight as to how I can resolve this issue.</p>
<p>So this is a snippet of my unit test.</p>
<pre><code>@Test
void shouldFindByStatus() {
    when(repository.findByBookingStatus(anyString(),Sort.by(&quot;id&quot;).descending())).thenReturn(getBookingEntityForFilterByStatus());
    when(mapper.toDomain(any(List&lt;BookingEntity.class))).thenReturn(getBookingFilterResponseDTO());
    
    List&lt;BookingFilterResponseDTO&gt; underTest = adapter.findByBookingStatus(&quot;CANCELLED&quot;);

    assertNotNull(underTest);
}
</code></pre>
<p>The error I encountered is this part:</p>
<pre><code>(any(List&lt;BookingEntity.class)))
</code></pre>
<p>It says that &quot;List&quot; is an expected expression. Now the problem is if I remove the List, it will throw a different error since I declared it as List on my mapper class.</p>
<p>This is my mapper class.</p>
<pre><code>List&lt;BookingFilterResponseDTO&gt; toDomain(List&lt;BookingEntity&gt; bookingEntity);
</code></pre>
<p>If anyone here got an idea as to how I can resolve the said issue. I would highly and sincerely appreciate it. Thanks!</p>
",https://stackoverflow.com/questions/75488173/expression-expected-error-encountered-in-junit5-test,"['java', 'mongodb', 'spring-boot', 'junit5', 'java-17']",18,False,0,0
Attempting to use Jest React Testing Library and webpack have no Idea why I am getting all these errors,"<p>I've been trying to implement jest and react testing library to this application that I've inherited and for some reason I've getting all of these errors that I can't figure out. Granted I am trying to learn unit testing at the moment.</p>
<p>unit-summary-tag.test.js</p>
<pre><code>/**
 * @jest-environment jsdom
 */

import React from &quot;react&quot;;

import { render, screen } from &quot;@testing-library/react&quot;
import UnitSummaryTag  from '../src/apps/auto_dsr/UnitSummaryTag';



  beforeAll(() =&gt; {
    render(&lt;UnitSummaryTag /&gt;)
  })
  it('shoud have a random test', ()=&gt;{
    expect(1).toBe(1);
  })
 
</code></pre>
<p>webpack.config.js</p>
<pre><code>const path = require('path');

module.exports = {
    entry: './js/src/index.js', // Input file path
    output: {
        filename: 'index-bundle.js', // output bundle file name
        path: path.resolve(__dirname, './static/js'), // path to Django static directory
    },
    module: {
        rules: [
          {
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            loader: &quot;babel-loader&quot;,
            options: { presets: [&quot;@babel/preset-env&quot;, &quot;@babel/preset-react&quot;] }
          }
        ]
      }
};
</code></pre>
<p>package.json</p>
<pre><code>{
  &quot;name&quot;: &quot;griffin-ai&quot;,
  &quot;version&quot;: &quot;1.0.0&quot;,
  &quot;description&quot;: &quot;&quot;,
  &quot;main&quot;: &quot;index.js&quot;,
  &quot;scripts&quot;: {
    &quot;prod&quot;: &quot;webpack --mode production&quot;,
    &quot;dev&quot;: &quot;webpack --mode development --watch&quot;,
    &quot;test&quot;: &quot;jest --coverage&quot;,
    &quot;test:watch&quot;: &quot;jest --coverage --watch&quot;
  },
  &quot;keywords&quot;: [],
  &quot;author&quot;: &quot;&quot;,
  &quot;license&quot;: &quot;ISC&quot;,
  &quot;devDependencies&quot;: {
    &quot;@babel/core&quot;: &quot;^7.20.2&quot;,
    &quot;@babel/preset-env&quot;: &quot;^7.20.2&quot;,
    &quot;@babel/preset-react&quot;: &quot;^7.18.6&quot;,
    &quot;babel-jest&quot;: &quot;^29.3.1&quot;,
    &quot;babel-loader&quot;: &quot;^9.1.0&quot;,
    &quot;jest&quot;: &quot;^29.3.1&quot;,
    &quot;jest-environment-jsdom&quot;: &quot;^29.5.0&quot;,
    &quot;webpack&quot;: &quot;^5.75.0&quot;,
    &quot;webpack-cli&quot;: &quot;^4.10.0&quot;
  },
  &quot;dependencies&quot;: {
    &quot;@testing-library/jest-dom&quot;: &quot;^5.16.5&quot;,
    &quot;@testing-library/react&quot;: &quot;^14.0.0&quot;,
    &quot;@testing-library/user-event&quot;: &quot;^13.5.0&quot;,
    &quot;@types/jest&quot;: &quot;^27.5.2&quot;,
    &quot;@types/react&quot;: &quot;^18.0.28&quot;,
    &quot;@types/react-dom&quot;: &quot;^18.0.11&quot;,
    &quot;react&quot;: &quot;^18.2.0&quot;,
    &quot;react-dom&quot;: &quot;^18.2.0&quot;,
    &quot;web-vitals&quot;: &quot;^2.1.4&quot;
  },
  &quot;eslintConfig&quot;: {
    &quot;extends&quot;: [
      &quot;react-app&quot;,
      &quot;react-app/jest&quot;
    ]
  }
}

</code></pre>
<p>and this is the error i'm getting
console.error
The above error occurred in the  component:</p>
<pre><code>      at text (C:\Users\629812\Documents\Projects\Griggin_Project_v2\griffin-ai\griffin_ai\js\src\apps\auto_dsr\UnitSummaryTag.js:5:32)
  
  Consider adding an error boundary to your tree to customize error handling behavior.
  Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

  18 |   // });
  19 |   beforeAll(() =&gt; {
&gt; 20 |     render(&lt;UnitSummaryTag /&gt;)
     |           ^
  21 |   })
  22 |   it('shoud have a random test', ()=&gt;{
  23 |     expect(1).toBe(1);

  at logCapturedError (node_modules/react-dom/cjs/react-dom.development.js:18687:23)
  at update.callback (node_modules/react-dom/cjs/react-dom.development.js:18720:5)
  at callCallback (node_modules/react-dom/cjs/react-dom.development.js:13923:12)
  at commitUpdateQueue (node_modules/react-dom/cjs/react-dom.development.js:13944:9)
  at commitLayoutEffectOnFiber (node_modules/react-dom/cjs/react-dom.development.js:23391:13)
  at commitLayoutMountEffects_complete (node_modules/react-dom/cjs/react-dom.development.js:24688:9)     
  at commitLayoutEffects_begin (node_modules/react-dom/cjs/react-dom.development.js:24674:7)
  at commitLayoutEffects (node_modules/react-dom/cjs/react-dom.development.js:24612:3)
  at commitRootImpl (node_modules/react-dom/cjs/react-dom.development.js:26823:5)
  at commitRoot (node_modules/react-dom/cjs/react-dom.development.js:26682:5)
  at finishConcurrentRender (node_modules/react-dom/cjs/react-dom.development.js:25892:9)
  at performConcurrentWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:25809:7)
  at flushActQueue (node_modules/react/cjs/react.development.js:2667:24)
  at act (node_modules/react/cjs/react.development.js:2582:11)
  at node_modules/@testing-library/react/dist/act-compat.js:46:25
  at renderRoot (node_modules/@testing-library/react/dist/pure.js:161:26)
  at render (node_modules/@testing-library/react/dist/pure.js:247:10)
  at Object.&lt;anonymous&gt; (js/tests/unit-summary-tag.test.js:20:11)
</code></pre>
<p>● shoud have a random test</p>
<pre><code>TypeError: Cannot read properties of undefined (reading 'slice')

  27 |
  28 | export function bgTag(status, text=true) {
&gt; 29 |     switch(status.slice(0,3)) {
     |                   ^
  30 |         case 'FMC':
  31 |             return text ? &quot; fmc-bg&quot; : &quot; fmc-count-bg&quot;;
  32 |         case 'NMC':

  at slice (js/src/utils.js:29:19)
  at UnitSummaryTag (js/src/apps/auto_dsr/UnitSummaryTag.js:5:25)
  at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:16305:18)
  at mountIndeterminateComponent (node_modules/react-dom/cjs/react-dom.development.js:20074:13)
  at beginWork (node_modules/react-dom/cjs/react-dom.development.js:21587:16)
  at beginWork$1 (node_modules/react-dom/cjs/react-dom.development.js:27426:14)
  at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:26560:12)
  at workLoopSync (node_modules/react-dom/cjs/react-dom.development.js:26466:5)
  at renderRootSync (node_modules/react-dom/cjs/react-dom.development.js:26434:7)
  at recoverFromConcurrentError (node_modules/react-dom/cjs/react-dom.development.js:25850:20)
  at performConcurrentWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:25750:22)
  at flushActQueue (node_modules/react/cjs/react.development.js:2667:24)
  at act (node_modules/react/cjs/react.development.js:2582:11)
  at node_modules/@testing-library/react/dist/act-compat.js:46:25
  at renderRoot (node_modules/@testing-library/react/dist/pure.js:161:26)
  at render (node_modules/@testing-library/react/dist/pure.js:247:10)
  at Object.&lt;anonymous&gt; (js/tests/unit-summary-tag.test.js:20:11)
</code></pre>
<p>I tried adding installing jest-dom packages as well as adding all of the dependencies that I believe it would need. I suspect it's a webpack issue but the thing is I'm not sure exactly what it could be.</p>
",https://stackoverflow.com/questions/75739580/attempting-to-use-jest-react-testing-library-and-webpack-have-no-idea-why-i-am-g,"['reactjs', 'webpack', 'jestjs', 'react-testing-library', 'babel-jest']",116,False,0,0
Would introducing outlier removal potentially stop my transformer model from learning?,"<p>I have recently added in Z-score outlier removal to the preprocessing for my transformer model and now the model is learning basically at all. It was working before Introduced this Would have adding this meant caused that or is it more likely that I have introduced that i have not yet been able to find?</p>
<p><a href=""https://i.stack.imgur.com/UgaHo.png"" rel=""nofollow noreferrer"">Before outlier removal</a></p>
<p><a href=""https://i.stack.imgur.com/QZRxi.png"" rel=""nofollow noreferrer"">After outlier removal</a></p>
<p>I have tried to find a bug by unit testing and looking at the observed outputs of different parts of the pre processing but it all looks okay. what am I missing?</p>
<p>apologies in advance if this is a stupid question I am very new to Neural networks</p>
",https://stackoverflow.com/questions/76007602/would-introducing-outlier-removal-potentially-stop-my-transformer-model-from-lea,"['python', 'tensorflow', 'machine-learning', 'keras', 'artificial-intelligence']",9,False,0,0
Is it possible to use the nrf native_posix board on windows?,"<p>I have a project built for an nrf board. The project uses zephyr os. Right now we're developing on windows. We'd like to add unit testing with unity/cmock. I've been looking in to the nrf documents <a href=""https://developer.nordicsemi.com/nRF_Connect_SDK/doc/latest/nrf/app_dev/testing_unity_cmock/index.html"" rel=""nofollow noreferrer"">https://developer.nordicsemi.com/nRF_Connect_SDK/doc/latest/nrf/app_dev/testing_unity_cmock/index.html</a>  and finding some examples (like this <a href=""https://github.com/antmicro/zephyr-cmock-unity-module"" rel=""nofollow noreferrer"">https://github.com/antmicro/zephyr-cmock-unity-module</a>) but they all use the native_posix board. As far as I understand that wouldn't be possible to use on Windows, is that correct? Do I have any other options for unity + nrf + zphyr + windows, or do I need to make a linux vm to run unit tests from?</p>
",https://stackoverflow.com/questions/76230813/is-it-possible-to-use-the-nrf-native-posix-board-on-windows,"['windows', 'zephyr-rtos', 'unity-test-framework']",24,False,0,0
Hibernate creating Entity Primary Key Id Negative,"<p>After upgrading to Spring Boot 2.7.7, which is dependent on Hibernate 5.6.14, Entities that are configured with Sequence Generator, new records started with negative ids?</p>
<p>For tables with records already in the database, sequence continues to work fine. The tables are using a postgres sequence to increase by 50, but first id is generating as -47, then -46 and so on. This must be a divide by zero issue, because it doesn't happen on records id with a pre-existing value greater than zero.</p>
<p>Very interesting issue to find, I only noticed because fresh db with unit testing.. Seems Hibernate had issue with this in the past but many years ago.</p>
",https://stackoverflow.com/questions/75113595/hibernate-creating-entity-primary-key-id-negative,"['spring-boot', 'hibernate']",29,False,0,1
Why do I need to restart karma?,"<p>I'm running some tutorials on Angular and unit testing. I have karma running (<code>npm test</code>), so while coding the tests are conveniently rerun and displayed automatically. This is all according to plan. But on some changes I get this error:
<a href=""https://i.stack.imgur.com/4qiVK.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/4qiVK.png"" alt=""enter image description here"" /></a></p>
<p>If I then revert the changes I just made, the error still persists even though the tests seems to be automatically rerun. So after this error occurred there seems to be no codechanges I can make to get rid of this error.</p>
<p>The only thing I found that works is to restart karma all together (<kbd>CTRL+C</kbd> and <code>npm test</code>).</p>
<p>So: <strong>Why does karma get stuck in the error and needs a restart?</strong></p>
",https://stackoverflow.com/questions/75094042/why-do-i-need-to-restart-karma,"['angular', 'karma-runner']",27,False,0,0
mock Axios.Create() in unit testing,"<p>i want to create an unit testing for my service. In my service, i used axios.create function to help me configure some config. I am a little confused with the unit test.
I've done creating unit tests and mocks for axios but without using axios.create. Maybe you can help me to solve my problem. I have tried several solutions but have not been able to solve my problem</p>
<p>this is my api.js</p>
<pre><code>import axios from &quot;axios&quot;;

const BASE_URL = process.env.REACT_APP_BASE_URL;


const api = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
  headers: {
    Accept: &quot;application/json&quot;
  },
});

const apiService = {
  post: async (url: string, json = {}, reqConfig = {}) =&gt; {
    const token = localStorage.getItem(&quot;accessToken&quot;);
    if (token) {
      api.defaults.headers.Authorization = `Bearer ${token}`;
    }
    api.defaults.headers[&quot;Content-Type&quot;] = &quot;application/json&quot;;
    const data = json;
    try {
      const response = await api.post(url, data, {
        baseURL: BASE_URL,
        ...reqConfig
      });
      return response;
    } catch (err) {
      return err
    }
  }
}

export default apiService
</code></pre>
<p>and this is my unit test:</p>
<pre><code>import apiService from &quot;../api&quot;;
import axios from &quot;axios&quot;;

jest.mock(&quot;axios&quot;);
const mockedAxios = axios as jest.Mocked&lt;typeof axios&gt;;

describe(&quot;apiService&quot;, () =&gt; {
    beforeAll(() =&gt; {
        mockedAxios.create.mockReturnThis();
    });
    it(&quot;should call apiService.post&quot;, async () =&gt; {
        mockedAxios.post.mockImplementationOnce(() =&gt;
            Promise.resolve({
                data: {
                    task_id: &quot;123&quot;
                },
                status: 200
            })
        );
        const response: any = await apiService.post(&quot;&quot;, {
            requester: &quot;example@gmail.com&quot;,
            subject: &quot;test&quot;,
            description: &quot;test&quot;,
            attach: false
        });
        expect(response.data.task_id).toEqual(&quot;123&quot;);
        expect(response.status).toEqual(200);
    });
});
</code></pre>
<p>this is the error:</p>
<p><a href=""https://i.stack.imgur.com/6cijj.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/6cijj.png"" alt=""enter image description here"" /></a></p>
<p>I have tried to comment the api.defaults code, but i got this one:</p>
<p><a href=""https://i.stack.imgur.com/jkGyq.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/jkGyq.png"" alt=""enter image description here"" /></a></p>
<p>can someone help me to solve my problem? Thankyou.</p>
",https://stackoverflow.com/questions/76183702/mock-axios-create-in-unit-testing,"['javascript', 'reactjs', 'unit-testing', 'axios']",68,False,0,1
Flutter Unit Testing with Mockito multiple stubs,"<p>I'm quite new to unit testing and I want to test a method of a service that calls conditionally a second method. The problem I'm facing now is that I'm getting a missing MissingStubError even I have created the missing stub.</p>
<p>mockito: 5.3.2</p>
<p>Error Message:
MissingStubError: 'createCashbookItem'
No stub was found which matches the arguments of this method call:
createCashbookItem(Instance of 'CashbookItem')</p>
<p>Test:</p>
<pre><code>@GenerateMocks([CashbookRepository, ReceiptRepository, CashbookItemRepository])
void main() {
  late BookingService bookingService;
  late MockCashbookRepository mockCashbookRepository;
  late MockCashbookItemRepository mockCashbookItemRepository;
  late MockReceiptRepository mockReceiptRepository;

  setUp(() {
    mockCashbookRepository = MockCashbookRepository();
    mockCashbookItemRepository = MockCashbookItemRepository();
    mockReceiptRepository = MockReceiptRepository();
    bookingService = BookingServiceImpl(
      receiptRepository: mockReceiptRepository,
      cashbookItemRepository: mockCashbookItemRepository,
      cashbookRepository: mockCashbookRepository,
    );
  });

  group(&quot;bookings&quot;, () {
    var t_OldReceipt = Receipt.empty();
    var t_NewReceipt = Receipt.empty();

    test(&quot;create booking&quot;, () async {
      t_OldReceipt = t_OldReceipt.copyWith(
          amount: 10,
          totalAmount: 10,
          taking: true,
          category: &quot;test&quot;,
          taxRate: 0,
          paymentType: kPaymentTypeBar,
          documentNumber: &quot;1&quot;,
          taxAmount: 0,
          receiptDate: DateTime.now(),
          year: &quot;2023&quot;,
          yearMonth: &quot;20232&quot;,
          yearMonthDay: &quot;2023210&quot;,
          contact: Contact.empty());
      // arrange

      var cashbookItem = CashbookItem.fromReceipt(t_OldReceipt);

      when(mockReceiptRepository.createReceipt(t_OldReceipt)).thenAnswer((realInvocation) async =&gt; const Right(unit));
    
when(mockCashbookItemRepository.createCashbookItem(cashbookItem)).thenAnswer((realInvocation) async =&gt; const Right(unit));
      // act
      final result = await bookingService.createBooking(t_OldReceipt);
      // assert
      expect(result, const Right(unit));
    });
  });
}
</code></pre>
<p>Method that I want to test:</p>
<pre><code>  Future&lt;Either&lt;ReceiptFailure, Unit&gt;&gt; createBooking(Receipt receipt) async {
    Either&lt;ReceiptFailure, Unit&gt;? receiptFailureOrSuccess;
    Either&lt;cashbook_failures.CashbookFailure, Unit&gt;? cashbookFailureOrSuccess;

    receiptFailureOrSuccess = await receiptRepository.createReceipt(receipt);

    if (receiptFailureOrSuccess.isLeft()) {
      return receiptFailureOrSuccess;
    }

    if (receipt.paymentType == kPaymentTypeBar) {
      cashbookFailureOrSuccess = await cashbookItemRepository.createCashbookItem(CashbookItem.fromReceipt(receipt));
      if(cashbookFailureOrSuccess.isLeft()){
        receiptRepository.deleteReceipt(receipt.id.value);
        return left(CreateCashbookItemFromReceiptFailure());
      } else {
        return right(unit);
      }
    }
    return receiptFailureOrSuccess;
  }
</code></pre>
<p>I have added a stub for the error and my assumption was that it is possible to have two stubs in one test. I want to test if the method createCashbookItem inside createBooking is called.</p>
",https://stackoverflow.com/questions/75419547/flutter-unit-testing-with-mockito-multiple-stubs,"['flutter', 'dart', 'unit-testing', 'mockito']",139,False,0,0
Vue router doesn&#39;t load with create-vue@3,"<p>i was trying out the vue router but i'm not getting the expected result.</p>
<p>I'm following the <a href=""https://router.vuejs.org/guide/"" rel=""nofollow noreferrer"">https://router.vuejs.org/guide/</a> tutorial, if i use the CDN and put it in a unique HTML file it works, but if i try in this way it doesn´t:</p>
<h2>Steps to reproduce:</h2>
<ul>
<li>run <code>npm create vue@3</code></li>
<li>Configuration:
<ul>
<li>Project name: … vue-project</li>
<li>Add TypeScript? Yes</li>
<li>Add JSX Support? Yes</li>
<li>Add Vue Router for Single Page Application development? Yes</li>
<li>Add Pinia for state management? … No</li>
<li>Add Vitest for Unit Testing? … No</li>
<li>Add an End-to-End Testing Solution? › No</li>
<li>Add ESLint for code quality? … No</li>
</ul>
</li>
<li>install all dependencies</li>
<li>Change <code>src/main.ts</code> to</li>
</ul>
<pre class=""lang-js prettyprint-override""><code>import * as Vue from 'vue'
import * as VueRouter from 'vue-router'

// 1. Define route components.
// These can be imported from other files
const Home = { template: '&lt;div&gt;Home&lt;/div&gt;' }
const About = { template: '&lt;div&gt;About&lt;/div&gt;' }

// 2. Define some routes
// Each route should map to a component.
// We'll talk about nested routes later.
const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
//   { path: '/smm', component: About },
]

// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = VueRouter.createRouter({
  // 4. Provide the history implementation to use. We are using the hash history for simplicity here.
  history: VueRouter.createWebHashHistory(),
  routes, // short for `routes: routes`
})

// 5. Create and mount the root instance.
const app = Vue.createApp({})
// Make sure to _use_ the router instance to make the
// whole app router-aware.
app.use(router)

app.mount('#app')
</code></pre>
<ul>
<li>Change <code>index.html</code> to</li>
</ul>
<pre class=""lang-html prettyprint-override""><code>&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;Vite App&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;

&lt;div id=&quot;app&quot;&gt;

    &lt;h1&gt;Hello App!&lt;/h1&gt;
    &lt;p&gt;
      &lt;!-- use the router-link component for navigation. --&gt;
      &lt;!-- specify the link by passing the `to` prop. --&gt;
      &lt;!-- `&lt;router-link&gt;` will render an `&lt;a&gt;` tag with the correct `href` attribute --&gt;
      &lt;router-link to=&quot;/&quot;&gt;Go to Home&lt;/router-link&gt;
      &lt;router-link to=&quot;/about&quot;&gt;Go to About&lt;/router-link&gt;
    &lt;/p&gt;
    &lt;!-- route outlet --&gt;
    &lt;!-- component matched by the route will render here --&gt;
    &lt;router-view&gt;&lt;/router-view&gt;
&lt;/div&gt;

    &lt;script type=&quot;module&quot; src=&quot;/src/main.ts&quot;&gt;&lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;

- run `yarn start`
</code></pre>
<p>Vue and vue-router versions:</p>
<pre class=""lang-json prettyprint-override""><code>  &quot;dependencies&quot;: {
    &quot;vue&quot;: &quot;^3.3.2&quot;,
    &quot;vue-router&quot;: &quot;^4.2.0&quot;
  },
</code></pre>
",https://stackoverflow.com/questions/76241963/vue-router-doesnt-load-with-create-vue3,"['typescript', 'vue.js', 'vue-router4']",43,True,0,1
Do I need to unit test my repository layer methods?,"<p>I have a repository layer with several &quot;repositories&quot;, that I use to help the application interact with the database. These serve as a database abstraction.</p>
<p>The database itself is a Postgres database and it is interacted with via Sequelize.</p>
<p>A lot of this repository code looks similar to the following example:</p>
<pre><code>createBook: async ({ id, title }: CreateBookInput): Promise&lt;BookEntity&gt; =&gt; {
    const createdBook = await BookEntity.create({
        id,
        title
    }

    return createdBook.get();
}
</code></pre>
<p>BookEntity looks like the following:</p>
<pre><code>export class BookEntity extends Model {
  id: number
  title: string
}
</code></pre>
<p>where Model is a Sequelize provided class.</p>
<p>So all of the functionality I am using is essentially provided by Sequelize, is it still worth me unit testing the <code>createBook</code> method? In that case, what is the best way to do it? Should I create a test database and test this method using that?</p>
",https://stackoverflow.com/questions/76074965/do-i-need-to-unit-test-my-repository-layer-methods,"['node.js', 'typescript', 'sequelize.js']",18,False,0,0
Module import for unit test is not linking,"<p>I have a Python AWS Lambda function located in a directory structure like this:</p>
<pre><code>|-lambda
      |
      |-lambda_function.py
               |
               |-tests
                     |
                     |-test.py
                     |-mockdata.json
</code></pre>
<p>I'm trying to perform unit testing using the unittest module, but I'm having trouble importing the lambda_handler function from the lambda_function.py file inside the test.py file.</p>
<p>I've tried using the following import statement in test.py:</p>
<pre><code>from lambda_function import lambda_handler 
</code></pre>
<p>However, since test.py is in a subdirectory, I'm getting undefined results and the test is failing.</p>
<p>How can I properly import the lambda_handler function from lambda_function.py when running tests from a subdirectory? Any help would be appreciated. Thanks!</p>
<p>I have tried add parent directory of the test file which is lambda_function.py like below:</p>
<pre><code>sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), &quot;..&quot;)))
</code></pre>
<p>but it didn't solve the problem.</p>
",https://stackoverflow.com/questions/76038896/module-import-for-unit-test-is-not-linking,"['python', 'aws-lambda', 'python-unittest', 'python-unittest.mock']",32,False,0,0
Dependency Injection In DoFns for Apache Beam Golang,"<p>I want to be able to unit test my apache beam dofns by mocking functions a dofn invokes.</p>
<p>Say I am defining a structural dofn and would like to dynamically define a sub-function invoked in the body of the dofn.</p>
<p>Using a separate receiver function on the struct causes serialization issues (and may constitute a closure? which is <a href=""https://beam.apache.org/documentation/programming-guide/#user-code-serializability"" rel=""nofollow noreferrer"">not allowed</a>)</p>
<h3>DoFn definition</h3>
<pre><code>
func init() {
  register.DoFn3x0[string, func(string), func(string)](&amp;structuralDoFnExample{})
}

type structuralDoFnExample struct {
  OtherReceiverFunction func(...) (...)
}

func (fn *structuralDoFnExample) ProcessElement(exampleInput string, emit, errs func(string)) {
  ...
  fn.OtherReceiverFunction(...)
  ...
}
</code></pre>
<h4>DoFn Invocation</h4>
<pre><code>emitted, errors := beam.ParDo2(s.Scope(&quot;something&quot;), &amp;structuralDoFnExample{
    OtherReceiverFunction: ReceiverFunctionImplementation,
  }, inputPCol)
</code></pre>
<h3>Error</h3>
<p><code>unable to convert unsupported type func(...) (...) to schema</code></p>
<p>Is there a way around this limitation? Is there some other way to define a dofn where I can use dependency injection? My motivation is to enable unit testing:</p>
<ol>
<li>Directly on the dofn itself that doesn't invoke real services (i.e. mocking ReceiverFunctionImplementation)</li>
<li>Run pipeline without invoking real services (i.e. mocking ReceiverFunctionImplementation)</li>
</ol>
",https://stackoverflow.com/questions/75871298/dependency-injection-in-dofns-for-apache-beam-golang,"['go', 'apache-beam']",58,False,3,0
&quot;Timeout on blocking read&quot; when using new Spring 6 HTTP Interface,"<p>We recently started testing <a href=""https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#rest-http-interface"" rel=""nofollow noreferrer"">the new HTTP Interface that came with Spring 6.</a></p>
<p>We defined a client like this:</p>
<pre><code>    HttpClient client = (HttpClient)((HttpClient)HttpClient.create().option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)).doOnConnected((conn) -&gt; {
        conn.addHandlerLast(new ReadTimeoutHandler(10000L, TimeUnit.MILLISECONDS));
    });
    WebClient webClient = WebClient.builder().clientConnector(new ReactorClientHttpConnector(client)).baseUrl(locationUrl.toExternalForm()).build();
    HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(WebClientAdapter.forClient(webClient)).build();
</code></pre>
<p>An interface can look something like this:</p>
<pre><code>@GetExchange(&quot;/availability&quot;)
    AvailabilityResponse getAvailability(@RequestParam(&quot;products&quot;) List&lt;String&gt; itemIds);
</code></pre>
<p>When using the client, we are occasionally getting exceptions like below. We initially thought that this was related to the connect timeout that we defined as 5 seconds, but this seems to be related to the reactor blockingGet rather than the actual HTTP call.</p>
<p>When searching for similar issues, everything I found seem to be related to unit testing of WebClient, with solutions like setting <code>@AutoConfigureWebTestClient(timeout = &quot;30000&quot;)</code>, so this does not help us.
How can we increase the blocking get timeout to match our ReadTimeoutHandler of 10 seconds?</p>
<pre><code>java.lang.IllegalStateException: Timeout on blocking read for 5000000000 NANOSECONDS
    at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:123)
    at reactor.core.publisher.Mono.block(Mono.java:1734)
    at org.springframework.web.service.invoker.HttpServiceMethod$ResponseFunction.execute(HttpServiceMethod.java:296)
    at org.springframework.web.service.invoker.HttpServiceMethod.invoke(HttpServiceMethod.java:105)
    at org.springframework.web.service.invoker.HttpServiceProxyFactory$HttpServiceMethodInterceptor.invoke(HttpServiceProxyFactory.java:271)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:218)
    at jdk.proxy3/jdk.proxy3.$Proxy135.searchPharmacies(Unknown Source)
    at &lt;redacted&gt;
    at jdk.internal.reflect.GeneratedMethodAccessor128.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:207)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:152)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1080)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:973)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1011)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:903)
    at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:705)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885)
    at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.springframework.web.filter.ServerHttpObservationFilter.doFilterInternal(ServerHttpObservationFilter.java:109)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:741)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)
</code></pre>
",https://stackoverflow.com/questions/75313793/timeout-on-blocking-read-when-using-new-spring-6-http-interface,"['java', 'spring', 'spring-boot', 'spring-webclient']",446,True,2,1
Cannot find name &#39;global&#39;,"<h2>Angular 15 Project using Jest Testing Framework Error</h2>
<p>I have an Angular 15 project using jest (v28.1.3) for unit testing.</p>
<p>I'm trying to test a method that utilizes a <code>setTimeout()</code> function. According to the <a href=""https://jestjs.io/docs/28.x/timer-mocks"" rel=""nofollow noreferrer"">documentation</a> it's as simple as</p>
<pre class=""lang-js prettyprint-override""><code>jest.useFakeTimers();
jest.spyOn(global, 'setTimeout');
...
//call component method
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(setTimeout).toHaveBeenLastCalledWith(expect.any(function), 100)
</code></pre>
<p>When I try running this test using the code above I get the following in the console:</p>
<blockquote>
<p>FAIL  src/app/data-flow/data-flow.component.spec.ts   ● Test suite
failed to run</p>
<p>src/app/data-flow/data-flow.component.spec.ts:112:18 - error TS2304:
Cannot find name 'global'.</p>
<p>112       jest.spyOn(global, 'setTimeout');</p>
<p>Test Suites: 1 failed, 1 total Tests:       0 total Snapshots:   0
total Time:        9.634 s Ran all test suites matching
/data-flow.component/i.</p>
</blockquote>
<p>Any thoughts on what could be causing this?</p>
",https://stackoverflow.com/questions/75182342/cannot-find-name-global,"['angular', 'jestjs']",122,False,1,1
"Compose android tests fail when minify enabled, class / methods not found","<p>My Compose unit tests fail if I have <code>minify</code> enabled on my app.</p>
<pre><code>java.lang.NoSuchMethodError: No interface method complete()Z in class Lkotlinx/coroutines/CompletableJob; or its super classes (declaration of 'kotlinx.coroutines.CompletableJob' appears in /data/app/com.clover.engine-7ap2fJvfCgX89H0L0ytLZg==/base.apk!classes3.dex)
at androidx.compose.ui.test.junit4.IdlingResourceRegistry.&lt;init&gt;(IdlingResourceRegistry.jvm.kt:46)
at androidx.compose.ui.test.junit4.IdlingResourceRegistry.&lt;init&gt;(IdlingResourceRegistry.jvm.kt:37)
at androidx.compose.ui.test.AndroidComposeUiTestEnvironment.&lt;init&gt;(ComposeUiTest.android.kt:220)
...
at androidx.compose.ui.test.junit4.AndroidComposeTestRule_androidKt.createComposeRule(AndroidComposeTestRule.android.kt:212)
at com.mytest.MyTest.&lt;init&gt;(...)
</code></pre>
<p>I've tried adding proguard rules for the missing symbols, which gets past the immediate problem, but it seems to be a never ending list which makes me think that isn't the right direction.</p>
<p>Minify is enabled like this:</p>
<pre><code>  buildTypes.all {
    minifyEnabled true
    // ...
  }
</code></pre>
<p>I have other <code>androidTest</code> tests that run fine, and the Compose-based activity in the app works fine when minify is enabled.</p>
<p>My Compose-related dependencies are like this:</p>
<pre><code>  def composeBom = platform('androidx.compose:compose-bom:2023.1.00')
  implementation composeBom
  androidTestImplementation composeBom
  implementation 'androidx.compose.material3:material3'
  implementation 'androidx.compose.ui:ui-tooling-preview'
  debugImplementation 'androidx.compose.ui:ui-tooling'
  implementation 'androidx.compose.runtime:runtime-livedata'

  implementation 'androidx.activity:activity-compose:1.6.1'
  implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.5.1'

  androidTestImplementation 'androidx.compose.ui:ui-test-junit4'
</code></pre>
<p>EDIT: I was looking into the &quot;Now in Android&quot; Compose best-practice app. Not 100% clear but it seems like it also does not enabled minify for unit testing:
<a href=""https://github.com/android/nowinandroid/blob/0d23e64848adea66ec878293a7c1bd18d128689a/app/build.gradle.kts#L46"" rel=""nofollow noreferrer"">https://github.com/android/nowinandroid/blob/0d23e64848adea66ec878293a7c1bd18d128689a/app/build.gradle.kts#L46</a></p>
",https://stackoverflow.com/questions/75392172/compose-android-tests-fail-when-minify-enabled-class-methods-not-found,"['android-jetpack-compose', 'android-testing', 'kotlin-android']",249,False,0,0
How to mock a method with IEquatable&lt;T&gt; type constrain?,"<p>In my C# project I am using <em>xUnit</em> and <em>Moq4</em> for unit testing.
The interface that I'm trying to mock looks like this:</p>
<pre><code>public interface IEngine
{
    void Push&lt;T&gt;() where T : IEquatable&lt;T&gt;;
}

</code></pre>
<p>I would like to create and setup mock of this interface like this:</p>
<pre><code>[Fact]
public void My_test()
{
   var value = 0;

   var mock = new Mock&lt;IEngine&gt;();

   mock.Setup(m =&gt; m.Push&lt;???&gt;()).Callback(() =&gt; value++);

   mock.Object.Push&lt;TypeOne&gt;();
   mock.Object.Push&lt;TypeTwo&gt;();

   Assert.Equal(2, value);
}
</code></pre>
<p>where <code>TypeOne</code> and <code>TypeTwo</code> are:</p>
<pre><code>public class TypeOne : IEquatable&lt;TypeOne&gt;
{
    public bool Equals(TypeOne? other) =&gt; true;
}

public class TypeTwo : IEquatable&lt;TypeTwo&gt;
{
    public bool Equals(TypeTwo? other) =&gt; true;
}
</code></pre>
<p>What should I write instead of '???' to make my test compile and work? Is it event possible?</p>
<p>I've tried something like</p>
<pre><code>mock.Setup(m =&gt; m.Push&lt;IEquatable&lt;It.IsAnyType&gt;&gt;()).Callback(() =&gt; value++);
</code></pre>
<p>But this doesn't compile with error:</p>
<blockquote>
<p>The type 'System.Equatable&lt;Moq.It.IsAnyType&gt;' cannot be used as type
parameter 'T' in the generic type or method 'IEngine.Push&lt;T&gt;()'. There
is no implicit reference conversion from
'System.Equatable&lt;Moq.It.IsAnyType&gt;' to
'System.Equatable&lt;System.Equatable&lt;Moq.It.IsAnyType&gt;&gt;'.</p>
</blockquote>
<p>I've read about <code>ITypeMatcher</code> interface and <code>TypeMatcherAttribute</code> from Moq4. But I can't figure out how to apply it in my case.</p>
<p>Please help.</p>
",https://stackoverflow.com/questions/75431105/how-to-mock-a-method-with-iequatablet-type-constrain,"['c#', 'unit-testing', 'moq', 'xunit']",76,False,0,0
Mock service return undefined with nested services,"<p>I'm currently working on an Angular project and I am creating unit testing for a component using Karma + Jasmine, so I have HTML that has a <code>ngIf</code> calling the API Service as:</p>
<p><strong>HTML</strong></p>
<pre><code>&lt;div class=&quot;row&quot; *ngIf=&quot;apiService.utilsService.userBelongsTo('operations')&quot;&gt;&lt;/div&quot;&gt;
</code></pre>
<p>The service in the <code>*ngIf</code> is the service that I want to mock on the <code>spec.ts</code> below</p>
<p><strong>TS</strong></p>
<pre><code>export class CashFlowSalariesComponent implements OnInit, OnChanges {
constructor(
public apiService: ApiService,
) {}
</code></pre>
<p><strong>SPECT.TS</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>describe('CashFlowSalariesComponent', () =&gt; {
      let fixture: ComponentFixture &lt; CashFlowSalariesComponent &gt; ;
      let mockApiService;
      let data;

      beforeEach(async(() =&gt; {
        data = [{
          id: 1006,
          role: ""Developer"",
          ...
        }]

        mockApiService = jasmine.createSpyObj(['userBelongsTo'])

        TestBed.configureTestingModule({
          schemas: [CUSTOM_ELEMENTS_SCHEMA],
          imports: [
            RouterTestingModule,
            FormsModule,
            ReactiveFormsModule,
            BrowserModule,
            HttpClientTestingModule,
            ToastrModule.forRoot({
              positionClass: 'toast-bottom-right'
            })
          ],
          declarations: [
            CashFlowSalariesComponent,
          ],
          providers: [{
              provide: ApiService,
              useValue: mockApiService
            }, UserService, ProfileService, VettingStatusService, ApplicationRoleService,
            SeniorityLevelService, PlacementStatusService, EducationLevelService, UtilsService, ShirtSizeService,
            CountryService, CityService, PostalCodeService, StateService, ClientSectorService, JobService, ProfileActivityService, ProfileSalaryActivityService, ClientService, RequestTimeOffService, TimeOffTypeService, PulsecheckDetailService, PulsecheckMasterService,
            PulsecheckQuestionService, ExpenseService, DepartmentService, ExchangeRateService, SkillCategoriesService, ProfileRoleService,
            ToastrService
          ]

        })

        fixture = TestBed.createComponent(CashFlowSalariesComponent);
      }));


      it('should set salaries data correctly', () =&gt; {
        mockApiService.userBelongsTo.and.returnValue(of('operations'))
        debugger;
        fixture.detectChanges();
      })</code></pre>
</div>
</div>
</p>
<p>As you see, I tried to create mock of api service as: <code>mockApiService = jasmine.createSpyObj(['userBelongsTo'])</code>, then use in the <code>it</code> as: <code>mockApiService.userBelongsTo.and.returnValue(of('operations'))</code>, but when I debug it throws as unknown as the following picture</p>
<p><a href=""https://i.stack.imgur.com/NQYsz.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/NQYsz.png"" alt=""introducir la descripción de la imagen aquí"" /></a></p>
<p>and the test return the following error:</p>
<blockquote>
<p>Cannot read properties of undefined (reading 'userBelongsTo')</p>
</blockquote>
<p>I do not know if this happen because userBelongs to it is inside another service inside apiService:</p>
<p><strong>ApiService</strong></p>
<pre><code>@Injectable()
export class ApiService {
 public utilsService: UtilsService;

constructor(private injector: Injector) {
this.utilsService = injector.get(UtilsService);
}
}
</code></pre>
<p><strong>Utils.Service:</strong></p>
<pre><code>userBelongsTo(groupName: string) {
    return this.groups.split(',').reduce((c, g) =&gt; c || g.toUpperCase() == groupName.toUpperCase(), false);
  }
</code></pre>
<p>How can I make this work? Regards</p>
",https://stackoverflow.com/questions/75179334/mock-service-return-undefined-with-nested-services,"['javascript', 'angular', 'typescript', 'jasmine', 'karma-jasmine']",54,False,0,1
Azure DevOps with Boomi (or) Jenkins with Boomi for CI/CD automation with various stages,"<p>Are there any methods by which we can integrate Dell Boomi with Azure DevOps or Jenkins to implement CI/CD automation with various stages including unit testing and SonarQube etc?<br />
Any help with tools details and approaches is highly appreciated.</p>
<p>Previously I have tried this integration process using the Bash scripts (Link for Scripts: <a href=""https://github.com/OfficialBoomi/boomicicd-cli.git"" rel=""nofollow noreferrer"">https://github.com/OfficialBoomi/boomicicd-cli.git</a> ) but it wasn't helpful as we are facing many blockers while executing the script and after fixing it also we were unable to connect to Boomi platform.<br />
I want to apply DevOps concepts to the Boomi platform, Where I need help to integrate the Azure DevOps platform with Boomi (or) Jenkins platform with Boomi.</p>
",https://stackoverflow.com/questions/75131553/azure-devops-with-boomi-or-jenkins-with-boomi-for-ci-cd-automation-with-variou,"['jenkins', 'azure-devops', 'integration', 'cicd', 'boomi']",187,False,0,0
Unit Testing Arduino ESP8266 in CI (Native) with libraries,"<p>I am using an Arduino <code>ESP8266</code> with <code>platformio</code>. I am adding Unit Testing with the <code>Unity</code> framework and I want to run the tests in Gitlab <code>CI</code>. In my project, I use other libraries, such as <code>ESP8266WiFi</code>.</p>
<p>I am using the <code>Native</code> platform to run tests and my <strong>platformio.ini</strong> file looks like this:</p>
<pre><code>[platformio]
default_envs = esp01

[env]
lib_deps = 
    dancol90/ESP8266Ping@^1.0

[env:esp01]
platform = espressif8266
framework = arduino
board = esp01
; Serial Monitor options
monitor_speed = 115200

[env:native]
; Testing without HW in CI, I am using this
platform = native
lib_deps = 
    ${env.lib_deps}
    fabiobatsilva/ArduinoFake@^0.3.1
; Coverage:
lib_compat_mode = off
build_src_filter = +&lt;*&gt; -&lt;*dirs*&gt; -&lt;to/&gt; -&lt;exclude/&gt;
build_flags =
  -lgcov
  --coverage
extra_scripts = ci/test_coverage.py
</code></pre>
<p>My <strong>test</strong> would be something like this:</p>
<pre><code>#include &lt;unity.h&gt;
#include &quot;data.h&quot;

void test_1(void) {
  uint8_t mode = get_value();
  TEST_ASSERT_EQUAL(mode, 0);
}

int main(int argc, char **argv) {
    UNITY_BEGIN();

    RUN_TEST(test_1);

    return UNITY_END();
}
</code></pre>
<p>My simplified <strong>code</strong> would be (data.cpp file):</p>
<pre><code>#include &lt;ESP8266WiFi.h&gt;

uint8_t mode = 0;
uint8_t get_value(){
  return mode;
}
</code></pre>
<p>The compilation is working fine with <code>pio run</code>.
I am running this command to run the tests:</p>
<pre><code>pio test -e native -vvv
</code></pre>
<p>The error is:</p>
<pre><code>test\test_main.cpp:2:25: fatal error: ESP8266WiFi.h: No such file or directory
</code></pre>
<p>Maybe <code>ArduinoFake</code> can't emulate this library? Or should I include the library somehow? Or can't I Unit Test the way I am trying to do it?</p>
<p>If I have this test without importing my code, the test passes:</p>
<pre><code>#include &lt;unity.h&gt;
// #include &quot;data.h&quot;

void test_1(void) {
  //uint8_t mode = get_value();
  TEST_ASSERT_EQUAL(0, 0);
}

int main(int argc, char **argv) {
    UNITY_BEGIN();

    RUN_TEST(test_1);

    return UNITY_END();
}
</code></pre>
",https://stackoverflow.com/questions/75790142/unit-testing-arduino-esp8266-in-ci-native-with-libraries,"['c++', 'continuous-integration', 'platformio', 'unity-test-framework']",87,True,0,1
How to make Repl.it hidden test cases,"<p>I'm part of an organization where we teach basic programming to highscholers. And we just switched the exercices grading platform because the old one went down. For the new one, we chose Repl.it because of its flexibility but there is a HUGE problem in it, all the test cases of input/output are public. Some students could simply use 'if' statements and bypass the whole question.</p>
<p>Any idea of how to solve this, without using unit testing? We accept new platform suggestions.</p>
<p>Its important to have hidden cases, so we can keep the autograding system. There are more than 150 students per class, so completely not viable to manually correct each exercise.</p>
",https://stackoverflow.com/questions/75935317/how-to-make-repl-it-hidden-test-cases,"['python', 'repl.it']",40,False,-1,1
How I Test my API call Method .NET 6 Moq X-Unit,"<p>I have this Method on my service layer, my project is builded on DDD Architecture i want to know how I Test my method that calls and api without call the original service returning a post</p>
<p>I Mocked the Interface of Service but when i debug, not enters into the Method on my Service layer, i want to  enter into the service method without do this make a real world call to the service that the method consumes</p>
<p>Service Layer Class Service.cs</p>
<pre><code>    public string UpdateCancellation(UpdateCancellationDTO ucDTO)
    {
        var e1 = _configuration.GetSection(&quot;CancellationEndpoint&quot;).Value;
        var response = _httpClient.PostAsJsonAsync
        (e1 + &quot;Update/&quot;, ucDTO).Result;            
        var value = response.Content.ReadAsStringAsync().Result;
        return response.StatusCode.ToString();
    }
</code></pre>
<p>Test Layer Class</p>
<pre><code>    private readonly Mock&lt;ICancellationService&gt; _service;
    private readonly IConfiguration _configuration;
    private readonly HttpClient _httpclient;

    public TestController()
    {
        _service = new Mock&lt;ICancellationService&gt;();
    }
    [Fact]
    public void UpdateCancellation()
    {

        UpdateCancellationDTO ucDTO = new UpdateCancellationDTO
        {
            RegistrationCode = 0,
            ApplicationDate = new DateOnly
            (DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day),
            ClientName = &quot;Test&quot;,
            ContactNumber = &quot;00&quot;,
            Document = &quot;00&quot;,
            DocumentType = &quot;cc&quot;,
            Email = &quot;@&quot;,
            GenesysNotification = &quot;S&quot;,
            ProductNumber = &quot;0&quot;,
            ProductType = &quot;0&quot;,
            SendMail = &quot;S&quot;
        };

        _service.Setup(x =&gt; x.UpdateCancellation(ucDTO));
        var controller = new CancellationController(_service.Object);
        var service = new CancellationService
        (_httpclient, _configuration);
        var result = controller.UpdateCancellation(ucDTO);

        result = &quot;registration_code: 1&quot;;
        Assert.Same(&quot;registration_code: 1&quot;, result);
    }
</code></pre>
<p>or what is the best way to test my method?</p>
<p>Post Data
For my personal the unit testing sucks</p>
<p>XUnit Test my HttpClient method
Learn how to do this weird invention of UnitSucksTesting</p>
",https://stackoverflow.com/questions/75226847/how-i-test-my-api-call-method-net-6-moq-x-unit,"['asp.net-web-api', '.net-6.0', 'xunit', 'xunit.net', 'ddd-service']",28,False,0,0
NGRX jest-marbles Testing Effect Involving forkJoin Operator,"<h2>Unit Testing an Effect that Incorporates a <code>forkJoin</code> Operator</h2>
<p>I have an Angular 15 project using NGRX. I'm writing unit tests against my store and associated modules.</p>
<p>My effect basically works like a polling service and calls a service inside a <code>forkJoin</code> operator. The code is below.</p>
<pre class=""lang-js prettyprint-override""><code>  getGroupFlow$ = createEffect(() =&gt;
    this.actions$.pipe(
      ofType(StatusPollingActions.pollFlow),
      tap(() =&gt; this.continuePolling = true),
      withLatestFrom(of(environment.statusPollingInterval)),
      switchMap(([action, pollingInterval]) =&gt;
        timer(0, pollingInterval).pipe(
          takeWhile(() =&gt; this.continuePolling, true),
          switchMap(() =&gt;
            forkJoin([
              this.nifiService.getProcessGroupFlow(this.inputGroupId),
              this.nifiService.getProcessGroupFlow(this.processingGroupId),
              this.nifiService.getProcessGroupFlow(this.outputGroupId),
              this.nifiService.getConnectionsForGroup(this.mainCanvasId),
            ]).pipe(
              map(([incoming, processing, outgoing, groupConnections]) =&gt;
                StatusPollingActions.pollFlowSuccess({
                  incomingGroupFlow: incoming,
                  processingGroupFlow: processing,
                  outputGroupFlow: outgoing,
                  groupConnections: groupConnections,
                })
              ),
              catchError((error) =&gt;
                of(StatusPollingActions.pollFlowFailure({ error }))
              )
            )
          )
        )
      )
    )
  );
</code></pre>
<p>Of note... the variables referenced in the effect are defined below:</p>
<ul>
<li><code>continuePolling</code>: boolean variable scoped to the class</li>
<li><code>statusPollingInterval</code>: number indicating how frequently to poll (passed in from environment)</li>
</ul>
<p>I'm a bit new to writing tests against NGRX and I'm using jest and jest-marbles for my test cases.
I need help building out the test case to model the expected flow and output.</p>
<p>Any help would be greatly appreciated!</p>
",https://stackoverflow.com/questions/75016169/ngrx-jest-marbles-testing-effect-involving-forkjoin-operator,"['unit-testing', 'ngrx', 'ngrx-effects']",20,False,0,0
"Is it possible to write unit tests with playwright/test, not using unit testing libs like jest/vitest?","<p>I've been trying to use playwright/test - playwright/experimental-ct-svelte libs.</p>
<p>If I've read the documentation; I can do unit testing as well without using jest. But I could not understand how I could mock my functions.</p>
<p>Also E2E test is just a part of our testing strategy; there has to be unit test coverage as well.</p>
<p>We expected we could cover all our test needings with playwright/test or experimental-ct-svelte; unit, component and e2e; but feel stuck at the moment.</p>
<p>What would you recommend us?</p>
<ul>
<li>We also need to support gherkin for BDD; so we think cucumber-js or jest-cucumber will be a good option for us to organise our step functions.</li>
</ul>
",https://stackoverflow.com/questions/75746596/is-it-possible-to-write-unit-tests-with-playwright-test-not-using-unit-testing,"['unit-testing', 'svelte', 'e2e-testing', 'playwright', 'sveltekit']",231,True,0,1
"How to take iOS screenshots from &quot;Unit Testing Bundle&quot; XCode projects, as opposed to &quot;UI Testing Bundle&quot; projects?","<p>In XCode (as of 14.3) there are two types of testing projects;
<a href=""https://i.stack.imgur.com/SGptO.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/SGptO.png"" alt=""enter image description here"" /></a></p>
<p>My understanding of them is;</p>
<p><strong>Unit Testing Bundle</strong> - great for White Box testing, can (optionally) access Host Application APIs.</p>
<p><strong>UI Testing Bundle</strong> - great for Black Box testing, cannot access Host Application APIs.</p>
<p>I would like to use the fantastic screenshot APIs of XCUIScreenshot as part of my Unit Testing bundles, but cannot seem to get it to work.</p>
<p>A few things I've tried:</p>
<ol>
<li><p>define a XCUIApplication as part of the XCTestCase init;</p>
<p>app = XCUIApplication()
let screenshot = app.windows.firstMatch.screenshot()</p>
</li>
</ol>
<p>This obviously works well in UI Testing Bundle tests, but when its not a UI Test, the XCUIApplication cannot be created no matter the scheme. This kind of makes sense, as in the UI tests, it expects to manage this thing completely.</p>
<ol start=""2"">
<li><p>use XCUIScreen to create it</p>
<p>let screenshot = XCUIScreen.main.screenshot()</p>
</li>
</ol>
<p>For a similar reason this fails; I've tried this on device and in simulator, there error is:</p>
<blockquote>
<p>Failed to get screenshot: Not authorized for performing UI testing
actions.</p>
</blockquote>
<p>My hunch is that the screenshot capability is really being triggered &quot;outside the device&quot;, and this is just not possible, but haven't found any conclusive text to say so.</p>
<p>Anyone with insight one direction or the other?</p>
<p>Footnote; my workaround is to use a UI Testing bundle, then bake in the white box code i need into my app, and trigger it via command line arguments...  but it all feels pretty hoop jumpy. I want to do this to generate App Store screenshots as well as test various parts of my UI, and testing via pure button clicks is also, not ideal :)</p>
",https://stackoverflow.com/questions/76367395/how-to-take-ios-screenshots-from-unit-testing-bundle-xcode-projects-as-oppose,"['ios', 'swift', 'xcode', 'unit-testing', 'xcode-ui-testing']",27,True,0,1
"How to simultaneously test all plugins, theme and db configuration of your wordpress website using phpunit?","<p>I've battled with this question for hours now, searching far and wide through the web finding several guides to setup testing for individual plugins which created new a installation of WordPress and created a new empty database as testing ground for said plugin.</p>
<p>However, what I wanted was to test all my plugins at the same time, as many have integrations with each other and have their own configurations already set in the database which would need to be re-inserted into the newly created test database.</p>
<p>So, I simply edited the file bin/install-wp-tests.sh as described below:</p>
<p>In the function <code>install_wp()</code> include the line at the end of the function: <code>cp -a /$USER/wordpress/wp-content/. $WP_CORE_DIR/wp-content/</code></p>
<p>In the function <code>create_db()</code>, change content of function to:</p>
<p><code>mysqldump $USER_wordpress &gt; dump.sql --user=&quot;$DB_USER&quot; --password=&quot;$DB_PASS&quot;$EXTRA</code></p>
<p><code>mysqladmin create $DB_NAME --user=&quot;$DB_USER&quot; --password=&quot;$DB_PASS&quot;$EXTRA</code></p>
<p><code>mysql $DB_NAME &lt; dump.sql --user=&quot;$DB_USER&quot; --password=&quot;$DB_PASS&quot;$EXTRA</code></p>
<p>(Note: In my case <code>$USER_wordpress</code> is the name of the wordpress databse, and <code>/$USER/wordpress/wp-content/</code> is the absolute path to wp-content.)</p>
<p>This way, the tests are made using your entire current installation of wordpress including all plugins you've installed or created, and the your current database data.</p>
<p>To load your plugins, you need to specify them on the function <code>_manually_load_plugin()</code> on the file tests/bootstrap.php, by including the plugin like so:
<code>require rtrim( sys_get_temp_dir(), '/\\' ) . '/wordpress/wp-content/plugins/' . 'exampleplugin/exampleplugin.php';</code></p>
<p>I've used the following guides:</p>
<p><a href=""https://poweredbycoffee.co.uk/unit-testing-with-wordpress/"" rel=""nofollow noreferrer"">https://poweredbycoffee.co.uk/unit-testing-with-wordpress/</a></p>
<p><a href=""https://maheshwaghmare.com/wordpress/blog/phpunit-tests/"" rel=""nofollow noreferrer"">https://maheshwaghmare.com/wordpress/blog/phpunit-tests/</a></p>
<p><a href=""https://wpmudev.com/blog/unit-testing-wordpress-plugins-phpunit/"" rel=""nofollow noreferrer"">https://wpmudev.com/blog/unit-testing-wordpress-plugins-phpunit/</a></p>
<p><a href=""https://sanjeebaryal.com.np/fixing-issues-while-setting-up-php-unit-tests-for-wordpress-plugins/"" rel=""nofollow noreferrer"">https://sanjeebaryal.com.np/fixing-issues-while-setting-up-php-unit-tests-for-wordpress-plugins/</a></p>
<p>But non of them answered the fundamental question of how to include all your plugins and database configurations for your tests, so you could test multiple plugins inside the same test and using all your plugin configurations already set inside you db.</p>
",https://stackoverflow.com/questions/75125078/how-to-simultaneously-test-all-plugins-theme-and-db-configuration-of-your-wordp,"['wordpress', 'phpunit']",36,False,0,0
Should I be testing files before or after Webpack bundles them?,"<p><strong>Background:</strong> I'm working with an older codebase and one repository uses Webpack to compile some handlers for AWS lambda functions. There's no existing tests for these specific lambda functions but they're not deployed to production and exist only to simplify some of the automated testing in the backend. Recently, while updating the version of Node we're using, the Webpack deployment broke and it wasn't caught until tests in other repositories that depend on these lambdas were failing. Our code itself was still fine, but a Webpack config option had changed and as a result the bundled code's entry point changed.</p>
<p>I want to include some automated testing to prevent this from happening again, but I'm not sure where in the build process those tests should sit. If the tests are run against the handler code before it's compiled by Webpack, then this most recent issue would not have been caught. However, if we're testing the compiled code then it will be harder to spot the cause for any failures. It also means the automated tests in the CI/CD pipeline will be dependent on the <code>build</code> stage (unless these tests are run as part of the <code>build</code> stage itself, but I think this is bad practice).</p>
<p><strong>What's the standard approach for testing Webpack-created files? Should I avoid running unit tests against the bundled code and go for an integration test or two for sanity-checking purposes coupled with more thorough unit testing, or is unit testing Webpack-created files acceptable?</strong></p>
<p>A larger scale refactoring is probably not going to be a viable option, but if I'm missing a simpler refactor that would help then that would also be helpful advice.</p>
",https://stackoverflow.com/questions/76039400/should-i-be-testing-files-before-or-after-webpack-bundles-them,"['javascript', 'node.js', 'webpack', 'automated-tests', 'gitlab-ci']",19,False,0,0
Advanced module unit test setup in Julia,"<p>I have custom Julia package, which has hopefully quite standard structure. I have single package, <code>src</code> directory with sources and then <code>test</code> directory with all the tests.
In my package I have 4 modules (1 &quot;main&quot; and entrypoint module) and then 3 submodules.</p>
<p>I am slowly adding tests to <code>tests</code> directory. Tests are importing modules with <code>using</code> keyword.
Now problem is, very often I am testing some &quot;private&quot; or unnecessary method to be visible to outside and I have to export those functions even though I would not export them otherwise.</p>
<p>How to solve this? I was thinking that each module could have &quot;Private&quot; submodule containing all these &quot;private&quot; functions and constants used for unit testing so that I don't bloat exports of my clean module API.</p>
",https://stackoverflow.com/questions/75301412/advanced-module-unit-test-setup-in-julia,"['unit-testing', 'julia']",73,True,2,1
Type hinting a decorator that injects function parameters / changes the function signature,"<p>I'm trying to write a decorator that can be used to suppress exceptions raised in a decorated function and return a default value instead.</p>
<p>I have struggled with getting the type hints correct, but all I'm left with now is an <code>error: Unexpected keyword argument &quot;default&quot;</code>.</p>
<p>Is there any way I can add the injected default (keyword) argument to the signature of the decorated method so that it is not unexpected anymore?</p>
<p>The decorator is implemented as follows:</p>
<pre class=""lang-py prettyprint-override""><code>import functools
from typing import TypeVar, ParamSpec, Callable

P = ParamSpec(&quot;P&quot;)
R = TypeVar(&quot;R&quot;)


def suppress(
    default: object = None,
) -&gt; Callable[[Callable[P, R]], Callable[P, R | object]]:

    def decorator_suppress(func: Callable[P, R]) -&gt; Callable[P, R | object]:
        functools.wraps(
            func,
        )

        def wrapper_suppress(
            *args: P.args,
            default: object = default,
            **kwargs: P.kwargs,
        ) -&gt; R | object:

            try:
                return func(*args, **kwargs)
            except Exception as e:
                return default

        return wrapper_suppress

    return decorator_suppress
</code></pre>
<p>The decorator should work in such a way that the default value can either be set as a parameter on the decorator itself, but also as a keyword argument on the function it decorates (to make for easier unit-testing)</p>
<pre class=""lang-py prettyprint-override""><code>@suppress(default=&quot;foo!&quot;)
def foo(a: int, b: int) -&gt; int:
    return a + b


a = foo(1, 1)
b = foo(1, &quot;2&quot;)
c = foo(1, &quot;2&quot;, default=&quot;bar!&quot;)

print(a)
print(b)
print(c)
</code></pre>
<p>results in:</p>
<pre><code>2
foo!
bar!
</code></pre>
<p>The mypy error:</p>
<pre><code>error: Unexpected keyword argument &quot;default&quot; for &quot;foo&quot;  [call-arg]
</code></pre>
<p>is (obviously) raised from:</p>
<pre class=""lang-py prettyprint-override""><code>c = foo(1, &quot;2&quot;, default=&quot;bar!&quot;)
</code></pre>
",https://stackoverflow.com/questions/75890433/type-hinting-a-decorator-that-injects-function-parameters-changes-the-function,"['python', 'python-decorators', 'mypy', 'functools']",56,False,2,0
Data Not Found Hit API of Unit Testing Laravel 8.x,"<p>I'm new to working on backend to make a unit testing of index method with Bearer Token for authentication.</p>
<p>But, I got failure after I run the command : <code>.\vendor\bin\phpunit</code> like below :</p>
<pre><code>PHPUnit 9.5.27 by Sebastian Bergmann and contributors.

..F                                                                 3 / 3 (100%)

Time: 00:00.228, Memory: 24.00 MB

There was 1 failure:

1) Tests\Feature\UserControllerTest::test_returns_user_data_list_successfully
Expected response status code [200] but received 404.

The following errors occurred during the request:

{
    &quot;success&quot;: false,
    &quot;message&quot;: &quot;Failed&quot;,
    &quot;error_code&quot;: 4041,
    &quot;errors&quot;: {
        &quot;message&quot;: &quot;Data not found&quot;
    }
}

Failed asserting that 200 is identical to 404.

C:\Users\artha\Documents\Switch\vendor\laravel\framework\src\Illuminate\Testing\TestResponse.php:177
C:\Users\artha\Documents\Switch\tests\Feature\UserControllerTest.php:18
</code></pre>
<p>For UserContoller.php :</p>
<pre><code>class UserController extends Controller
{
    public function __construct()
    {
        $this-&gt;middleware('auth.jwt');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = User::orderBy('created_at', 'DESC')-&gt;all();
        $message = 'Success';
        return $this-&gt;sendResponse($user-&gt;makeVisible('role'), $message, 200);
    }
}
</code></pre>
<p>The code of <code>route/api.php</code> :</p>
<pre><code>Route::resource('user', UserController::class, ['except' =&gt; ['create', 'edit']]);
</code></pre>
<p>And I made <code>UserContollerTest.php</code> like below :</p>
<pre><code>&lt;?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class UserControllerTest extends TestCase
{
    public function test_returns_user_data_list_successfully()
    {
        $token    = 'eyJ0eXA.....dY3CtVO1T4o--8nM';
        $response = $this-&gt;withHeaders(['Authorization' =&gt; 'Bearer '. $token,
                        'Accept' =&gt; 'application/json'])
                        -&gt;get('api/user/index');

        $response-&gt;assertStatus(200);
    }
}
</code></pre>
<p>I tried to solved with various ways on internet like read all official documentations and others but I didn't get insight right to solve this. I made <code>.env.testing</code>, too.</p>
<p>Any idea, how to solving this problem?</p>
<p>Thank you for your insight.</p>
<p>I tried to solve with these link :
<a href=""https://www.stackoverflow.com/"">https://stackoverflow.com/questions/46769959/laravel-phpunit-test-with-api-token-authentication</a></p>
<p><a href=""https://www.stackoverflow.com/"">https://stackoverflow.com/questions/55568924/how-to-pass-bearer-token-to-test-api-using-phpunit-and-liip</a></p>
<p><a href=""https://www.stackoverflow.com/"">https://laravel.com/docs/6.x/http-tests#session-and-authentication</a></p>
",https://stackoverflow.com/questions/75016126/data-not-found-hit-api-of-unit-testing-laravel-8-x,"['unit-testing', 'laravel-8', 'bearer-token']",33,False,1,0
How to test if a method retrieves data in Jasmine + Angular14,"<p>As part of my job, I am working on an Angular project using v14, but im pretty new with unit testing with Jasmine.</p>
<p>My problem is that I need to test if a custom autocomplete component (which we created and is working as it should) is retrieving a list of objects that it requires, and i can't figure it out how to do it.</p>
<p>I will provide all my code and then what I've tried.</p>
<p><strong>component.ts:</strong></p>
<pre><code>getFooList(): void {
    this.optionsFoo =
      this.foobar?.map((bar) =&gt; {
        return {
          label: bar.property ?? '',
          value: bar
        }
      }) ?? []
    this.optionsFooToDisplay = this.optionsFoo 
  }
</code></pre>
<p>The <code>optionsFooToDisplay</code> variable is an array of objects which look like this:</p>
<pre><code>Option&lt;FOO&gt;[]
</code></pre>
<p><strong>Option interface:</strong></p>
<pre><code>export interface Option&lt;T&gt; {
  label: string
  value: T
}
</code></pre>
<p><strong>FOO interface:</strong></p>
<pre><code>export interface FOO {
  foo1?: string
  foo2?: string
  foo3?: string
  foo4?: string
  foo5?: string
  foo6?: string
}
</code></pre>
<p>And this is what I've tried so far:
<strong>component.spec.ts</strong>:</p>
<pre><code>it('should retrieve list of foos', () =&gt; {
    const mockFoo: Option&lt;FOO&gt; =
      [
        {
          label: 'foooo',
          value: {
            foo1: '69420',
            foo2: 'baaaar',
            foo3: 'AA',
            foo4: 'BBBBB',
            foo5: 'CC',
            foo6: 'DDDDDD'
          }
        }
      ] ?? []
    expect(component.optionsFooToDisplay).toContain(mockFoo)
  })
</code></pre>
<p>And finally, this is the error that VSCode shows:</p>
<pre><code>Type '{ label: string; value: { foo1: string; foo2: string; foo3: string; foo4: string; foo5: string; foo6: string; }; }[]' is missing the following properties from type 'Option&lt;FOO&gt;': label, value
</code></pre>
<p>I'm stuck there and I don't know how to develop that properly.</p>
",https://stackoverflow.com/questions/75821570/how-to-test-if-a-method-retrieves-data-in-jasmine-angular14,"['angular', 'testing', 'jasmine', 'karma-jasmine']",22,True,0,1
nginx config for websockets (Actioncable),"<p>I am trying to set up nginx config to support Ruby's actioncable flavor of websockets, and I continue to get a 404 at the mounted path. The logs show:</p>
<pre><code>Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: close, HTTP_UPGRADE: )
</code></pre>
<p>I am modifying config already set by my company's platform, and it looks like:</p>
<pre><code>location / {
        # root location for static assets
        root /opt/app/public;

        # for uri's not found in public assets look for index.html, if doesn't exist fall back to @app
        try_files $uri $uri/index.html @app;
      }

      location @app {
          &lt;% if !ENV['PROXY_HTTP_VERSION'].nil? &amp;&amp; !ENV['PROXY_HTTP_VERSION'].empty? %&gt;proxy_http_version &lt;%= ENV[&quot;PROXY_HTTP_VERSION&quot;] %&gt;;&lt;% end %&gt; 
          proxy_pass http://app;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header Host $http_host;
          proxy_set_header X-Request-Start $reqstart;
          proxy_read_timeout &lt;%= !ENV['NGINX_PROXY_READ_TIMEOUT_SECONDS'].nil? &amp;&amp; !ENV['NGINX_PROXY_READ_TIMEOUT_SECONDS'].empty? ? ENV[&quot;NGINX_PROXY_READ_TIMEOUT_SECONDS&quot;] : 60 %&gt;;
          proxy_redirect off;
          proxy_request_buffering &lt;%= (ENV['NGINX_DISABLE_PROXY_REQUEST_BUFFERING'] == 'true') ? 'off' : 'on' %&gt;;
      }

        set $cable_location &lt;% if !ENV['BASEPATH'].nil? &amp;&amp; !ENV['BASEPATH'].empty? %&gt;&lt;%= ENV[&quot;BASEPATH&quot;] %&gt;/&lt;%= ENV[&quot;WEBSOCKET_ROUTE&quot;] %&gt;;&lt;% else %&gt;/&lt;%= ENV[&quot;WEBSOCKET_ROUTE&quot;] %&gt;;&lt;% end %&gt;

        location $cable_location {
            &lt;% if !ENV['PROXY_HTTP_VERSION'].nil? &amp;&amp; !ENV['PROXY_HTTP_VERSION'].empty? %&gt;proxy_http_version &lt;%= ENV[&quot;PROXY_HTTP_VERSION&quot;] %&gt;;&lt;% end %&gt; 
            proxy_pass http://app;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-Request-Start $reqstart;
            proxy_set_header Upgrade &quot;websocket&quot;;
            proxy_set_header Connection &quot;Upgrade&quot;;
            proxy_read_timeout &lt;%= !ENV['NGINX_PROXY_READ_TIMEOUT_SECONDS'].nil? &amp;&amp; !ENV['NGINX_PROXY_READ_TIMEOUT_SECONDS'].empty? ? ENV[&quot;NGINX_PROXY_READ_TIMEOUT_SECONDS&quot;] : 60 %&gt;;
            proxy_redirect off;
            proxy_request_buffering &lt;%= (ENV['NGINX_DISABLE_PROXY_REQUEST_BUFFERING'] == 'true') ? 'off' : 'on' %&gt;;
        }
</code></pre>
<p>In the above, eventually setting websocket forwarding at all would be wrapped in an if-statement, but for testing it's not. What cable_location would look like is either <code>/basepath/websocket</code> or <code>/websocket</code> depending on what the env variables look like. Unit testing shows that cable_location is correctly set when the env variables exist. The basepath variable would come in such as <code>/basepath</code> and the websocket_route as <code>websocket</code>.</p>
<p>The above config looks correct from my google search, so I'm not sure what I'm missing.</p>
",https://stackoverflow.com/questions/76008324/nginx-config-for-websockets-actioncable,"['nginx', 'websocket', 'actioncable']",24,False,0,0
Why must create or call of the Java class before modifying static final field of another class with Unsafe?,"<p>I tried applying <code>sun.misc.Unsafe</code> to modify <code>public static final</code> field of some class for unit testing and <code>jmh</code> benchmarks. Testing with, at least, JDK11 to JDK17, it seemed to work well only after the class object is created or some static function of that class is called as some trigger. My full code is in the bottom.</p>
<h2>Questions</h2>
<ul>
<li><strong>Why is it required before modification?</strong></li>
<li><strong>Is there any other way to do modification with less executions and memory consumption?</strong></li>
</ul>
<h2>More Details</h2>
<p>Some methods worked only in <em>SOME</em> platform or JDK version. For example:</p>
<pre><code>Object o = Another.class;

// ...
</code></pre>
<p>or</p>
<pre><code>{
    Object o = Another.class;
} // save stack

// ...
</code></pre>
<p>worked with version &quot;16-ea&quot; in sololearn playground, but not work on my OpenJDK 15.0.2+7 (Zulu15.29.15 on macOS 13.1).</p>
<p>And another method that worked in both platforms:</p>
<pre><code>{
    Object a = new Another();
}

// ...
</code></pre>
<p>or</p>
<pre><code>Another.hi();

// ...

class Another () {
    public static void hi () {}
}
</code></pre>
<h2>Reference</h2>
<p><a href=""https://stackoverflow.com/a/61150853/8244977"">https://stackoverflow.com/a/61150853/8244977</a></p>
<h2>Full Example</h2>
<pre><code>import sun.misc.Unsafe;
import java.lang.reflect.Field;

public class Program
{
    public static final Object SF = &quot;Original&quot;;

    public static void main(String[] args) throws Exception {
        ////////////////////////////////////////////////////////////////////////////////
        // Test with this class

        modify(Program.class.getDeclaredField(&quot;SF&quot;), &quot;New-1&quot;);
        System.out.println(&quot;Program.SF:\t&quot; + Program.SF);  // Worked: Program.SF:   New-1

        modify(Program.class.getDeclaredField(&quot;SF&quot;), &quot;New-2&quot;);
        System.out.println(&quot;Program.SF:\t&quot; + Program.SF);  // Worked: Program.SF:   New-2

        ////////////////////////////////////////////////////////////////////////////////
        // Test with another class

        modify(Another.class.getDeclaredField(&quot;SF&quot;), &quot;New-1&quot;);
        System.out.println(&quot;Another.SF:\t&quot; + Another.SF);  // Failed: Another.SF:   Original

        // like a trigger
        {
            Object c = new Another();
        }

        modify(Another.class.getDeclaredField(&quot;SF&quot;), &quot;New-2&quot;);
        System.out.println(&quot;Another.SF:\t&quot; + Another.SF);  // Worked: Another.SF:   New-2
    }

    public static void modify(Field f, Object v) throws Exception {
        Field fu = Unsafe.class.getDeclaredField(&quot;theUnsafe&quot;);
        fu.setAccessible(true);
        Unsafe u = (Unsafe) fu.get(null);

        u.putObject(
            u.staticFieldBase(f),
            u.staticFieldOffset(f),
            v
        );        
    }
}

class Another {
    public static final Object SF = &quot;Original&quot;;
}
</code></pre>
",https://stackoverflow.com/questions/75713240/why-must-create-or-call-of-the-java-class-before-modifying-static-final-field-of,"['java', 'reflection', 'static', 'final', 'unsafe']",89,True,0,3
What is the problem with my R Shiny module unit-testing that it returns not a failing nor a success message?,"<p>I have a Shiny app with two modules. The dataselect-and-table_module.R updates the second <code>selectInput(&quot;speciesName&quot;)</code> depending on the first <code>selectInput(&quot;speciesNametype&quot;)</code> and the timeline_module.R plots a timeline for the selected rows of data. I want to test the dataselect-and-table_module.R server with testthat package.</p>
<p>I made the Shiny app file structure as follows:</p>
<pre><code>myapp/
|- app.R
|- R
|   |- dataselect-and-table_module.R
|   |- timeline_module
`- tests
    `- testthat
        |- dataselect-and-table_module.R
</code></pre>
<p>Where dataselect-and-table_module.R contains the <code>dataselect_ui</code> and <code>dataselect_server</code> code.</p>
<p>I expected the result of this test to pass, but it tells just this instead:</p>
<pre><code>Backtrace:
  1. shiny::testServer(...)
 22. session$setInputs(speciesNametype = &quot;Scientific Name&quot;, speciesName = &quot;Aix galericulata&quot;)
 23. self$setInputs(!!!mapNames(ns, rlang::dots_list(..., .homonyms = &quot;error&quot;)))
 24. private$flush()
 25. shiny:::flushReact()
 26. .getReactiveEnvironment()$flush()
 27. ctx$executeFlushCallbacks()
 28. base::lapply(...)
 29. shiny:::FUN(X[[i]], ...)
 30. shiny:::flushCallback()
     ...
 61. shiny:::do()
 70. base::Reduce(...)
 71. shiny:::f(init, x[[i]])
 73. shiny:::func(v$value)
 86. shiny:::valueFunc()
 87. shiny:::`&lt;observer:observeEvent(input$speciesNametype)&gt;`(...)
 88. observe()
 89. shiny::updateSelectizeInput(...)
 90. shiny::updateSelectInput(session, inputId, label, choices, selected)
 91. shiny:::selectOptions(choices, selected, inputId, FALSE)
</code></pre>
<p>This is the unit test that I have written:</p>
<pre><code>library(testthat)
library(shiny)
library(shinytest)
test_that(&quot;the right rows of data are selected &quot;, {
  testServer(dataselect_server, {
    session$setInputs(speciesNametype =&quot;Scientific Name&quot;, speciesName=&quot;Aix galericulata&quot;)
    df&lt;-fread(&quot;R/www/polData.csv&quot;,data.table=FALSE)
    colnames(df)&lt;-c(&quot;Country&quot;,&quot;Scientific Name&quot;, &quot;Vernacular Name&quot;,&quot;Event Date&quot;,&quot;Event Time&quot;,&quot;Longitude Decimal&quot;,&quot;Latitude Decimal&quot;,&quot;Individual Count&quot;)
    df&lt;-df[-1]
    rownames(df) &lt;- NULL
    df&lt;-df[df$`Scientific Name`==&quot;Aix galericulata&quot;,]
    expect_true(identical(finalDf(), df))
  })
})
</code></pre>
<p>The <code>df</code> is:</p>
<pre><code>df&lt;-fread(&quot;R/www/polData.csv&quot;,data.table=FALSE)
colnames(df)&lt;-c(&quot;Country&quot;,&quot;Scientific Name&quot;, &quot;Vernacular Name&quot;,&quot;Event Date&quot;,&quot;Event Time&quot;,&quot;Longitude Decimal&quot;,&quot;Latitude Decimal&quot;,&quot;Individual Count&quot;)
df&lt;-df[-1]
rownames(df) &lt;- NULL
df&lt;-df[df$`Scientific Name`==&quot;Aix galericulata&quot;,]
df
       Scientific Name Vernacular Name Event Date Event Time Longitude Decimal Latitude Decimal Individual Count
1     Aix galericulata   Mandarin Duck 2015-03-11      23:16          21.03560         52.21380                1
16005 Aix galericulata   Mandarin Duck 2019-12-26      12:13          21.03505         52.20979               10
16006 Aix galericulata   Mandarin Duck 2019-12-26      12:17          21.03505         52.20974               41
16045 Aix galericulata   Mandarin Duck 2019-10-31      14:54          21.03168         52.22670               20
19163 Aix galericulata   Mandarin Duck 2019-05-08      18:30          21.02606         52.22140               10
19830 Aix galericulata   Mandarin Duck 2019-05-09      11:35          21.02997         52.24705                1
20050 Aix galericulata   Mandarin Duck 2019-04-27      17:42          21.03504         52.21534               10
21002 Aix galericulata   Mandarin Duck 2019-04-06      10:43          21.03162         52.21270                3
22155 Aix galericulata   Mandarin Duck 2018-07-11                     21.03544         52.21502                1
27988 Aix galericulata   Mandarin Duck 2017-12-26      11:39          21.06793         52.24251                8
43210 Aix galericulata   Mandarin Duck 2015-10-22      11:35          19.93470         50.04780                1
48415 Aix galericulata   Mandarin Duck 2015-03-25                     21.03132         52.21520               20
</code></pre>
<p>And the <code>finalDf()</code> is:</p>
<pre><code>testServer(dataselect_server, {
  session$setInputs(speciesNametype =&quot;Scientific Name&quot;, speciesName=&quot;Aix galericulata&quot;)
  print(finalDf())
})
       Scientific Name Vernacular Name Event Date Event Time Longitude Decimal Latitude Decimal Individual Count
1     Aix galericulata   Mandarin Duck 2015-03-11      23:16          21.03560         52.21380                1
16005 Aix galericulata   Mandarin Duck 2019-12-26      12:13          21.03505         52.20979               10
16006 Aix galericulata   Mandarin Duck 2019-12-26      12:17          21.03505         52.20974               41
16045 Aix galericulata   Mandarin Duck 2019-10-31      14:54          21.03168         52.22670               20
19163 Aix galericulata   Mandarin Duck 2019-05-08      18:30          21.02606         52.22140               10
19830 Aix galericulata   Mandarin Duck 2019-05-09      11:35          21.02997         52.24705                1
20050 Aix galericulata   Mandarin Duck 2019-04-27      17:42          21.03504         52.21534               10
21002 Aix galericulata   Mandarin Duck 2019-04-06      10:43          21.03162         52.21270                3
22155 Aix galericulata   Mandarin Duck 2018-07-11                     21.03544         52.21502                1
27988 Aix galericulata   Mandarin Duck 2017-12-26      11:39          21.06793         52.24251                8
43210 Aix galericulata   Mandarin Duck 2015-10-22      11:35          19.93470         50.04780                1
48415 Aix galericulata   Mandarin Duck 2015-03-25                     21.03132         52.21520               20
</code></pre>
<p>It seems that the two data.frames are exactly the same but I don't know why my test doesn't pass.
I'm new to unit testing. What is my mistake? I appreciate any help.</p>
",https://stackoverflow.com/questions/75158141/what-is-the-problem-with-my-r-shiny-module-unit-testing-that-it-returns-not-a-fa,"['r', 'unit-testing', 'shiny', 'shiny-server']",74,False,0,0
unittest directory structure - cannot import src code,"<p>I have the following folder structure in my project:</p>
<pre><code>my-project
   src/
       __init__.py
       script.py
   test/
       __init__.py
       test_script.py
</code></pre>
<p>Ideally I want to have a separate folder where all the unit tests go. My <code>test_script.py</code> looks something like this:</p>
<pre><code>from src.script import my_object

class TestClass(unittest.TestCase):
    
    def test_script_object(self):
        # unit test here
        pass

if __name__ == 'main':
    unittest.main()
</code></pre>
<p>When I try to run the script (using <code>python test_script.py</code>) I get the following error:</p>
<pre><code>Traceback (most recent call last):
  File &quot;test_script.py&quot;, line 4, in &lt;module&gt;
    from src.script import my_object
ModuleNotFoundError: No module named 'src'
</code></pre>
<p>I was following the instructions <a href=""https://stackoverflow.com/questions/1896918/running-unittest-with-typical-test-directory-structure"">from this other thread</a>, and I even tried appending <code>src</code> to the sys path (which forces me to change how I do imports in the rest of the project). When I'm not trying to append to the sys path, both of my <code>__init__.py</code> files are empty.</p>
<p>I am using python 3.8.</p>
<p>Does anyone have any suggestions? I'm new to unit testing in python, so maybe there is a better structure or other conventions I'm not aware of. Thanks in advance for your help!</p>
",https://stackoverflow.com/questions/75036841/unittest-directory-structure-cannot-import-src-code,"['python', 'python-3.x', 'python-unittest']",145,True,0,1
NodeJS Custom Unit Test Automation Query,"<p>I have 2 Java Script files runTest.js and tests.js as below. This code is for custom automation of unit testing and it works. I am relatively new to Java Script syntax and unable to understand how exactly the statement <em>tests.forEach(testRun =&gt; testRun(test));</em> works.</p>
<p>I have tried to read about Exports, Arrow Functions and Anonymous functions. Still could not get clarity on the Java Script syntax used here.</p>
<p>Also, I do understand that <strong>test specification and test function are correlated by name</strong> because, the execution fails at statement <em>tests.forEach(testRun =&gt; testRun(test));</em>, IF any one of the below is true:</p>
<ol>
<li>The exported function name “test” in “module.exports = (test)” is different OR</li>
<li>Name of the function “test” in ”function test(input, expected)” is different</li>
</ol>
<p><strong>runTest.js</strong></p>
<pre><code>const tests = [require('./tests.js')];

function test(input, expected) {
   console.log(input, expected); 
   //Displays 
   //42 and its expected result JSON
   //Hello and its expected result JSON
}


// Run all tests — **HOW DOES THE BELOW STATEMENT REALLY WORK?**
tests.forEach(testRun =&gt; testRun(test));
</code></pre>
<p><strong>tests.js</strong></p>
<pre><code>module.exports = (test) =&gt; {
   //NumericLiteral
   test(`42`, {
      type: &quot;Program&quot;,
      body: {
         type: &quot;NumericLiteral&quot;,
         value: 42,
      },
   });

   //StringLiteral
   test(`'Hello'`, {
      type: &quot;Program&quot;,
      body: {
         type: &quot;StringLiteral&quot;,
         value: &quot;Hello&quot;,
      },
   });
};
</code></pre>
",https://stackoverflow.com/questions/75003629/nodejs-custom-unit-test-automation-query,"['node.js', 'unit-testing', 'anonymous-function']",36,False,0,0
How to get passing parameter count in a function NUNIT mocking assertion?,"<p>How to get the parameters count which is passing to the function using Nunit mocking for assertion and that function called inside another function.</p>
<p>For e.g:</p>
<pre><code>public class TestClass
{
    public string Name {get;set;}
    public int Id {get;set;}
}

public void ProcessData(IEnumerable&lt;EventData&gt; events)
{
    List&lt;TestClass&gt; testClasses = new();

    events.ForEach(msg =&gt; {
       var testClass = JsonConvert.DeserializeObject&lt;TestClass&gt;(msg.EventBody.ToString());

       if(testClass != null)
       {
          testClasses.Add(testClass);
       }
   });

   if(testClasses.Count &gt; 0)
   {
       BulkUpdateData(testClasses);
   }
}

public void BulkUpdateData(List&lt;TestClass&gt; testClasses)
{ ... }
</code></pre>
<p>Now, I need to do unit testing this &quot;ProcessData&quot; method.
For this using NUnit framework in .Net 6.0.</p>
<p>I can pass test data to &quot;ProcessData&quot; method by mocking while writing unit test cases.
But here my case is,</p>
<p><strong>Consider now I'm passing 10 values in a list to &quot;ProcessData&quot;. In that only 8 got passed to &quot;BulkUpdateData&quot; method since 2 values are not got deserialized due to invalid data.
Here how to get this BulkUpdateData got 8 values inside the &quot;ProcessData&quot; method.</strong></p>
<p>I need to get this count value for assertion.</p>
<p>Kindly suggest on this.</p>
",https://stackoverflow.com/questions/75265486/how-to-get-passing-parameter-count-in-a-function-nunit-mocking-assertion,"['c#', '.net', 'unit-testing', 'nunit', 'moq']",42,False,0,1
generate Scala test class in VS Code,"<p>I have written a Scala class in my project and wish to stub the corresponding <code>src/test/**/TestClass.scala</code> by some magical key command or equivalent. Is there a way to do this that is hidden within VS Code or Metals?</p>
<p>edit: I was too general here. I'm not looking for stubbing out tests within a test class for some existing class. I'm looking for feature parity with JetBrains, where I can right-click on a class and get the option to create a corresponding test file within the project. The generated test file contains by default a <code>package</code> line, and an empty class definition that extents a unit testing framework API such as scalatest. The test file template can be further configured by the user via a preferences menu.</p>
",https://stackoverflow.com/questions/76122313/generate-scala-test-class-in-vs-code,"['scala', 'visual-studio-code', 'scala-metals']",25,False,0,0
Issues with mocking functions used by mapping function in Spark apply,"<p>I have a function <code>applier</code> that uses Sparks <code>GroupedData.applyInPandas</code>. The <code>applyInPandas</code> maps the grouped data with a function named <code>mapper</code>, which in turn calls a function <code>get_value</code>. When unit testing, I need to mock the <code>get_value</code>-function. The reason for this is that in my original code, the <code>get_value</code>-function has a side-effect I need to avoid while testing.</p>
<p>The issue is that the <code>get_value</code>-function does get mocked, but the <code>applyInPandas</code>-call does not pick it up. I've constructed this minimal example to illustrate the issue:</p>
<pre><code># funs.py
def get_value():
  return 'not mocked'

def mapper(df):
  t = get_value()
  return df.assign(v=t)

def applier(df):
    print(mapper(df.toPandas()))
    return df.groupby('id').applyInPandas(mapper, schema='id long, v string')
</code></pre>
<p>and</p>
<pre><code># tests.py
import unittest
import unittest.mock as mock
from funs import applier

def get_value_mock():
    return 'mocked'

df = spark.createDataFrame(
  [(1, 'a'), (1, 'b'), (2, 'c'), (2, 'd')],
  ('id', 'v')
)

class Testfuns(unittest.TestCase):
    @mock.patch('funs.get_value', get_value_mock)
    def test_applier(self):
        applier(df).show()

if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)
</code></pre>
<p>Running this outputs:</p>
<pre><code>   id       v
0   1  mocked
1   1  mocked
2   2  mocked
3   2  mocked
.+---+----------+
| id|         v|
+---+----------+
|  1|not mocked|
|  1|not mocked|
|  2|not mocked|
|  2|not mocked|
+---+----------+
</code></pre>
<p>Which tells me that the <code>get_value</code>-function was mocked in the <code>print</code>-call made by <code>applier</code>, but not in the <code>applyInPandas</code>-call.</p>
<p>I would expect the <code>get_value</code>-function to be mocked either everywhere or nowhere in <code>funs.py</code>.</p>
<p>Does anyone have any ideas on what's going on here?</p>
",https://stackoverflow.com/questions/76089298/issues-with-mocking-functions-used-by-mapping-function-in-spark-apply,"['python', 'apache-spark', 'pyspark', 'mocking', 'python-unittest']",63,False,0,0
Should I write unit test for the @KafkaListener,"<p>I have a Kafka consumer which uses <code>@KafkaListener</code>. But the listener does nothing except receiving the message and pass it to private method to do the necessary things. My question is I am wondering whether I need to write integration testing to see listener is working or just the unit test. If I write unit test again the <code>@KafkaListener</code> annotated method is not doing much and just pass the message to relevant private method. So in that case, I cannot write unit tests for private methods. See below receiver code.</p>
<pre><code>@Service
@Slf4j
class KafkaConsumerService {

    @KafkaListener(
        groupId = &quot;#{groupId('listener')}&quot;,
        topics = [&quot;#{pubTopic('someTopic')}&quot;]
    )
    fun process(@Payload message: EventMessage) {
        log.info(&quot;Received a message &gt; &quot;)
        when (message.type) {
            Type1 -&gt; processMessageType1(message.type1Mesage)
            Type2 -&gt; processMessageType2(message.type2Mesage)
            else -&gt; log.info(&quot;unhandled type &quot;)
        }
    }

    private fun processMessageType1(message: Type1Mesage) {
        log.warn(&quot;Received a Type1Mesage &quot; )
        val someClassObj = SomeClass()
        someClassObj.publicMethod(message)
    }

    private fun processMessageType2(message: Type2Mesage) {
        log.warn(&quot;Received a Type2Mesage &quot;)
        val someClassObj = SomeClass()
        someClassObj.publicMethod(message)
    }   
}
</code></pre>
<p>How can I test this? or there is no need to do Unit Testing here? I wrote some integration testing to see whether the listener is working but it did not work. Appreciate expert's advise.</p>
",https://stackoverflow.com/questions/76007690/should-i-write-unit-test-for-the-kafkalistener,"['unit-testing', 'apache-kafka', 'junit', 'integration-testing', 'spring-kafka']",63,True,0,1
tox is not able to recognize python versions installed by pyvenv,"<p>I am trying to learn how to use tox for python unit testing on multiple python installations.  I have used <code>pyenv</code> to install multiple python installations to the <code>/home/username/.pyenv/versions/version_number/bin/python</code>, where <code>version_number</code> could be 3.9.16, or 3.10.9.  I have added the following lines to my <code>pyproject.toml</code> file.  I have a simple test directory structure that looks like</p>
<pre><code>hello
|_ pyproject.toml
|_ hello
|   |_ __init__.py
|   |_ main.py
|_tests
|   |_ __init__.py
    |_ test_main.py
</code></pre>
<p>Among other lines in my <code>pyproject.toml</code> file I have the following <code>tox</code> config lines</p>
<pre><code>[tool.pytest.ini_options]
testpaths = [&quot;tests&quot;]
console_output_style = &quot;progress&quot;

[tool.tox]
legacy_tox_ini = &quot;&quot;&quot;
    [tox]
    env_list = py39, py310, mypy

    [testenv]
    deps = 
        pytest

    [testenv:py39]
    basepython = /home/jonwebb/.pyenv/versions/3.9.16/bin/python 

    [testenv:py310]
    basepython = /home/jonwebb/.pyenv/versions/3.10.9/bin/python

    [testenv:mypy]
    deps = mypy
    commands = mypy hello
&quot;&quot;&quot;
</code></pre>
<p>When I try to run tox from the uppermost <code>hello</code> directory I get an error stating;</p>
<pre><code>py39: failed with env name py39 conflicting with base python /home/username/.pyenv/version/3.9.16/bin/python
py310: failed with env name py310 conflicting with base python /home/username/.pyenv/versions/3.10.9/bin/python
</code></pre>
<p>It appears that <code>tox</code> is having problems with my python installations created with <code>pyenv</code>.  How can I fix this installation so it recognizes my python installations installed with <code>pyenv</code>?  It is probably worth noting that this code implementation is using a local .venv folder created with <code>poetry</code>.</p>
",https://stackoverflow.com/questions/75425311/tox-is-not-able-to-recognize-python-versions-installed-by-pyvenv,"['python', 'pyenv', 'tox']",145,True,0,1
Code Coverage Triggered by an External/Consumer Application,"<p>I am working on a node module that will be consumed by another application.</p>
<p>I know certain unit testing modules have this built-in functionality, but I need to check the coverage of my code without using unit tests (Jest, for example).</p>
<p>I specifically need the code coverage for which lines were called by the consumer application. Probably something like a code coverage listener where I can start the listener &gt; run the consumer application &gt; capture the report.</p>
<p>// My module (crypto-module)</p>
<pre><code>function performEncryption(data) {
  // codes
}
</code></pre>
<p>// External app</p>
<pre><code>const crypto = require('crypto-module')
crypto.performEncryption(data)
</code></pre>
<p>Basically the external app will be ran and I need to know which lines were called by it in my module, <code>crypto-module</code> (strictly need the code coverage percentages. breakpoints or logs are not applicable in this scenario).</p>
<p>Any suggestions are welcome. Thank you!</p>
",https://stackoverflow.com/questions/75692767/code-coverage-triggered-by-an-external-consumer-application,"['node.js', 'code-coverage']",14,False,0,0
Microsoft.Azure.Functions.Worker.Middleware.IFunctionsWorkerMiddleware Unit Testing,"<p>Looking for some examples on how to setup unit testing around IFunctionsWorkerMiddleware.  All the examples I've found are for MVC and not function apps.</p>
<p>Example for MVC, but looking for .net 6 using function apps</p>
<pre><code>using var host = await new HostBuilder() .ConfigureWebHost(webBuilder =&gt; { webBuilder .UseTestServer() .ConfigureServices(services =&gt; { services.AddMyServices(); }) .Configure(app =&gt; { app.UseMiddleware&lt;MyMiddleware&gt;(); }); }) .StartAsync(); var response = await host.GetTestClient().GetAsync(&quot;/&quot;)
</code></pre>
<p>Thanks in advance.</p>
<p>In order to test the middleware we need to spin up a host using HostBuilder; as part of configuring host builder we can stipulate it needs to use the test server (an in-memory webserver).  This is what we will make request against an what should be executing the middleware. Every single example I've found and tried are all for MVC  and nothing for function apps.  and every attempt pretty much results in a gRPC issue (gRPC is spun uo by the function app process by default, I cannot find where/how to not set it up).</p>
",https://stackoverflow.com/questions/75236439/microsoft-azure-functions-worker-middleware-ifunctionsworkermiddleware-unit-test,['asp.net-core-middleware'],144,False,1,0
MIniHBaseCluster shutting down with java.lang.RuntimeException: Master not initialized after 200000ms,"<p>To give a background, our project uses bigtable. For unit testing, we are using the package hbase-testing-util:2.2.3 for creating a local mini hbase cluster.
Our code base is in Java 8 and I'm trying to migrate it to Java 17. While doing so, I'm encountering the following error on running the unit tests (in java 17).</p>
<pre><code>Starting hbase testing utility failed: java.io.IOException: Shutting down
    at org.apache.hadoop.hbase.MiniHBaseCluster.init(MiniHBaseCluster.java:266)
    at org.apache.hadoop.hbase.MiniHBaseCluster.&lt;init&gt;(MiniHBaseCluster.java:116)
    at org.apache.hadoop.hbase.HBaseTestingUtility.startMiniHBaseCluster(HBaseTestingUtility.java:1142)
    at org.apache.hadoop.hbase.HBaseTestingUtility.startMiniCluster(HBaseTestingUtility.java:1107)
    at org.apache.hadoop.hbase.HBaseTestingUtility.startMiniCluster(HBaseTestingUtility.java:1071)
    at com.yawasa.server.testing.TestingUtility.init(TestingUtility.java:165)
</code></pre>
<pre><code>java.lang.ExceptionInInitializerError
    at com.yawasa.server.BabelFishStringValueTest.before(BabelFishStringValueTest.java:56)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.RunBefores.invokeMethod(RunBefores.java:33)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:108)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:57)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:39)
    at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:52)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at jdk.proxy1/jdk.proxy1.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$2.run(TestWorker.java:176)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:113)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:65)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
Caused by: java.lang.RuntimeException: java.io.IOException: Shutting down
    at com.yawasa.server.testing.TestingUtility.init(TestingUtility.java:195)
    at com.yawasa.server.testing.TestingUtility.&lt;clinit&gt;(TestingUtility.java:713)
    ... 46 more
Caused by: java.io.IOException: Shutting down
    at org.apache.hadoop.hbase.MiniHBaseCluster.init(MiniHBaseCluster.java:266)
    at org.apache.hadoop.hbase.MiniHBaseCluster.&lt;init&gt;(MiniHBaseCluster.java:116)
    at org.apache.hadoop.hbase.HBaseTestingUtility.startMiniHBaseCluster(HBaseTestingUtility.java:1142)
    at org.apache.hadoop.hbase.HBaseTestingUtility.startMiniCluster(HBaseTestingUtility.java:1107)
    at org.apache.hadoop.hbase.HBaseTestingUtility.startMiniCluster(HBaseTestingUtility.java:1071)
    at com.yawasa.server.testing.TestingUtility.init(TestingUtility.java:165)
    ... 47 more
Caused by: java.lang.RuntimeException: Master not initialized after 200000ms
    at org.apache.hadoop.hbase.util.JVMClusterUtil.waitForEvent(JVMClusterUtil.java:229)
    at org.apache.hadoop.hbase.util.JVMClusterUtil.startup(JVMClusterUtil.java:197)
    at org.apache.hadoop.hbase.LocalHBaseCluster.startup(LocalHBaseCluster.java:413)
    at org.apache.hadoop.hbase.MiniHBaseCluster.init(MiniHBaseCluster.java:259)
    ... 52 more
</code></pre>
<p>There is another set of stacktrace for ~360 threads that indicate that the threads are waiting for some event. They look like this:</p>
<pre><code>Thread 340 (master/localhost:0.Chore.1):
  State: TIMED_WAITING
  Blocked count: 0
  Waited count: 3
  Stack:
    java.base@17.0.7/jdk.internal.misc.Unsafe.park(Native Method)
    java.base@17.0.7/java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:252)
    java.base@17.0.7/java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:1672)
    java.base@17.0.7/java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1182)
    java.base@17.0.7/java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:899)
    java.base@17.0.7/java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1062)
    java.base@17.0.7/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1122)
    java.base@17.0.7/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
    java.base@17.0.7/java.lang.Thread.run(Thread.java:833)
Thread 341 (snapshot-hfile-cleaner-cache-refresher):
  State: TIMED_WAITING
  Blocked count: 0
  Waited count: 1
  Stack:
    java.base@17.0.7/java.lang.Object.wait(Native Method)
    java.base@17.0.7/java.util.TimerThread.mainLoop(Timer.java:563)
    java.base@17.0.7/java.util.TimerThread.run(Timer.java:516)
</code></pre>
<p>I haven't been able to find any info for this particular issue.</p>
<p>I tried upgrading the library to 2.3.0+ version but that is leading to a jar hell much before this code path is hit, so I'm not sure if resolving the jar hell will resolve the complete issue.</p>
",https://stackoverflow.com/questions/76224450/minihbasecluster-shutting-down-with-java-lang-runtimeexception-master-not-initi,"['java', 'unit-testing', 'hbase', 'java-17', 'hbasetestingutility']",53,False,1,0
Create list of imports service provider on unit testing,"<p>I'm new to Angular, and I have a new team that told me to implement unit testing on an old project with Angular 8. So after investigating that, I decided to use Karma + Jasmine, and I created <code>.spect.ts</code> document like this:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>describe(""CashFlowSalariesComponent"", () =&gt; {
      let fixture: ComponentFixture &lt; CashFlowSalariesComponent &gt; ;
      let instance;
      let profile: ProfileModel;

      beforeEach(async() =&gt; {
        TestBed.configureTestingModule({
          schemas: [CUSTOM_ELEMENTS_SCHEMA],
          imports: [
            RouterTestingModule,
            FormsModule,
            ReactiveFormsModule,
            BrowserModule,
            HttpClientModule,
            ToastrModule.forRoot({
              positionClass: ""toast-bottom-right"",
            }),
          ],
          declarations: [CashFlowSalariesComponent],
          providers: [
             ApiService,
    UserService,
    ProfileService,
    VettingStatusService,
    SkillService,
    ApplicationRoleService,
    SeniorityLevelService,
    PlacementStatusService,
    EducationLevelService,
    UtilsService,
    ShirtSizeService,
    GenderService,
    TimeZoneService,
    CountryService,
    CityService,
    PostalCodeService,
    StateService,
    ClientSectorService,
    JobService,
    ClientService,
    PulsecheckQuestionService,
    PulsecheckMasterService,
    ExchangeRateService,
    DepartmentService,
    ExpenseService,
    ProfileRoleService,
    SkillCategoriesService,
    ProfileActivityService,
    ProfileSalaryActivityService,
    TimeSheetService,
    HolidayService,
    RequestTimeOffService,
    TimeOffTypeService,
    InvoiceService,
    PulsecheckDetailService,
          ],
        }).compileComponents();

        fixture = TestBed.createComponent(CashFlowSalariesComponent);
        instance = fixture.componentInstance;

        fixture.detectChanges();

        profile = new ProfileModel();
        (instance as any).exchangeRate = 18.92;
      });

      afterEach(() =&gt; {
        fixture.destroy();
      });

      it(""To test instance creation of component"", () =&gt; {
        expect(instance).toBeTruthy();
      });</code></pre>
</div>
</div>
</p>
<p>As you can see, I had to import many services from providers because my ApiService had injected them, so if I no add them, it returned an error like this:</p>
<blockquote>
<p>NullInjectorError: No provider for {serviceName}!</p>
</blockquote>
<p>So each time I call the ApiService on each component, developers should copy and paste from this component all the services. So my question is: is this a way to create a class or something to import all providers in once without copying and pasting code each time? How can I achieve this?</p>
",https://stackoverflow.com/questions/75197251/create-list-of-imports-service-provider-on-unit-testing,"['javascript', 'angular', 'typescript', 'jasmine', 'karma-jasmine']",75,True,1,1
How to parametrize a parametrized function in pytest?,"<p>I have the following pytest function, where GAMES_AVAILABLE is a dynamic list of different games that I want my code to test.</p>
<pre><code>@pytest.mark.parametrize(&quot;game_ref&quot;, GAMES_AVAILABLE)
def test_all_games(game_ref):
    game_components = build_game_components(game_ref)
    available_players = determine_available_players(game_components)
    teams = create_player_teams(game_components['game'].number_of_players,available_players)
    for players in teams:
        if 'viz' in game_components:
            arena = Arena(players, game_components['game'], game_components['viz'])
        else:
            arena = Arena(players, game_components['game'])
        arena.playGames(2)
    return teams
</code></pre>
<p>With the following output</p>
<pre><code>Testing started at 4:20 p.m. ...
Connected to pydev debugger (build 223.8617.48)
Launching pytest with arguments /home/tue/PycharmProjects/Hive_nn/tests/test_all_games.py --no-header --no-summary -q in /home/tue/PycharmProjects/Hive_nn/tests

============================= test session starts ==============================
collecting ... collected 3 items

test_all_games.py::test_all_games[game_ref0] 
test_all_games.py::test_all_games[game_ref1] 
test_all_games.py::test_all_games[game_ref2] 

======================== 3 passed, 3 warnings in 7.56s =========================

Process finished with exit code 0
</code></pre>
<p>As it currently is, my code plays each game in all the possible configurations that the game can be played in, which is done dynamically depending on what functions have been implemented for a particular game.</p>
<p>Right now my code produces one test per game, however I would like for it to produce one test per team in each game and then run:</p>
<pre><code>    if 'viz' in game_components:
        arena = Arena(players, game_components['game'], game_components['viz'])
    else:
        arena = Arena(players, game_components['game'])
    arena.playGames(2)
</code></pre>
<p>inside these new subtest.</p>
<p>But I am not sure how to do that?</p>
<p>Also I am very new to unit testing so if something seems strange or stupid in my code, it probably is, and I would appreciate any feedback about what to improve :)</p>
",https://stackoverflow.com/questions/75511490/how-to-parametrize-a-parametrized-function-in-pytest,"['python', 'unit-testing', 'pytest']",22,True,0,1
"React Element I want to unit test is state dependent, but testing state is not recommended in RTL. What to do?","<p>I know I should not test state with React Testing Library. But in my case the visibility of element is depended on state of the component.</p>
<p>As you see in this code,</p>
<pre class=""lang-js prettyprint-override""><code>export const SliderContainer = ({ totalSliderItems, sliderItems }: SliderProps): JSX.Element =&gt; {
 const [activeSlideItem, setActiveSlideItem] = useState&lt;number&gt;(0);

 const changeActiveSlideItem = (action: string): void =&gt; {
   switch (action) {
     case 'prev':
       activeSlideItem &gt; 0 &amp;&amp; setActiveSlideItem(activeSlideItem - 1);
       break;
     case 'next':
       activeSlideItem &lt; totalSliderItems &amp;&amp; setActiveSlideItem(activeSlideItem + 1);
       break;
   }
 }

 return (
   &lt;div className='relative'&gt;
     &lt;SliderButton data-testid=&quot;prevButton&quot; type=&quot;prev&quot; onClick={() =&gt; { changeActiveSlideItem('prev') }} disabled={activeSlideItem === 0 &amp;&amp; true}/&gt;
       {/* Create an array with length totalSlideItems and then render SliderItem totalSlideItems times */}
       &lt;div className=&quot;slide flex&quot; style={{ transform: `translateX(-${activeSlideItem * 100}%)` }}&gt;
         {Array.from({ length: totalSliderItems }, (_, index) =&gt; {
           return &lt;SliderItem
                     key={index}
                     imageSrc={sliderItems[index].imageSrc}
                     imageAlt={sliderItems[index].imageAlt}
                     sliderItemDescription={sliderItems[index].sliderItemDescription}
                 /&gt;
         })}
       &lt;/div&gt;
       &lt;SliderButton data-testid=&quot;nextButton&quot; type=&quot;next&quot; onClick={() =&gt; { changeActiveSlideItem('next') }} disabled={activeSlideItem === totalSliderItems - 1 &amp;&amp; true}/&gt;
   &lt;/div&gt;
 )
}
</code></pre>
<p>code for SliderButton</p>
<pre class=""lang-js prettyprint-override""><code>import classNames from 'classnames';
import { MouseEventHandler } from 'react';

interface SliderButtonProps {
  type: string
  onClick?: MouseEventHandler
  disabled?: boolean
  className?: boolean
}
export const SliderButton = ({ type, onClick, disabled, className }: SliderButtonProps): 
JSX.Element =&gt; {
  return (
    &lt;button onClick={onClick} className={classNames(className, 'absolute sliderButton', disabled &amp;&amp; 'disabled')} data-testid={`${type}-button`}&gt;
        {type}
    &lt;/button&gt;
  )
};
</code></pre>
<p>the prop <code>disable</code> is dependent on value of the state <code>activeSlideItem</code>. So, to test is the button disabled or not, somehow I must set value to the <code>activeSlideItem</code> during unit testing. But as far as I know, we should not test state with React Testing Library because RTL runs the test from user perspective and users have no idea about component state. What can I do? I can't use enzyme either because I found a lot of articles which say Enzyme is dead. Or is there any other smarter way to perform the test?</p>
<p>my Jest code..</p>
<pre class=""lang-js prettyprint-override""><code>import { render } from '@testing-library/react';
import SliderContainer from './slider';

describe('slider test', () =&gt; {
  const sliderItems = [{
    imageSrc: 'images/test/test.jpg',
    imageAlt: 'test',
    sliderItemDescription: 'test'
  }, {
    imageSrc: 'images/test/test.jpg',
    imageAlt: 'test',
    sliderItemDescription: 'test'
  }, {
    imageSrc: 'images/test/test.jpg',
    imageAlt: 'test',
    sliderItemDescription: 'test'
  }]
  it('previous button is disabled when activeSliderItem is 0', () =&gt; {
    const slider = render(&lt;SliderContainer sliderItems={sliderItems} totalSliderItems={sliderItems.length}/&gt;)
    // code for testing is prev button is disabled ..
  });
})
</code></pre>
",https://stackoverflow.com/questions/75971482/react-element-i-want-to-unit-test-is-state-dependent-but-testing-state-is-not-r,['react-testing-library'],45,False,0,1
ShowDialog stalls with .NET Core 6,"<p>I am upgrading from .NET Framework to .NET Core and I am having a problem with <code>ShowDialog</code>. With .NET Framework and unit testing the <code>ShowDialog</code> hits the command and keeps right on processing but with .NET Core the <code>ShowDialog</code> starts a new thread and stays there until a button is selected manually. This can't work with a unit test.</p>
<p>This line of code:</p>
<pre><code>tabControl.SelectTabItem(1); // FlaUI command
</code></pre>
<p>causes the popup window to be displayed but I need to select a grid item and an Ok button. My question is how to not stall on the <code>ShowDialog</code> action?</p>
<p>This is a picture of the Dialog box:
<a href=""https://i.stack.imgur.com/SAPu0.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/SAPu0.png"" alt=""enter image description here"" /></a></p>
<p>The Unit test is in it's own project and calls the dialog box in another project as shown:</p>
<pre><code>       tableSelection = new DatabaseTableSelection(filePath, contr);
       tableSelection.Topmost = true;
       tableSelection.ShowDialog();
       if (tableSelection.selectedTable == null)
       {
          return false;
       }
</code></pre>
<p>It seems that I need to Mock this but I have never used mock before. Any ideas?</p>
",https://stackoverflow.com/questions/75312735/showdialog-stalls-with-net-core-6,"['c#', 'wpf', 'unit-testing', '.net-core', 'mocking']",84,False,-1,1
Error this.http.post is not a function with Jasmine,"<p>I just started testing my software with Jasmine and Karma (haven't done any unit testing not E2E yet so I'm just a newbie here).</p>
<p>What I have been asked to do is to create a generic API service that you call everytime you need to make an HTTP request, in order to avoid repeating code and making programming faster. I show you what I already have:</p>
<p><strong>api.service.ts</strong></p>
<pre><code>import { HttpClient, HttpContext, HttpParams } from '@angular/common/http'
import { Injectable } from '@angular/core'
import { Observable } from 'rxjs'

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  headers: ApiRequests = {
    httpHeaderAccept: 'application/json',
    context: new HttpContext(),
    params: new HttpParams()
  }

  constructor(private _http: HttpClient) {}

  post&lt;T&gt;(url: string, body: object): Observable&lt;T&gt; {
    return this._http.post&lt;T&gt;(url, body, { ...this.headers })
  }
}
</code></pre>
<p>I do not show the rest of the HTTP methods because they are very similar, POST will do the trick here.</p>
<p>And now this is my <strong>.spec.ts</strong> file:</p>
<pre><code>import { HttpClient } from '@angular/common/http'
import { TestBed } from '@angular/core/testing'
import { of } from 'rxjs'
import { ApiService } from './api.service'

describe('ApiService', () =&gt; {
  let service: ApiService
  let httpClientSpyPost: {
    post: jasmine.Spy
  }

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        ApiService,
        { provide: HttpClient, useValue: httpClientSpyPost }
      ]
    })
    service = TestBed.inject(ApiService)
    httpClientSpyPost = jasmine.createSpyObj('HttpClient', ['post'])
  })

  it('should be created', () =&gt; {
    expect(service).toBeTruthy()
  })

  it('(POST) -&gt; should return a response with a body', (done: DoneFn) =&gt; {
    const body = {}
    const expectedResponse = {}
    httpClientSpyPost.post.and.returnValue(of(expectedResponse))
    service.post('url', body).subscribe((response) =&gt; {
      expect(response).toEqual(expectedResponse)
      done()
    })
  })
})
</code></pre>
<p>And this is the error Jasmine is throwing me:</p>
<pre><code>TypeError: this._http.post is not a function
</code></pre>
<p>I don't really know what it does really mean and I think I've set up everything correct and tried some things I've read here.</p>
",https://stackoverflow.com/questions/75554006/error-this-http-post-is-not-a-function-with-jasmine,"['angular', 'unit-testing', 'testing', 'jasmine']",176,True,0,2
Jest cannot read properties of undefined even though I do define it. It seems to only read strings but not integers,"<p>I am having trouble with unit testing with Jest.<br />
I want to declare a <code>counter</code> property for my instance of scope and assign it the value of 0.</p>
<p>The problem is that it won't even run my expect statements because it's not able to read the properties of undefined.</p>
<pre><code>let scope;
    beforeEach(() =&gt; {
      scope = new Scope();
    });

    ...

test('calls the listener fn when the watch value changes', () =&gt; {
      scope.someValue = 'a';
      scope.counter = 0;

      const listenerFn = scope =&gt; {
        scope.counter++;
      };

      const watchFn = scope =&gt; scope.someValue;

      scope.$watch(watchFn, listenerFn);

      expect(scope.counter).toEqual(0);

      scope.$digest();

      expect(scope.counter).toBe(1);

      scope.$digest();

      expect(scope.counter).toBe(1);

      scope.someValue = 'b';

      expect(scope.counter).toBe(1);
      
      scope.$digest();

      expect(scope.counter).toBe(2);
    });
</code></pre>
<p>This is the error I'm having.</p>
<pre><code>TypeError: Cannot read properties of undefined (reading 'counter')

      36 |       scope.counter = 0;
      37 |       const listenerFn = scope =&gt; {
    &gt; 38 |         scope.counter++;
         |         ^
      39 |       };
      40 |       const watchFn = scope =&gt; scope.someValue;
      41 |       scope.$watch(watchFn, listenerFn);
</code></pre>
<p>I have tried initializing <code>scope.counter = 0</code> in the class constructor.<br />
Also initializing it in the test block.<br />
Jest keeps saying that it cannot read values of undefined. I have tried changing the value to a string but it just won’t read <code>scope.counter</code> as a property of scope.</p>
<p>I was expecting it to read <code>scope.counter</code> like it would read <code>scope.someValue</code></p>
<p>If anyone has any suggestions or can push me in the right direction, please anything to help me get through this.</p>
",https://stackoverflow.com/questions/75306179/jest-cannot-read-properties-of-undefined-even-though-i-do-define-it-it-seems-to,"['javascript', 'unit-testing', 'jestjs']",41,False,0,0
"AppConfiguration, Azure Function and custom type configuration class no refreshing","<p>I've been using customs type configuration classes as Singleton in DI for a long time in AZ Functions and never had the need to reload changes as I do now implementing Azure App Configuration.</p>
<p>But I've been trying to make my custom type class reload/update the settings value from App COnfiguration and it doesn't work, never gets updated as IConfigurate it gets I want my customs tupe class <code>AppConfiguration</code> to be able load the latest changes.
Using IConfiguration such <code>_configuration[&quot;AppConfiguration:Integer&quot;]</code> the changes gets updated but I dont want to move all my code to IConfiguration as I lose the benefit of customs type for unit testing and mocking.</p>
<p>How to combine these 3, using .NET 6: AppConfiguration, Azure Function and custom type configuration?</p>
<p>My code so far.</p>
<pre><code>
namespace AppConfigPOC
{
    public class Function1
    {
        private readonly AppConfiguration _appConfiguration;
        private readonly IFeatureManager _featureManager;
        private readonly IConfiguration _configuration;
        private readonly IConfigurationRefresher _configurationRefresher;
        public Function1(IOptionsSnapshot&lt;AppConfiguration&gt; appConfiguration, IFeatureManager featureManager, IConfiguration configuration, IConfigurationRefresherProvider refresherProvider)
        {
            _appConfiguration = appConfiguration.Value;
            _featureManager = featureManager;
            _configuration = configuration;
            _configurationRefresher = refresherProvider.Refreshers.First();
        }

        [FunctionName(&quot;Function1&quot;)]
        public async Task&lt;IActionResult&gt; Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, &quot;get&quot;, &quot;post&quot;, Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation(&quot;C# HTTP trigger function processed a request.&quot;);

            await _configurationRefresher.TryRefreshAsync();


            var result = new ConfigResult
            {
                Interger = _appConfiguration.Integer.ToString(),  //,
                IntergerIConfg = _configuration[&quot;AppConfiguration:Integer&quot;],
                ListValues = _appConfiguration.ListValues,
                Print = await _featureManager.IsEnabledAsync(nameof(FeatureFlags.Print)),
                UseDB = await _featureManager.IsEnabledAsync(nameof(FeatureFlags.UseDB)),
                Sentinel = _appConfiguration.Sentinel,
                KVReference = _appConfiguration.KvValue
            };

            return new OkObjectResult(result);
        }
    }

    public class AppConfiguration
    {
        public int Integer { get; set; } = 3;

        public string ListValues { get; set; } = &quot;1,3,5&quot;;

        public string Sentinel { get; set; }

        public string KvValue { get; set; }
    }

    public class ConfigResult
    {
        public string Interger { get; set; }
        public string IntergerIConfg { get; set; }

        public string ListValues { get; set; }

        public bool Print { get; set; }

        public bool UseDB { get; set; }

        public string KVReference { get; set; }

        public string Sentinel { get; set; }
    }

    public enum FeatureFlags
    {
        Print,
        UseDB
    }
}

</code></pre>
<p>This is my Startup and DI.</p>
<pre><code>
[assembly: FunctionsStartup(typeof(AppConfigPOC.Startup))]
namespace AppConfigPOC
{
    public class Startup : FunctionsStartup
    {
        private IConfiguration _config;

        private static IConfigurationRefresher _refresher = null;

        public override void Configure(IFunctionsHostBuilder builder)
        {
#if (DEBUG)
            builder.Services.AddLogging((builder) =&gt;
            {
                builder.AddFilter(&quot;Microsoft&quot;, LogLevel.Debug);
            });
#endif
            builder.Services.AddAzureAppConfiguration();

            builder.Services.AddFeatureManagement();


            builder.Services.Configure&lt;AppConfiguration&gt;(_config.GetSection(nameof(AppConfiguration)));
        }

        public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder fnConfigurationBuilder)
        {
            var configBuilder = fnConfigurationBuilder.ConfigurationBuilder;

            var settings = configBuilder.Build();

            configBuilder.AddAzureAppConfiguration(options =&gt;
            {
                options.Connect(settings[&quot;ConnectionStrings:AppConfig&quot;])
                                       .Select(KeyFilter.Any, null)
                                       .Select(&quot;QA&quot;)
                                       .UseFeatureFlags() //default 30seconds
                                       .ConfigureRefresh(refresh =&gt;
                                       {
                                           refresh.Register(&quot;AppConfiguration:Sentinel&quot;, refreshAll: true).SetCacheExpiration(TimeSpan.FromSeconds(5));
                                       }).ConfigureKeyVault(kv =&gt;
                                       {
                                           kv.SetCredential(new DefaultAzureCredential());
                                       });

                _refresher = options.GetRefresher();
            });
            configBuilder.AddEnvironmentVariables();

            configBuilder.AddJsonFile(&quot;appsettings.json&quot;, optional: true, reloadOnChange: true);

            _config = configBuilder.Build();
        }
    }
}

</code></pre>
",https://stackoverflow.com/questions/75520499/appconfiguration-azure-function-and-custom-type-configuration-class-no-refreshi,"['.net', 'azure-functions', 'azure-app-configuration']",115,False,0,0
Is there a way to resolve &#39;cannot find import statement outside a module&#39; in nextjs?,"<p>I am using nextjs and installed jest with Babel to do unit testing.</p>
<p>When I run npm test it gives me below error of 'import'
FAIL  <strong>tests</strong>/pages/index.test.js
● Test suite failed to run</p>
<pre><code>Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default &quot;node_modules&quot; folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your &quot;node_modules&quot; files transformed, you can specify a custom &quot;transformIgnorePatterns&quot; in your config.
 • If you need a custom transformation specify a &quot;transform&quot; option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the &quot;moduleNameMapper&quot; config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

/Users/alex/Desktop/test/tech-blog-web/node_modules/github-slugger/index.js:1
({&quot;Object.&lt;anonymous&gt;&quot;:function(module,exports,require,__dirname,__filename,jest){import { regex } from './regex.js'
                                                                                  ^^^^^^

SyntaxError: Cannot use import statement outside a module

  1 | import React from 'react';
&gt; 2 | import { slug } from &quot;github-slugger&quot;;
    | ^
</code></pre>
<p>Most of my files are .js extension with a few of .jsx extension</p>
<p>I tried adding type:module in my package.json and changing my files name to .mjs but still face this error.</p>
<p>Below is my jest.config.js</p>
<pre><code>      module.exports = {

      collectCoverage: true,
</code></pre>
<p>// on node 14.x coverage provider v8 offers good speed and more or less good report</p>
<pre><code>  coverageProvider: 'v8',

  coverageReporters: ['json', 'html'],

  coverageDirectory: 'coverage',

  collectCoverageFrom: [

'**/*.{js,jsx,ts,tsx}',

'!**/*.d.ts',

'!**/node_modules/**',

'!&lt;rootDir&gt;/out/**',

'!&lt;rootDir&gt;/.next/**',

'!&lt;rootDir&gt;/*.config.js',

'!&lt;rootDir&gt;/coverage/**',
</code></pre>
<p>],</p>
<pre><code>  testEnvironment: &quot;jest-environment-jsdom&quot;,

  moduleNameMapper: {

&quot;\\.(css|less|scss|sass)$&quot;: &quot;identity-obj-proxy&quot;,

// Handle module aliases

'^@layouts/(.*)$': '&lt;rootDir&gt;/layouts/$1',

'^@components/(.*)$': '&lt;rootDir&gt;/layouts/components/$1',

'^@partials/(.*)$': '&lt;rootDir&gt;/layouts/partials/$1',

'^@shortcodes/(.*)$': '&lt;rootDir&gt;/layouts/shortcodes/$1',

'^@config/(.*)$': '&lt;rootDir&gt;/config/$1',

'^@json/(.*)$': '&lt;rootDir&gt;/json/$1',

'^@hooks/(.*)$': '&lt;rootDir&gt;/hooks/$1',

'^@lib/(.*)$': '&lt;rootDir&gt;/lib/$1',
</code></pre>
<p>},</p>
<pre><code>  transform: {

// &quot;^.+\\.jsx?$&quot;: &quot;babel-jest&quot;,

// '^.+\\.jsx?$': 'babel-jest',

// '^.+\\.js?$': 'babel-jest',

// '^.+\\.(js|jsx)$': 'babel-jest',

// '^(github-slugger)$': 'babel-jest',

// &quot;^.+\\.mjs$&quot;: &quot;babel-jest&quot;,

'^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
</code></pre>
<p>},</p>
<pre><code>  moduleFileExtensions: [&quot;js&quot;, &quot;jsx&quot;, &quot;json&quot;, &quot;node&quot;, &quot;md&quot;],

  setupFilesAfterEnv: ['./setupTests.js'],

  testPathIgnorePatterns: [

//'&lt;rootDir&gt;/node_modules/', 

&quot;&lt;rootDir&gt;/node_modules/(?!(github-slugger)/)&quot;,

// '&lt;rootDir&gt;/.next/',

// '&lt;rootDir&gt;/setupTests.js',

  ],

};



.babelrc


  &quot;presets&quot;: [

&quot;@babel/preset-env&quot;,

&quot;@babel/preset-react&quot;

  ]
</code></pre>
<p>Please kindly help me. I'm trying to do this for 3 days and honestly feeling so lost.</p>
<p>I tried adding 'node:module' to my package.json</p>
<p>I tried remaining files from .js to .mjs</p>
<p>I tried changing many times my jest.config.js &amp; .babelrc but to no success</p>
",https://stackoverflow.com/questions/75890959/is-there-a-way-to-resolve-cannot-find-import-statement-outside-a-module-in-nex,"['unit-testing', 'next.js', 'jestjs', 'babeljs', 'es6-modules']",143,False,0,1
Visual Studio | Determine Template Type of an existing Project,"<p>I am trying to rebuild an existing solution from scratch.
I know that the main project is created from a ASP.NET web application template.</p>
<p>But I am stuck when I want to create another project for unit testing as there are a bunch of templates to choose from (MSTest, NUnit, xUnit, etc.)</p>
<p>From the project type GUIDs and this overview of <a href=""https://github.com/JamesW75/visual-studio-project-type-guid"" rel=""nofollow noreferrer"">Visual Studio Project Type Guids</a> I know that the project is of type</p>
<ul>
<li><strong>C#</strong> (GUID: FAE04EC0-301F-11D3-BF4B-00C04F79EFBC) and</li>
<li><strong>Test</strong> (GUID: 3AC096D0-A1C2-E12C-1390-A8335801FDAB)</li>
</ul>
<p>But this information does not help me in choosing the exact same template of the original project.</p>
<p>Is there any way to get information on the very template that was used for the original project?</p>
<p>Any help is much appreciated!</p>
",https://stackoverflow.com/questions/76235532/visual-studio-determine-template-type-of-an-existing-project,"['visual-studio', 'unit-testing', 'project-template']",11,False,0,1
Extracting and testing an express-validator function,"<p>I'd like to test my implementation of <code>express-validator</code> rules in my middleware. I understand that I shouldn't test 3rd party code, but in my (perhaps flawed) view, I'm testing my implementation rather than their code.</p>
<p>A cut down version would usually look like this:</p>
<pre><code>// routes.js
router.post('/example',
[
  body('email')
    .isString()
    .withMessage('Invalid characters, please use letters and numbers only'))
],
//// To be replaced by:
// validateLogin(),
controller.exampleFn());
</code></pre>
<p>but I need to be able to extract it for testing, which I do by <a href=""https://express-validator.github.io/docs/running-imperatively"" rel=""nofollow noreferrer"">running the validations imperatively:</a></p>
<pre><code>// validation.js

// parallel processing
const validate = validations =&gt; {
  return async (req, res, next) =&gt; {
    await Promise.all(validations.map(validation =&gt; validation.run(req)));

    const errors = validationResult(req);
    if (errors.isEmpty()) {
      return next();
    }

    const error = new Error();
    error.message = process.env.NODE_ENV === 'development'? 'Validation Failed':'Error';

    error.statusCode = !errors.isEmpty()? 422:500;
    error.errors = errors.array({onlyFirstError: true});
    next(error);
    return error;
  };
};

const validateLogin = () =&gt; {
  const exampleValidationRules = [
    body('email')
      .isString()
      .withMessage('Invalid characters, please use letters and numbers only')
  ];
  return validation(exampleValidationRules);
}

module.exports = {
  validateLogin
};
</code></pre>
<p>I can then call the middleware in my routes, and in my test files.</p>
<p>For example:</p>
<pre><code>// auth.test.js
describe('Unit Tests', () =&gt; {
  it('should return 422 if email validation fails', async() =&gt; {
    const wrongEmailReq = { body: {email: 'nic@hotmail.com'} };
    const notStringReq = { body: {email:1} };
    const res = {
      statusCode: 500,
      status: (code) =&gt; {this.statusCode = code; return this},
    };

    // Function to be tested  
    const validationFn = validateLogin();

    const wrongEmail = await validationFn(wrongEmailReq, res, ()=&gt;{});
    const notString = await validationFn(notStringReq, res, ()=&gt;{});

    expect(wrongEmail.statusCode).to.be.equal(422);
    expect(wrongEmail.errors[0].param).to.be.equal('email');

    expect(notString.statusCode).to.be.equal(422);
    expect(notString.errors[0].param).to.be.equal('email');

    return;
});
</code></pre>
<p>I'm just slightly confused about how I'd test the 'success' case. <code>validationFn</code> returns <code>next()</code> if successful. But that would just be <code>undefined</code>.</p>
<p>Should I just test <code>expect(correct.statusCode).to.be.undefined;</code>? That doesn't seem specific enough.</p>
<p>Also, is there actually any advantage to unit testing this function over using <code>http-chai</code> to run the requests? I thought perhaps it was more lightweight, but unsure.</p>
",https://stackoverflow.com/questions/75234318/extracting-and-testing-an-express-validator-function,"['javascript', 'node.js', 'express', 'mocha.js']",33,False,0,0
Swift: Testing async functions nested in timers?,"<p>I'm new to swift, and facing an issue with testing asynchronous swift code nested within a timer.</p>
<p>I have a swift <code>.scheduledTimer</code> that sends data to an API every 5 minutes in swift via <code>URLSession.shared.upload</code></p>
<p>In order for the asynchronous call to work within .scheduledTimer I've wrapped it in <code>Task</code> , like so:</p>
<pre><code>self.timerProvider.scheduledTimer(withTimeInterval: timeBetweenAPISendsInSeconds, repeats: true) { _ in
    Task {
        await URLSession.shared.upload(for: request, from: encodedSessionBatch)
    }
}
</code></pre>
<p>The problem I have is with unit testing. Specifically:</p>
<pre><code>func test_scheduledTimer_sendsSessionBatchToAPI() async throws {
    MockTimer.currentTimer.fire()
    XCTAssertEqual(mockApiDispatcher.sentToAPICount, 1)
}
</code></pre>
<p>That &quot;sentToAPICount&quot; won't get picked up, because the test fires before the async operation completes. This normally isn't a problem with async tests, I either:</p>
<ul>
<li>Stick 'async/await' in the test function. Can't do that in this instance(?), because the async call is nested within a timer</li>
<li>Use expectation.fulfill()...which I'm guessing requires a callback to use effectively, which this code doesn't have?</li>
</ul>
<p>As mentioned, I'm relatively new to swift, and eager for ideas: what's the standard way of asynchronous tests nested in timers?</p>
",https://stackoverflow.com/questions/75089745/swift-testing-async-functions-nested-in-timers,"['swift', 'unit-testing', 'asynchronous']",105,False,4,1
How to declare a sequence in DBUnit XML - in core Java,"<p>I need help to solve a unit testing problem using DBUnit. In my code I call nextvalue of the sequence.</p>
<p>This is failing as expected as my xml is not correct.</p>
<p>I have a schema /dtd as expected with table elements. and the  in xml works ok.</p>
<p>But I want test my sequence also. some article are giving answers on how to reset
<a href=""https://stackoverflow.com/questions/20607704/reset-sequence-in-dbunit"">Reset sequence in DBUnit?</a></p>
<pre><code> &lt;?xml version='1.0' encoding='UTF-8'?&gt;
    &lt;dataset reset_sequences=&quot;emp_seq, dept_seq&quot;&gt;
        &lt;emp empno=&quot;1&quot; ename=&quot;Scott&quot; deptno=&quot;10&quot; job=&quot;project manager&quot; /&gt;
        ....
    &lt;/dataset&gt;
</code></pre>
<p>But my insert happens via code, and the dataset or other element should help me get next value (i.e. the sequence should exist)</p>
<p>How can I declare/define a sequence wither in DTD or dataset XML</p>
<p>I could not find an answer. So please dont brand me lazy. I use only XML in this scenario . Please help</p>
<p><a href=""https://stackoverflow.com/questions/16697740/how-to-use-oracle-sequence-numbers-in-dbunit"">How to use Oracle Sequence Numbers in DBUnit?</a></p>
<p><a href=""https://github.com/springtestdbunit/spring-test-dbunit/pull/30"" rel=""nofollow noreferrer"">https://github.com/springtestdbunit/spring-test-dbunit/pull/30</a></p>
",https://stackoverflow.com/questions/75340009/how-to-declare-a-sequence-in-dbunit-xml-in-core-java,"['java', 'dbunit']",50,False,1,0
How to create a custom task only for unit testing?,"<p>Currently, unit tests in c# needs a lot of shell parameters: <a href=""https://stackoverflow.com/questions/76258066/how-to-simplify-the-unit-tests-execution-in-c-sharp-when-shell-is-used-instead-v"">How to simplify the unit tests execution in c# when shell is used instead Visual Studio?</a></p>
<p>That's why I'm trying to create a custom task to be able to run the tests and code coverage with <strong>one line</strong> and also keep it cross-platform for windows developers.</p>
<p>I tried something like <code>dotnet foo</code> but I could not find any official or workaround.</p>
<h1>dotnet + msbuild</h1>
<p>The following task works</p>
<pre><code>&lt;Target Name=&quot;Foo&quot;&gt;
  &lt;Message Text=&quot;This is a Foo task&quot; /&gt;
&lt;/Target&gt;

dotnet msbuild -target:Foo
</code></pre>
<p>But the problem is: This command loads the main <strong>./src/Main.csproj</strong>, not the <strong>./test/Test.csproj</strong> of tests, so the custom task (for unit test) should be in the <strong>Main.csproj</strong>, which doesn't make sense</p>
<pre><code>./src
./src/Controllers
./src/Controllers/**
./src/Main.csproj
./src/Startup.cs
./test
./test/Controllers
./test/Controllers/**
./test/Test.csproj
</code></pre>
<p>I tried to pass the relative location of <strong>./test/Test.csproj</strong> with</p>
<ul>
<li><code>--project</code> without success</li>
</ul>
<p>But another error is raised: <code>error MSB1001: Unknown switch.</code></p>
<p>So my question is:</p>
<blockquote>
<p>How to create a custom task only for unit testing?</p>
</blockquote>
",https://stackoverflow.com/questions/76258850/how-to-create-a-custom-task-only-for-unit-testing,"['c#', 'unit-testing', '.net-core', 'msbuild']",28,True,0,1
Replacing functions during testing,"<p>I'm trying to write test functions for a project I'm working on. I using oracle as my database in the project and in the testing I'm using the in memory sqlite3 my problem is that some queries syntax are different. This isn't a problem when I'm unit testing because I can pass queries as parameters and adapt them but when I try to test the do() function responsible for calling all the functions this becomes undoable.</p>
<p>Here an example of my class:</p>
<pre><code>def my_class:
 def get_insert_query(self):
    return &quot;insert .... where my_date &gt; sysdate&quot;
 def insert(self,query):
     ...
 def get_update_query(self):
    return &quot;update .... where my_date &gt; sysdate&quot;
 def update(self,query):
     ...
 def do(self):
     query = self.get_insert_query()
     self.insert(query)
     query = self.get_update_query()
     self.update()
</code></pre>
<p>I want to test do() function. I found out that's it possible to replace a function using the patch from unittest.mock to replace get_insert_query with a function that return a query adapted to sqlite3 but my problem with it that it doesn't the same order of execution and doesn't enable me to execute the rest of the function.</p>
",https://stackoverflow.com/questions/76331134/replacing-functions-during-testing,"['python', 'oracle', 'sqlite', 'python-unittest', 'python-unittest.mock']",29,False,0,0
Expecting error with axios-mock-adapter only works inside a try-catch block or when only one test is run,"<p>I'm mocking an axios instance using axios-mock-adapter for unit testing a service that connects to an API.</p>
<h2>api.ts</h2>
<pre class=""lang-js prettyprint-override""><code>export const api = axios.create({
  baseURL: `${process.env.PUBLIC_URL}/api`,
});
</code></pre>
<h2>answers.service.test.ts</h2>
<pre class=""lang-js prettyprint-override""><code>import { api } from &quot;../services/api&quot;;
import MockAdapter from &quot;axios-mock-adapter&quot;;

describe(&quot;AnswersService&quot;, () =&gt; {
  let mockAxios = new MockAdapter(api);

  afterEach(() =&gt; {
    mockAxios.reset();
  });
</code></pre>
<p>Testing using practices recommended in the Jest documentation result in strange behaviour and failing tests.</p>
<p>There is something strange afoot:</p>
<ul>
<li>If I setup my test like this, it runs without trouble. However, if I remove the extra validations it shows that the api instance has not been called even once. Moreover, the test also fails if I run it with others, showing that <code>Received promise resolved instead of rejected</code>.</li>
</ul>
<pre class=""lang-js prettyprint-override""><code>it(&quot;Should throw error when creating answer with invalid question ID&quot;, async () =&gt; {
    const answer = &quot;answer&quot;;
    const idQuestion = -1;
    let spy = jest.spyOn(api, &quot;post&quot;);

    mockAxios.onPost(`/answers/${idQuestion}`).reply(404);

    await expect(createAnswer(answer, idQuestion)).rejects.toThrow(NotFoundError);

    // expect(spy).toHaveBeenCalledWith(`/answers/${idQuestion}`, {
    //   body: answer,
    // });
    //expect(spy).toHaveBeenCalledTimes(1);
  });
</code></pre>
<ul>
<li>If I modify the test so it uses a try-catch block, the test actually runs without issues but I get the warning that I shouldn't be calling expect conditionally.</li>
</ul>
<pre class=""lang-js prettyprint-override""><code>it(&quot;Should throw error when creating answer with invalid question ID&quot;, async () =&gt; {
    const answer = &quot;answer&quot;;
    const idQuestion = -1;

    mockAxios.onPost(`/answers/${idQuestion}`).reply(404);

    try {
      await createAnswer(answer, idQuestion);
    }
    catch (e) {
      expect(e).toBeInstanceOf(NotFoundError);
    }

    expect(jest.spyOn(api, &quot;post&quot;)).toHaveBeenCalledWith(`/answers/${idQuestion}`, {
      body: answer,
    });
    expect(jest.spyOn(api, &quot;post&quot;)).toHaveBeenCalledTimes(1);
  });
</code></pre>
<p>What could be going on? I don't understand what's going on. The first option seems to be the better one, but it just won't work.</p>
",https://stackoverflow.com/questions/75450055/expecting-error-with-axios-mock-adapter-only-works-inside-a-try-catch-block-or-w,"['typescript', 'axios', 'jestjs', 'axios-mock-adapter']",157,False,0,0
"How to test a post request which returns a URI with spring boot, junit 5 and mockito","<p>I'm creating a REST API in spring boot where I have a <code>post</code> request end point. If it succeeds it returns the URI of the newly created resource in the <code>location header</code>.</p>
<p>I wanted to write tests for the endpoint. I'm using JUnit v5, and Mockito.
The problem is I have mocked the call to the service function but it still returns a <code>NullPointerException</code></p>
<p>In the controller class, in the post end point I have this function:</p>
<pre><code>@PostMapping(value = &quot;/new&quot;)
    public ResponseEntity&lt;String&gt; registerNewDoctor(@RequestBody @Valid DoctorPOJO doctor) {
        Doctor savedDoctor = doctorService.addNewDoctor(doctor);
        if (doctor != null) {
            log.debug(&quot;DOCTOR SAVED: {}&quot;,savedDoctor);
            URI location = ServletUriComponentsBuilder.fromCurrentContextPath().path(&quot;/id/{id}&quot;).buildAndExpand(savedDoctor.getDocId()).toUri();
            return ResponseEntity.created(location).build();
        } else {
            return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(&quot;Object can not be processed&quot;);
        }
    }
</code></pre>
<p>In the unit Test I have:</p>
<pre><code>@WebMvcTest
@Slf4j
class DoctorControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private DoctorService doctorService;
@MockBean
private SlotService slotService;
@Test
void registerNewDoctorTest() throws Exception {
        // given - set up
        SlotPOJO slot1 = new SlotPOJO(&quot;monday&quot;, LocalTime.parse(&quot;09:00:00.00&quot;), LocalTime.parse(&quot;13:00:00.00&quot;), LocalTime.parse(&quot;00:15:00.00&quot;));
        SlotPOJO slot2 = new SlotPOJO(&quot;tuesday&quot;, LocalTime.parse(&quot;09:00:00.00&quot;), LocalTime.parse(&quot;13:00:00.00&quot;), LocalTime.parse(&quot;00:15:00.00&quot;));
        List&lt;SlotPOJO&gt; slotPOJOList = new ArrayList&lt;&gt;(Arrays.asList(slot1, slot2));
        DoctorPOJO doctorPOJO = new DoctorPOJO(1, &quot;doctor1&quot;, &quot;doc1email@gmail.com&quot;, &quot;1234567890&quot;, &quot;123&quot;, &quot;MBBS&quot;, &quot;Orthopedics&quot;, &quot;4y&quot;, slotPOJOList);
        Doctor doc = new Doctor(1, &quot;doctor1&quot;, &quot;doc1email@gmail.com&quot;, &quot;1234567890&quot;, &quot;123&quot;, &quot;MBBS&quot;, &quot;Orthopedics&quot;, &quot;4y&quot;);

       // mocking the service method 
        given(doctorService.addNewDoctor(doctorPOJO)).willReturn(doc);

        // when - perform actions to be tested
        ResultActions response = mockMvc.perform(post(&quot;/doctor/new&quot;).contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(doctorPOJO)).accept(MediaType.APPLICATION_JSON));

        // then - verify the results
        response.andDo(print()).andExpect(status().isCreated());
    }
}
</code></pre>
<p>As you can see I have mocked the <code>addNewDoctor</code> method using mockito to return <code>doc</code> when called but I still get this error:</p>
<blockquote>
<p>Request processing failed; nested exception is
java.lang.NullPointerException: Cannot invoke
&quot;project.doctorservice.entity.Doctor.getDocId()&quot; because &quot;savedDoctor&quot;
is null</p>
</blockquote>
<p>Please help me sort out this mistake and guide me a little to how to do it correctly because I'm new to unit testing</p>
",https://stackoverflow.com/questions/75486901/how-to-test-a-post-request-which-returns-a-uri-with-spring-boot-junit-5-and-moc,"['java', 'spring-boot', 'unit-testing', 'junit', 'mockito']",296,False,0,0
mocking functions in react with jest not working on all,"<p>I am using jest to do unit testing. I have a Login screen that calls a login function that is in a service. I can mock the login function using</p>
<pre><code>     jest.spyOn(AuthenticationService, 'login').mockImplementation(async (username, password) =&gt; { console.log('mock login called', username, password); return Promise.resolve(true)});
</code></pre>
<p>and that intercepts the login function and works as intended.
The problem is that I actually want to intercept the authenticate inside the same service as login function that login calls.
when I change 'login' to 'authenticate' it does nothing. all the functions just get triggered as normal and nothing is mocked</p>
<p>I have also tried mocking with the following with no luck</p>
<pre><code> jest.mock('../../auth/authentication.service', () =&gt; ({
     ...jest.requireActual('../../auth/authentication.service'),
     authenticate: jest.fn((username, password) =&gt; {
         console.log('mock login called', username, password);
         //return Promise.resolve(true);
     })
 }));
</code></pre>
<p>I have a feeling it is to do with the fact the login page is calling login but is never actually calling authenticate from itself but not sure if that makes a difference.</p>
<p>authenticate and login are both exported correctly from the service so both should be available to mock</p>
",https://stackoverflow.com/questions/75914592/mocking-functions-in-react-with-jest-not-working-on-all,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",25,False,0,0
ViewModel with Mock don&#39;t get array of objects in Unit Testing,"<p>I have a project for practicing Unit testing with Swift, normally the project work in the simulator, in the view is the data from a external api and it's functional.</p>
<p>When I try to make the Unit Testing with a mock for get fake data from a Bundle, the test indicates the object with the data in published var is empty, but in the completion block in the result this data is ok.</p>
<p>ViewModel:</p>
<pre><code>final class UserViewModel: ObservableObject {
    @Published var users : [UserModel] = []
    @Published var messageError: String?
    @Published var alertError: Bool = false
    
    private let userRepository: UserRepo
    
    init(userRepository: UserRepo = UserRepository()){
        self.userRepository = userRepository
    }
    
    func getUsers(){
        userRepository.sendRequest(.getUsers, [UserModel].self) {[weak self] result in
            DispatchQueue.main.async {
                switch result {
                case .success(let users):
                    self?.users = users
                case .failure(let error):
                    self?.messageError = error.errorDescription
                    self?.alertError = true
                }
            }
        }
    }
}
</code></pre>
<p>Repository:</p>
<pre><code>protocol UserRepo {
    func sendRequest&lt;T: Decodable&gt;(_ route: APIAssembleRequest, _ type: T.Type, _ params: Any?..., completionBlock: @escaping (Result&lt;T, NetworkError&gt;) -&gt; Void)
}

final class UserRepository: UserRepo {
    
    private let userDatasource: UserData
    
    init (userDatasource: UserData = UserDatasource()){
        self.userDatasource = userDatasource
    }
    
    func sendRequest&lt;T: Decodable&gt;(_ route: APIAssembleRequest, _ type: T.Type, _ params: Any?..., completionBlock: @escaping (Result&lt;T, NetworkError&gt;) -&gt; Void){
        userDatasource.sendRequest(route, type, params, completionBlock: completionBlock)
    }
}
</code></pre>
<p>Datasource:</p>
<pre><code>protocol UserData {
    func sendRequest&lt;T: Decodable&gt;(_ route: APIAssembleRequest, _ type: T.Type, _ params: Any?..., completionBlock: @escaping HandlerUser&lt;T&gt;)
}

final class UserDatasource: UserData, RequestGenerator, RequestHandler, ResponseHandler {
    
    func sendRequest&lt;T: Decodable&gt;(_ route: APIAssembleRequest, _ type: T.Type, _ params: Any?..., completionBlock: @escaping HandlerUser&lt;T&gt;){
        
        let request = self.generateRequest(route: route, params: params)
        _ = self.send(request: request) { response in
            self.handleResponse(response, type, completionBlock: completionBlock)
        }
    }    
}
</code></pre>
<p>UserModel:</p>
<pre><code>struct UserModel: Decodable, Encodable, Equatable {
    var id: Int
    var name: String?
    var email: String?
    var genre: String?
    var status: String?
    
    enum CodingKeys: String, CodingKey {
        case id
        case name
        case email
        case genre = &quot;gender&quot;
        case status
    }
    
    init(from decoder: Decoder) throws{
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.id = try container.decode(Int.self, forKey: .id)
        self.name = try container.decode(String.self, forKey: .name)
        self.email = try container.decode(String.self, forKey: .email)
        self.genre = try container.decode(String.self, forKey: .genre)
        self.status = try container.decode(String.self, forKey: .status)
    }
}
</code></pre>
<p>For that code is working fine</p>
<p>Now the mock</p>
<pre><code>import Foundation
@testable import UsersMVVMURLSessionAndGenericsEnvironmentObject


final class MockUser: UserRepo {
    
    func sendRequest&lt;T&gt;(_ route: UsersMVVMURLSessionAndGenericsEnvironmentObject.APIAssembleRequest, _ type: T.Type, _ params: Any?..., completionBlock: @escaping (Result&lt;T, UsersMVVMURLSessionAndGenericsEnvironmentObject.NetworkError&gt;) -&gt; Void) where T : Decodable {
        completionBlock(.success(decodeData(route: route)))
    }
    
    func decodeData&lt;T:Decodable&gt;(route: APIAssembleRequest) -&gt; T{
        let bundlePath = Bundle.main.path(forResource: &quot;Stub&quot;, ofType: &quot;bundle&quot;)
        let bundle = Bundle(path: bundlePath!)
        switch route {
        case .getUsers:
            return bundle!.decode([UserModel].self, from: &quot;Users.json&quot;) as! T
        default:
            return bundle!.decode(UserModel.self, from: &quot;Users.json&quot;) as! T
        }
        
    }
}
</code></pre>
<p>Bundle extension for decode fake data and function for decode data and compare</p>
<pre><code>import Foundation
@testable import UsersMVVMURLSessionAndGenericsEnvironmentObject

extension Bundle {
    
    func decode&lt;T: Decodable&gt;(_ type: T.Type, from file: String, dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate, keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) -&gt; T {
        guard let url = self.url(forResource: file, withExtension: nil) else {
            fatalError(&quot;Failed to locate \(file) in bundle.&quot;)
        }

        guard let data = try? Data(contentsOf: url) else {
            fatalError(&quot;Failed to load \(file) from bundle.&quot;)
        }

        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = dateDecodingStrategy
        decoder.keyDecodingStrategy = keyDecodingStrategy

        do {
            return try decoder.decode(T.self, from: data)
        } catch DecodingError.keyNotFound(let key, let context) {
            fatalError(&quot;Failed to decode \(file) from bundle due to missing key '\(key.stringValue)' not found – \(context.debugDescription)&quot;)
        } catch DecodingError.typeMismatch(_, let context) {
            fatalError(&quot;Failed to decode \(file) from bundle due to type mismatch – \(context.debugDescription)&quot;)
        } catch DecodingError.valueNotFound(let type, let context) {
            fatalError(&quot;Failed to decode \(file) from bundle due to missing \(type) value – \(context.debugDescription)&quot;)
        } catch DecodingError.dataCorrupted(_) {
            fatalError(&quot;Failed to decode \(file) from bundle because it appears to be invalid JSON&quot;)
        } catch {
            fatalError(&quot;Failed to decode \(file) from bundle: \(error.localizedDescription)&quot;)
        }
    }
}


extension Bundle {
    static func getUsersJson() -&gt; [UserModel] {
        let bundlePath = Bundle.main.path(forResource: &quot;Stub&quot;, ofType: &quot;bundle&quot;)
        let bundle = Bundle(path: bundlePath!)
        
        return bundle!.decode([UserModel].self, from: &quot;Users.json&quot;)
    }
}
</code></pre>
<p>Users.json</p>
<pre><code>[
    {
        &quot;id&quot;: 204656,
        &quot;name&quot;: &quot;Kalyani Acharya&quot;,
        &quot;email&quot;: &quot;acharya_kalyani@becker-white.co&quot;,
        &quot;gender&quot;: &quot;female&quot;,
        &quot;status&quot;: &quot;active&quot;
    },
    {
        &quot;id&quot;: 204655,
        &quot;name&quot;: &quot;Divjot Reddy&quot;,
        &quot;email&quot;: &quot;reddy_divjot@bergnaum.info&quot;,
        &quot;gender&quot;: &quot;female&quot;,
        &quot;status&quot;: &quot;inactive&quot;
    },
    {
        &quot;id&quot;: 204581,
        &quot;name&quot;: &quot;Baidehi Kapoor&quot;,
        &quot;email&quot;: &quot;baidehi_kapoor@cruickshank.name&quot;,
        &quot;gender&quot;: &quot;male&quot;,
        &quot;status&quot;: &quot;inactive&quot;
    },
    {
        &quot;id&quot;: 204503,
        &quot;name&quot;: &quot;Chapal Varman&quot;,
        &quot;email&quot;: &quot;varman_chapal@rippin.com&quot;,
        &quot;gender&quot;: &quot;female&quot;,
        &quot;status&quot;: &quot;inactive&quot;
    },
    {
        &quot;id&quot;: 204424,
        &quot;name&quot;: &quot;Navin Verma&quot;,
        &quot;email&quot;: &quot;navin_verma@bosco-leffler.co&quot;,
        &quot;gender&quot;: &quot;male&quot;,
        &quot;status&quot;: &quot;inactive&quot;
    },
    {
        &quot;id&quot;: 204423,
        &quot;name&quot;: &quot;Gajadhar Nayar&quot;,
        &quot;email&quot;: &quot;nayar_gajadhar@jacobi.org&quot;,
        &quot;gender&quot;: &quot;female&quot;,
        &quot;status&quot;: &quot;inactive&quot;
    },
    {
        &quot;id&quot;: 204421,
        &quot;name&quot;: &quot;Aditeya Nayar&quot;,
        &quot;email&quot;: &quot;aditeya_nayar@paucek.org&quot;,
        &quot;gender&quot;: &quot;female&quot;,
        &quot;status&quot;: &quot;inactive&quot;
    },
    {
        &quot;id&quot;: 204420,
        &quot;name&quot;: &quot;Gajabahu Khan&quot;,
        &quot;email&quot;: &quot;khan_gajabahu@friesen.io&quot;,
        &quot;gender&quot;: &quot;female&quot;,
        &quot;status&quot;: &quot;active&quot;
    },
    {
        &quot;id&quot;: 204419,
        &quot;name&quot;: &quot;Javas Khatri&quot;,
        &quot;email&quot;: &quot;khatri_javas@purdy-klocko.biz&quot;,
        &quot;gender&quot;: &quot;female&quot;,
        &quot;status&quot;: &quot;active&quot;
    },
    {
        &quot;id&quot;: 204329,
        &quot;name&quot;: &quot;Chandramohan Chaturvedi&quot;,
        &quot;email&quot;: &quot;chandramohan_chaturvedi@turcotte.com&quot;,
        &quot;gender&quot;: &quot;male&quot;,
        &quot;status&quot;: &quot;inactive&quot;
    }
]
</code></pre>
<p>And the testable class with function for compare the results with fake data</p>
<pre><code>import XCTest
@testable import UsersMVVMURLSessionAndGenericsEnvironmentObject

final class UsersMVVMURLSessionAndGenericsEnvironmentObjectTests: XCTestCase {
    
    var mockUserViewModel: UserViewModel!
    
    override func setUpWithError() throws{
        mockUserViewModel = UserViewModel(userRepository: MockUser())
        
    }
    
    func test_GetUsers(){
        mockUserViewModel.getUsers()
        XCTAssertEqual(mockUserViewModel.users, Bundle.getUsersJson())
    }
    
    override func tearDownWithError() throws {
        mockUserViewModel = nil
    }
}
</code></pre>
<p>This is the result of the test</p>
<blockquote>
<p>test_GetUsers(): XCTAssertEqual failed: (&quot;[]&quot;) is not equal to (&quot;[UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204656, name: Optional(&quot;Kalyani Acharya&quot;), email: Optional(&quot;acharya_kalyani@becker-white.co&quot;), genre: Optional(&quot;female&quot;), status: Optional(&quot;active&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204655, name: Optional(&quot;Divjot Reddy&quot;), email: Optional(&quot;reddy_divjot@bergnaum.info&quot;), genre: Optional(&quot;female&quot;), status: Optional(&quot;inactive&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204581, name: Optional(&quot;Baidehi Kapoor&quot;), email: Optional(&quot;baidehi_kapoor@cruickshank.name&quot;), genre: Optional(&quot;male&quot;), status: Optional(&quot;inactive&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204503, name: Optional(&quot;Chapal Varman&quot;), email: Optional(&quot;varman_chapal@rippin.com&quot;), genre: Optional(&quot;female&quot;), status: Optional(&quot;inactive&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204424, name: Optional(&quot;Navin Verma&quot;), email: Optional(&quot;navin_verma@bosco-leffler.co&quot;), genre: Optional(&quot;male&quot;), status: Optional(&quot;inactive&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204423, name: Optional(&quot;Gajadhar Nayar&quot;), email: Optional(&quot;nayar_gajadhar@jacobi.org&quot;), genre: Optional(&quot;female&quot;), status: Optional(&quot;inactive&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204421, name: Optional(&quot;Aditeya Nayar&quot;), email: Optional(&quot;aditeya_nayar@paucek.org&quot;), genre: Optional(&quot;female&quot;), status: Optional(&quot;inactive&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204420, name: Optional(&quot;Gajabahu Khan&quot;), email: Optional(&quot;khan_gajabahu@friesen.io&quot;), genre: Optional(&quot;female&quot;), status: Optional(&quot;active&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204419, name: Optional(&quot;Javas Khatri&quot;), email: Optional(&quot;khatri_javas@purdy-klocko.biz&quot;), genre: Optional(&quot;female&quot;), status: Optional(&quot;active&quot;)), UsersMVVMURLSessionAndGenericsEnvironmentObject.UserModel(id: 204329, name: Optional(&quot;Chandramohan Chaturvedi&quot;), email: Optional(&quot;chandramohan_chaturvedi@turcotte.com&quot;), genre: Optional(&quot;male&quot;), status:Optional(&quot;inactive&quot;))]&quot;)</p>
</blockquote>
<p>Thanks for your answers</p>
<p>I try debugging test but the result for completion block is good, only when the test finish is the message with the error</p>
",https://stackoverflow.com/questions/75317626/viewmodel-with-mock-dont-get-array-of-objects-in-unit-testing,"['arrays', 'swift', 'unit-testing', 'mvvm', 'viewmodel']",59,False,0,0
Unit testing of destructive functions in lisp,"<p>The background here is that I have a non-destructive version of a function that I want to make destructive for performance reasons. However, writing unit tests gets challenging because lisp considers all quoted lists in the source code to be constants and changing those leads to undefined behaviour.</p>
<p>I'm using parachute as the unit testing framework</p>
<p>e.g.,</p>
<pre><code>(define-test suite-1
 (let ((start '((1 2) (3 4) (5 6)))
       (end '((7 1 2) (3 4) (5 6))))
  (is #'equal end (push 7 (car start))))
 (let ((start '((1 2) (3 4) (5 6)))
       (end '((8 1 2) (3 4) (5 6))))
  (is #'equal end (push 8 (car start)))))
</code></pre>
<p>This kinda fails because we end up pushing <code>8</code> onto the constant list <code>(1 2)</code> which eventually causes <code>(push 8 (car start))</code> to result in <code>(8 7 1 2)</code> instead of the expected <code>(8 1 2)</code></p>
<p>This isn't a problem with testing non-destructive functions because they don't modify constants. This is also not a problem outside of unit tests because I know that the original structure will no longer be needed.</p>
<p>I could replace the above with this ugly thing :-</p>
<pre><code>(let ((start (list (list 1 2) (list 3 4) (list 5 6))) ...
</code></pre>
<p>which then creates a proper non-constant list but it sure does make the code unreadable...</p>
<p>Any suggestions on how other people approach this?</p>
",https://stackoverflow.com/questions/75251279/unit-testing-of-destructive-functions-in-lisp,"['unit-testing', 'common-lisp', 'destructive-function', 'parachute']",111,True,2,2
How can I use `select.select()` with `readline()`?,"<p>Sample code:</p>
<pre><code>import os
import select

r, w = os.pipe()
rf = open(r, &quot;rb&quot;)
wf = open(w, &quot;wb&quot;)
wf.write(b&quot;abc\n&quot;)
wf.write(b&quot;def\n&quot;)
wf.flush()
for ii in range(2):
    select.select([rf], [], [])
    print(rf.readline())
</code></pre>
<p>This only prints out the first line, not the second line that is written to the pipe; it hangs before that is written out.</p>
<p>I assume that what is going on is that <code>readline()</code> reads a chunk of text and looks for a newline; because there is now nothing actually buffered in the pipe, <code>select()</code> doesn't return.</p>
<p>What's the best way around this?  I can't just call <code>realine()</code> repeatedly because that call will block when it finds there is no data waiting, which defeats the point of using select.</p>
<p>Ideally the solution would work for both sockets and pipes (because I'm writing socket code and then mocking the sockets with pipes for unit testing).</p>
<p>I've tried implementing <code>readline()</code> myself, reading one character at a time and looking for the newline, to try to leave something in the OS buffer but that seems to suffer from the same problem.</p>
",https://stackoverflow.com/questions/76112754/how-can-i-use-select-select-with-readline,"['python', 'python-3.x', 'select']",35,False,1,0
Error in copying artifact between pipelines,"<p>I am playing around with Jenkins with some sample codes I found and I'm having problems in artifact copying (I think). So I'm running Jenkins in a Docker on my Windows 11 machine. In Jenkins, there's a simple flow of pipelines (<code>build_pipeline</code>, <code>test_pipeline</code> &amp; <code>deploy_pipeline</code>) which all of this will run in sequence. So <code>build_pipeline</code> just fetches the codes from GitHub and builds it, then <code>test_pipeline</code> will do some basic unit testing, and finally <code>deploy_pipeline</code> will deploy the new updated code. I'm having an error during the <code>deploy_pipeline</code> phase:</p>
<p>This is my <code>build_pipeline</code> script:</p>
<pre><code>pipeline {
    agent {
        docker {
            image 'python:2-alpine'
        }
    }
    stages {
        stage('Build') {
            steps {
                sh 'python -m py_compile sources/add2vals.py sources/calc.py'
                stash(name: 'compiled-results', includes: 'sources/*.py*')
                archiveArtifacts artifacts: 'sources/*.py*', fingerprint: true
            }
        }
    }
}
</code></pre>
<p>And this is the deploy_pipeline script:</p>
<pre><code>pipeline {
    agent any
    environment {
        VOLUME = '$(pwd)/sources:/src'
        IMAGE = 'cdrx/pyinstaller-linux:python2'
    }
    stages {
        stage('Deliver') {
            steps {
                // Copy the artifacts from the Build pipeline
                copyArtifacts projectName: 'build_pipeline', filter: 'compiled-results', selector: specific('lastSuccessful')

                // Unstash the 'compiled-results' stash
                unstash name: 'compiled-results'

                dir(path: env.BUILD_ID) {
                    sh &quot;docker run --rm -v ${VOLUME} ${IMAGE} 'pyinstaller -F add2vals.py'&quot;
                }
            }
            post {
                success {
                    archiveArtifacts &quot;${env.BUILD_ID}/sources/dist/add2vals&quot;
                    sh &quot;docker run --rm -v ${VOLUME} ${IMAGE} 'rm -rf build dist'&quot;
                }
            }
        }
    }
}

</code></pre>
<p>During the <code>deploy_pipeline</code> phase, this error will occur:</p>
<pre><code>[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/deploy_pipeline
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Deliver)
[Pipeline] copyArtifacts
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: Unable to find a build for artifact copy from: build_pipeline
Finished: FAILURE
</code></pre>
<p>I already ticked the &quot;Allow to copy artifacts&quot; in the configuration for <code>build_pipeline</code> so I'm not sure what else is wrong here. No problem with <code>test_pipeline</code>. Just <code>deploy_pipeline</code> since it needs to reuse the stash saved in the <code>build_pipeline</code>, but for some reason it cannot find the stash. Any guidance/help is greatly appreciated.</p>
",https://stackoverflow.com/questions/76259008/error-in-copying-artifact-between-pipelines,"['jenkins', 'jenkins-pipeline']",30,False,0,0
Unable to import numbered Streamlit pages as modules,"<p>I've a multi-page Streamlit application in the following structure:</p>
<pre><code>src\project
  | Home.py
  | pages\
      | 1_abc.py
      | 2_def.py
      | 3_ghi.py
tests
  | test_app.py
</code></pre>
<p>Streamlit is able to launch and load these pages correctly. However, I'm having issues trying to import these pages as modules for unit testing:</p>
<pre class=""lang-py prettyprint-override""><code># test_app.py
from project.Home import HomeClass
from project.pages.1_abc import ABCClass
from project.pages.2_def import DEFClass
from project.pages.3_ghi import GHIClass

# ...
</code></pre>
<p>The above returns <code>SyntaxError: invalid decimal literal</code></p>
<p>I figured out that <code>1_abc</code> etc. is an invalid name format for modules as module names cannot start with a number, but that number is used by Streamlit to control the ordering of pages in the sidebar. It seems to me that importing a file as a module is mutually exclusive with loading the file as a Streamlit page in a controlled sequence.</p>
<p>Is there any way to reconcile the 2 requirements? For example, can I define the page order elsewhere, for example in a configuration file for Streamlit to reference? Or can I define the module name elsewhere for Python to use as an alternative to filename?</p>
",https://stackoverflow.com/questions/75741385/unable-to-import-numbered-streamlit-pages-as-modules,"['python', 'python-import', 'streamlit']",90,False,0,2
"pytest unittest, how to group test cases?","<p>I am new to unit testing and trying to implement some in my latest project. However, I can't seem to get the structure quite right.
In the following example I have a bunch of redundant code and it still isn't working, with the @pytest.mark.parametrize</p>
<p>What I would like ideally is for my test_select_childnode to be run with various different games, but for each game I need to create a node and mcts object, which I then pass to the test along with an integer. I think I need parametrize in order to achieve this but it doesn't seem to be working in this example. The example was working when I directly fed the fixtures into the test_select_childnode, but then I would need to repeat that function for each game along with repeating the fixtures which seems like a lot of boilerplate I'm sure could be done smarter.</p>
<pre><code>@pytest.fixture
def node_ttt():
    g = TicTacToeGame()
    node = Node(g)
    return node

@pytest.fixture
def mcts_ttt():
    g = TicTacToeGame()
    nnet = TicTacToeNNet(g,nn_args)
    model = NNetWrapper(g,nnet,nn_args)
    mcts_instance = MCTS(model, mcts_args)
    return mcts_instance


@pytest.mark.parametrize(&quot;mcts, node, action_idx&quot;, [
    (mcts_ttt, node_ttt, 0),
])


def test_select_childnode(mcts, node, action_idx):
    &quot;&quot;&quot;
    Assert that childnode is creating a new node when needed.
    Assert that childnode is not creating a new node when not needed.
    &quot;&quot;&quot;
    mcts.nodes[node.id] = node
    child_node = mcts.select_childnode(node, action_idx)
    child_node2 = mcts.select_childnode(node, action_idx)
    assert child_node != child_node2, &quot;child nodes are not unique when they should be&quot;
    mcts.add_node(child_node, node.id, action_idx)

    child_node2 = mcts.select_childnode(node, action_idx)
    assert child_node == child_node2, &quot;accessing the same child node that we previously added, should not create a new node&quot;




Testing started at 8:02 p.m. ...
Connected to pydev debugger (build 223.8617.48)
Launching pytest with arguments /home/tue/PycharmProjects/Hive_nn/tests/test_mcts.py --no-header --no-summary -q in /home/tue/PycharmProjects/Hive_nn/tests

============================= test session starts ==============================
collecting ... collected 1 item

test_mcts.py::test_select_childnode[mcts_ttt-node_ttt-0] FAILED          [100%]
test_mcts.py:43 (test_select_childnode[mcts_ttt-node_ttt-0])
mcts = &lt;function mcts_ttt at 0x7fe673be1f30&gt;
node = &lt;function node_ttt at 0x7fe673be1e10&gt;, action_idx = 0

    @pytest.mark.parametrize(&quot;mcts, node, action_idx&quot;, [
        (mcts_ttt, node_ttt, 0),
    ])
    
    
    def test_select_childnode(mcts, node, action_idx):
        &quot;&quot;&quot;
        Assert that childnode is creating a new node when needed.
        Assert that childnode is not creating a new node when not needed.
        &quot;&quot;&quot;
&gt;       mcts.nodes[node.id] = node
E       AttributeError: 'function' object has no attribute 'nodes'

test_mcts.py:54: AttributeError




============================== 1 failed in 1.29s ===============================

Process finished with exit code 1
</code></pre>
",https://stackoverflow.com/questions/75502794/pytest-unittest-how-to-group-test-cases,"['python', 'unit-testing', 'pytest']",64,True,0,2
Handling decimal-fields of mocked ontology-objects in unit-tests,"<p>I am trying to write unit tests for a typescript function repo in foundry. According to the palantir-foundry documentation, I'd like to use <code>Objects.create()</code> to mock objects for my tests and <code>whenObjectSet(objectSetOperation).thenReturn(objects)</code> for injection.</p>
<p>However, setting decimal fields of mocked objects in my tests results in the exception:</p>
<pre><code>node:internal/process/promises:279
            triggerUncaughtException(err, true /* fromPromise */);
            ^
[...]
SafeError: Setting property type is not supported.
args: [
    {
      type: 'UNSAFE',
      name: 'type',
      value: '{&quot;version&quot;:2,&quot;propertyTypeId&quot;:&quot;confirmed_quantity_menge&quot;,&quot;type&quot;:{&quot;type&quot;:&quot;decimal&quot;}}'
    }
  ],
  type: 'UserCausedError',
  errorInstanceId: 'd4e336a8-791b-48e3-8ea8-feb5405ace53',
  result: {
    runtimeError: {
      message: 'Setting property type is not supported.',
      stacktrace: 'SafeError: Setting property type is not supported.\n' +
        '    at UserCausedError.SafeError [as constructor] (/scratch/standalone/53c47a40-195f-4d78-9e75-53ee67c1e813/code-assist/contents/functions-typescript/node_modules/@foundry/witchcraft-logging-api/src/args/safeError.ts:26:9)\n' +
        '    at new UserCausedError (/scratch/standalone/53c47a40-195f-4d78-9e75-53ee67c1e813/code-assist/contents/functions-typescript/node_modules/@foundry/functions-typescript-runtime-isolate-api/src/UserCausedError.ts:19:5)\n' +
        '    at Object.settingPropertyTypeNotSupported (/scratch/standalone/53c47a40-195f-4d78-9e75-53ee67c1e813/code-assist/contents/functions-typescript/node_modules/@foundry/functions-typescript-runtime-storage/src/Errors.ts:81:12)\n' +
        '    at ObjectPropertyStore.throwIfSettingPropertyTypeUnsupported (/scratch/standalone/53c47a40-195f-4d78-9e75-53ee67c1e813/code-assist/contents/functions-typescript/node_modules/@foundry/functions-typescript-runtime-storage/src/properties/ObjectPropertyStore.ts:63:22)\n' +
        '    at ObjectPropertyStore.set (/scratch/standalone/53c47a40-195f-4d78-9e75-53ee67c1e813/code-assist/contents/functions-typescript/node_modules/@foundry/functions-typescript-runtime-storage/src/properties/ObjectPropertyStore.ts:26:14)\n' +
        '    at AnnotatingObjectStorageProvider.setPropertyValue (/scratch/standalone/53c47a40-195f-4d78-9e75-53ee67c1e813/code-assist/contents/functions-typescript/node_modules/@foundry/functions-typescript-runtime-storage/src/DefaultObjectStorageProvider.ts:39:28)\n
[...]
      parameters: {
        type: '{&quot;version&quot;:2,&quot;propertyTypeId&quot;:&quot;confirmed_quantity_menge&quot;,&quot;type&quot;:{&quot;type&quot;:&quot;decimal&quot;}}'
      }
    },
    type: 'runtimeError'
  }
}
</code></pre>
<p>In the foundry documentation I found the following information regarding the <code>decimal</code> type:</p>
<blockquote>
<p><code>decimal</code>: Properties of this type cannot be used within action
types as the precision cannot be    guaranteed when updating this data
type due to the conversion between JSON and Java. This type is also
not supported in Object Storage V2.</p>
</blockquote>
<p>However, I feel like this restriction really should not apply when it comes unit-testing (after all we are only talking about mocked data in this context). Does someone know a workaround for that problem without having to change the property type (and thus the ontology)?</p>
",https://stackoverflow.com/questions/75983918/handling-decimal-fields-of-mocked-ontology-objects-in-unit-tests,"['unit-testing', 'palantir-foundry', 'palantir-foundry-api']",32,True,0,1
Cannot use SQLAlchemy Session() outside Flask application context for unit testing,"<p>This is my inside <code>flaskapp/__init__.py</code> for creating my Flask app, with it I can access Session inside any module in the package, by just importing Session from <code>flaskapp/db.py</code>:</p>
<pre class=""lang-py prettyprint-override""><code>import os
from flask import Flask

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)

    app.config.from_mapping(
        SECRET_KEY=b'some_secret_key',
        DEBUG=True,
        SQLALCHEMY_DATABASE_URI=f'sqlite:///{os.path.join(app.instance_path, &quot;flaskapp.sqlite&quot;)}',
    )

    if test_config is None:
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(test_config)

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    with app.app_context():
        from flaskapp.routes import home, auth

        from flaskapp.db import init_db
        init_db()

    return app
</code></pre>
<p>This is my <code>flaskapp/db.py</code>:</p>
<pre class=""lang-py prettyprint-override""><code>from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from flask import current_app

engine = create_engine(current_app.config['SQLALCHEMY_DATABASE_URI'], echo=True)
Session = sessionmaker(bind=engine)

def init_db():
    import flaskapp.models as models
    models.Base.metadata.create_all(engine)

def drop_db():
    import flaskapp.models as models
    models.Base.metadata.drop_all(engine)
</code></pre>
<p>With that, I can access the database in any other module, for example, <code>flaskapp/auth.py</code>:</p>
<pre class=""lang-py prettyprint-override""><code>from flask import flash, session
from sqlalchemy import select

from flaskapp.db import Session
from flaskapp.models import User

def log_user(username: str, password: str) -&gt; bool:
    with Session() as db_session:
        stmt1 = select(User).where(User.username == username)
        query_user = db_session.execute(stmt1).first()

        if not query_user:
            flash('Some error message')

        # Some password verifications and other things
        session['username'] = query_user[0].username
        flash('Successfully logged in')

        return True

</code></pre>
<p>Until that point, I don't have any problem, the problem comes when I try to do unit testing with <code>unittest</code>, I can't set the test environment and I don't know how can I use the <code>Session</code> object defined in <code>flaskapp/db.py</code> for testing in a separate database. Everything I've tried until now gets me an error, this is my <code>tests/__init__.py</code>:</p>
<pre class=""lang-py prettyprint-override""><code>import unittest

from flaskapp import create_app
from flaskapp.db import Session
from flaskapp.models import User

class BaseTestClass(unittest.TestCase):
    def setUp(self):
        self.app = create_app(test_config={
            'TESTING': True,
            'DEBUG': True,
            'APP_ENV': 'testing',
             # I pass the test database URI expecting the engine to use it
            'SQLALCHEMY_DATABASE_URI': 'sqlite:///testdb.sqlite',
        })
        self.client = self.app.test_client()

        # Context
        with self.app.app_context():
            self.populate_db()

    def tearDown(self):
        pass

    def populate_db(self):
        with Session() as db_session:
            db_session.add(User(
                username='Harry',
                email='harry@yahoo.es',
                password = 'Harry123.'
            ))

            db_session.commit()
</code></pre>
<p>When I try to use the Session object inside <code>populate_db()</code> I get this error:</p>
<pre class=""lang-bash prettyprint-override""><code>=====================================================================
ERROR: tests.test_auth (unittest.loader._FailedTest.tests.test_auth)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.test_auth
Traceback (most recent call last):
  File &quot;/usr/local/lib/python3.11/unittest/loader.py&quot;, line 407, in _find_test_path
    module = self._get_module_from_name(name)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File &quot;/usr/local/lib/python3.11/unittest/loader.py&quot;, line 350, in _get_module_from_name
    __import__(name)
  File &quot;/home/chus/usb/soft/proy/SAGC/tests/test_auth.py&quot;, line 1, in &lt;module&gt;
    from flaskapp.db import Session
  File &quot;/home/chus/usb/soft/proy/SAGC/flaskapp/db.py&quot;, line 5, in &lt;module&gt;
    engine = create_engine(current_app.config['SQLALCHEMY_DATABASE_URI'], echo=True)
                           ^^^^^^^^^^^^^^^^^^
  File &quot;/home/chus/usb/soft/proy/SAGC/venv/lib/python3.11/site-packages/werkzeug/local.py&quot;, line 316, in __get__
    obj = instance._get_current_object()  # type: ignore[misc]
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File &quot;/home/chus/usb/soft/proy/SAGC/venv/lib/python3.11/site-packages/werkzeug/local.py&quot;, line 513, in _get_current_object
    raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.


----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
</code></pre>
<p>Can someone help me out? I've tried everything to make the tests use the app context in order to populate the test database and make queries but it appears to be conflicting with it being created in <code>create_app()</code> or something.</p>
",https://stackoverflow.com/questions/75416281/cannot-use-sqlalchemy-session-outside-flask-application-context-for-unit-testi,"['python', 'sqlite', 'flask', 'sqlalchemy', 'python-unittest']",99,False,-1,1
Restrict functions to be visible only for testing,"<p><em>This question is related to <a href=""https://stackoverflow.com/questions/35683991/kotlin-make-an-internal-function-visible-for-unit-tests"">Kotlin: Make an internal function visible for unit tests</a>, but this question deals with how to make internal functions <strong>unavailable</strong> to code that is <strong>not</strong> unit tests.</em></p>
<p>Suppose I have some methods that I want to use for unit testing, but I want to prevent them from being used in production code. How can I make it as difficult as possible to use the function in production code without resorting to any reflection tricks (such as modifying the visibility of a function) that could be blocked by a SecurityManager?</p>
<p>Essentially, can I make something like <a href=""https://guava.dev/releases/19.0/api/docs/com/google/common/annotations/VisibleForTesting.html"" rel=""nofollow noreferrer""><code>@VisibleForTesting</code></a>, but with some enforcement behind it? Or emulate the encapsulation abilities of <a href=""https://doc.rust-lang.org/rust-by-example/testing/unit_testing.html"" rel=""nofollow noreferrer"">Rust unit tests</a> which can be embedded directly in the module they are testing, thus allowing the tests to access items in that module without requiring those items to be visible outside the module?</p>
",https://stackoverflow.com/questions/75600940/restrict-functions-to-be-visible-only-for-testing,"['kotlin', 'unit-testing']",126,False,0,1
Strategy for unit and integration tests within the same project,"<p>I have a simple REST API written in Node.js, Express, and Prisma. I would like to write both unit and integration tests in Jest, where unit tests rely on a mocked Prisma client and integration tests run against a real test database.</p>
<p>I followed <a href=""https://www.prisma.io/docs/guides/testing/unit-testing"" rel=""nofollow noreferrer"">Prisma's guide to unit testing</a>, which works well so far. However, running integration tests isn't possible because the Prisma client is mocked.</p>
<ul>
<li>The <code>jest.config.js</code> uses <code>setupFilesAfterEnv</code> to boostrap the <a href=""https://www.prisma.io/docs/guides/testing/unit-testing#singleton"" rel=""nofollow noreferrer"">Prisma mock</a>.</li>
<li>My test files are co-located with the actual source code, not within a dedicated directory.</li>
<li>All tests (unit and integration) are launched via <code>jest --watch</code>.</li>
</ul>
<p>I would like to know a good strategy to run some tests with the mocked Prisma client and some tests with the real one. So far, my ideas didn't work out (like conditionally mocking Prisma or calling <code>jest.restoreAllMocks()</code>). Do you have any suggestions/ideas how this can be achieved?</p>
",https://stackoverflow.com/questions/75135215/strategy-for-unit-and-integration-tests-within-the-same-project,"['express', 'testing', 'jestjs', 'prisma', 'supertest']",99,False,0,0
Unit testing method that returns bool,"<p>Let's consider a method <code>bool Validate(Request req)</code>. The specific implementation doesn't matter.</p>
<p>But the thing we know is that this method always return <code>true</code> or <code>false</code>. And now I see problem with unit testing method like this below.</p>
<p>We can test whether it returns <code>false</code> when validation fails for many cases, e.g. user is not adult, has not enough role to access some resource etc.</p>
<p>But we can't determine where the <code>false</code> is returned. So unit test can be successful but due to different reason than expected.</p>
<p>Currently, to check whether <code>false</code> is returned where I want to return it (and this is specified by concrete test method where it should be returned) I set breakpoint on this <code>return</code> statement and run concrete unit test method. If test stops on this breakpoint I'm sure unit test is not lying.</p>
<p>But this approach seems primitive to me. How shall I write unit tests for methods that returns <code>bool</code>?</p>
",https://stackoverflow.com/questions/76265752/unit-testing-method-that-returns-bool,"['c#', 'unit-testing']",65,True,0,2
Mocha testcase is not running on chrome browser when we use import module in test spec files,"<p>We have been working on mocha and chai to write the unit test cases for the typescript project. But when we use the import module statement in the test spec file and launch html to run test cases on the browser, the mocha interface loads but no test cases run on the browser. It keeps on showing passes: 0
failures: 0
duration: 0s and the browser doesn't even throw some error to point out the exact issues.<a href=""https://i.stack.imgur.com/LkMhp.png"" rel=""nofollow noreferrer"">Browser snapshot</a>
If we go to the sources folder in the browser then the test spec file, chai.js, and mocha.js load successfully.
Official steps have been followed to integrate the mocha and chai test cases.</p>
<p>Here is the sample code structure:</p>
<p>index.ts:</p>
<pre><code>export class SampleClass {
  sayHello() {
    return &quot;Hello, world!&quot;;
  }
}
</code></pre>
<p>SampleSpec.ts</p>
<pre><code>import { SampleClass } from &quot;../src/index.js&quot;;
var expect = chai.expect;
var assert = chai.assert;
describe(&quot;Sample&quot;, () =&gt; {
  it(&quot;says hello&quot;, () =&gt; {
    console.log(&quot;Inside it block&quot;);
    const sample = new SampleClass();
    const result = &quot;Hello&quot;;
    expect(result).to.equal(sample.sayHello);
  });
});
</code></pre>
<p>index.html:</p>
<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;Test&lt;/title&gt;
    &lt;!-- &lt;script src=&quot;../node_modules/chai/chai.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;../node_modules/mocha/mocha.js&quot;&gt;&lt;/script&gt; --&gt;
    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/chai@4.2.0/chai.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/mocha@10.2.0/mocha.js&quot;&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id=&quot;mocha&quot;&gt;&lt;/div&gt;
    &lt;script type=&quot;module&quot; src=&quot;../test/Castor.spec.js&quot;&gt;&lt;/script&gt;
    &lt;script&gt;
      mocha.setup(&quot;bdd&quot;);
      mocha.run();
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;

</code></pre>
<p>tsconfig:</p>
<pre><code>{
  &quot;compilerOptions&quot;: {
    &quot;target&quot;: &quot;ES2020&quot;,                                  
    &quot;module&quot;: &quot;ES2020&quot;,                                
    &quot;esModuleInterop&quot;: true,                            
    &quot;forceConsistentCasingInFileNames&quot;: true,            

    &quot;strict&quot;: true,                                      
    &quot;skipLibCheck&quot;: true                                 
  }
}

</code></pre>
<p>Note: It is working on safari and giving the right results of unit testing but not running on chrome browser.</p>
<p>Can someone help what's the issue here when running on chrome?</p>
",https://stackoverflow.com/questions/75358250/mocha-testcase-is-not-running-on-chrome-browser-when-we-use-import-module-in-tes,"['google-chrome', 'mocha.js']",58,False,1,1
Python unit testing with consistent random.seed using multiprocessing?,"<p>I have a function in my code that calls a <code>multiprocessing.Pool</code>, and each worker process calls a function <code>generate_sensor</code> that uses <code>random.randint</code> and <code>random.choice</code> a number of times.  <code>generate_sensor</code> is in the file <code>seed.py</code>, which imports <code>random</code>.</p>
<p>I want to set a consistent random seed to ensure reproducible unit tests, and I'm having trouble, I <em>think</em> because of the use of multiprocessing, which means the order random is called isn't consistent.  Or maybe I just am trying to set the seed incorrectly.</p>
<hr />
<p>The code in question, <code>my_module.py</code> in <code>main</code> contains something like this:</p>
<pre class=""lang-py prettyprint-override""><code>num_processes = multiprocessing.cpu_count() -1
pool = multiprocessing.Pool(num_processes)
tasks: list[tuple[seed.Seed, str, int, int]] = []
sensors: dict[str, sensor.Sensor] = {}

for i in range(num_processes):
    tasks.extend([(s, self.recSeq, seedSensPerProcess, i) for s in seeds])

for t in tasks:
    pool.apply_async(
        generate_sensor, t, callback=lambda result: sensors.update(
            [(r.seq, r) for r in result]
        ),
    )
pool.close()
pool.join()
return sensors
</code></pre>
<hr />
<p>I'm trying to set a consistent seed in pytest for unit testing, to ensure a consistent result.</p>
<p>So far, I tried both of the following, to no success:</p>
<p><strong>Failed Approach 1:</strong></p>
<pre class=""lang-py prettyprint-override""><code>def test_my_function() -&gt; None:
    random.seed(0)
    out_sensors = my_module.main()
    print(out_sensors)
    assert False # so pytest will show print no matter what
</code></pre>
<p>This shows a different output every time, so the random imported by seed.py is not affected.</p>
<p><strong>Failed Approach 2:</strong></p>
<pre class=""lang-py prettyprint-override""><code>def test_my_function() -&gt; None:
    with patch(&quot;my_package.seed.random&quot;) as mock_random:
        mock_random = random.Random(0)

        out_sensors = my_module.main()
        print(out_sensors)
        assert False # so pytest will show print no matter what
</code></pre>
<p>This fails silently, and doesn't generate any output-- I'm guessing seed's imported random is no longer working.</p>
<hr />
<p>Any idea on how to properly pass a random seed to the submodule?</p>
",https://stackoverflow.com/questions/75871558/python-unit-testing-with-consistent-random-seed-using-multiprocessing,"['python', 'random', 'mocking', 'multiprocessing', 'pytest']",73,False,1,1
Unittesting a ServiceStack service that uses AutoMapper,"<p>We are using ServiceStack for our .NET backend and I am trying to work on getting unit testing into the project. However there are some automated tools within ServiceStack that makes it a bit complicated to isolate the units so I could really use some advice. In the example below I would like to unit test a simple service that basically does the following:</p>
<ol>
<li>Takes a request DTO</li>
<li>Passes the DTO to the repository</li>
<li>Gets back a domain model</li>
<li>If the model exists, it maps it to a responseDTO using Automapper and returns it as a part of an IHTTPResult</li>
</ol>
<p>So the problem I have is that it seems like Automapper is automatically added to the ServiceStack application and in the application the mapper are registered by just calling:</p>
<pre><code>AutoMapping.RegisterConverter().
</code></pre>
<p>So how could I inject this into the service to be able to do the unittest?</p>
<p>Example test:</p>
<pre><code>using AutoMapper;
using FluentAssertions;
using NSubstitute;

namespace Api.Services.Tests.Unit;

public class OrderApiServiceTests
{
    private readonly OrderApiService _sut;
    private readonly IOrderApiRepository accountApiRepository = Substitute.For&lt;IOrderApiRepository&gt;();

    public OrderApiServiceTests()
    {
        _sut = new OrderApiRepository(orderApiRepository);
        var config = new MapperConfiguration(cfg =&gt; ApiDtoMapping.Register());
        var mapper = config.CreateMapper();
    }

    [Fact]
    public async Task Get_ShouldReturnAccount_WhenAccountExistsAsync()
    {
        // Arrange
        var order = new Order
        {
            Name = &quot;MyOrder&quot;,
            Value = 1000,
        };

        var expectedResponse = new OrderApiDto
        {
            Name = &quot;MyOrder&quot;,
            Value = 1000,
        };

        orderApiRepository.GetAsync(Arg.Any&lt;GetOrder&gt;()).Returns(order);

        // Act
        var result = await _sut.Get(new GetOrder());

        // Assert
        result.StatusCode.Should().Be(System.Net.HttpStatusCode.OK);
        result.Response.Should().BeEquivalentTo(expectedResponse);
    }
}
</code></pre>
<p>Added a full example including all files:</p>
<pre><code>// Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler(&quot;/Error&quot;);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
    app.UseHttpsRedirection();
}

app.UseServiceStack(new AppHost());
app.Run();

// Configure.AppHost.cs
using Funq;
using ssUnitTests.ServiceInterface;

[assembly: HostingStartup(typeof(ssUnitTests.AppHost))]

namespace ssUnitTests;

public class AppHost : AppHostBase, IHostingStartup
{
    public void Configure(IWebHostBuilder builder) =&gt; builder
        .ConfigureServices(services =&gt;
        {
        });

    public AppHost() : base(&quot;ssUnitTests&quot;, typeof(MyServices).Assembly) { }

    public override void Configure(Container container)
    {
        container.RegisterAutoWiredAs&lt;OrderRepository, IOrderRepository&gt;().ReusedWithin(ReuseScope.None);

        // Configure ServiceStack only IOC, Config &amp; Plugins
        SetConfig(new HostConfig
        {
            UseSameSiteCookies = true,
        });

        Mappings.RegisterConverters();
    }
}

// Mappings.cs
using ssUnitTests.ServiceModel;

namespace ssUnitTests;

public static class Mappings
{
    public static void RegisterConverters()
    {
        AutoMapping.RegisterConverter((Order from) =&gt;
        {
            var to = from.ConvertTo&lt;OrderDto&gt;();
            to.DtoProperty = from.BaseProperty + &quot;Dto&quot;;
            return to;
        });
    }
}

// IOrderRepository.cs
using ssUnitTests.ServiceModel;

namespace ssUnitTests.ServiceInterface;

public interface IOrderRepository
{
    Order GetOrder();
}

// Order.cs
namespace ssUnitTests.ServiceModel;

public class Order
{
    public string Name { get; set; }
    public string BaseProperty { get; set; }
}

// OrderDto.cs
namespace ssUnitTests.ServiceModel;

public class OrderDto
{
    public string Name { get; set; }
    public string DtoProperty { get; set; }
}

// OrderRequest.cs
using ServiceStack;

namespace ssUnitTests.ServiceModel;

[Route(&quot;/order&quot;)]
public class OrderRequest : IReturn&lt;OrderDto&gt;
{
    public int Id { get; set; }
}

// UnitTest.cs
using NSubstitute;
using NUnit.Framework;
using ssUnitTests.ServiceInterface;
using ssUnitTests.ServiceModel;

namespace ssUnitTests.Tests;

public class UnitTest
{
    private readonly MyServices _sut;
    private readonly IOrderRepository _repository = Substitute.For&lt;IOrderRepository&gt;();

    public UnitTest()
    {
        _sut = new MyServices(_repository);
    }

    [Test]
    public void Get_ShouldReturn_OrderDto()
    {
        var order = new Order
        {
            Name = &quot;MyName&quot;,
            BaseProperty = &quot;MyBaseProperty&quot;
        };

        _repository.GetOrder().Returns(order);

        var response = (OrderDto)_sut.Any(new OrderRequest { Id = 1 });

        Assert.That(response.Name.Equals(order.Name));
        Assert.That(response.DtoProperty.Equals(order.BaseProperty + &quot;Dto&quot;));
    }
}

</code></pre>
",https://stackoverflow.com/questions/75293911/unittesting-a-servicestack-service-that-uses-automapper,"['c#', 'unit-testing', 'servicestack']",79,True,1,1
MVVM: View Creates ViewModel ViewModel takes Model as a Constructor argument. Is this an MVVM violation?,"<p>In MVVM I was reading that the View and the Model should not know about each other. (C# example)</p>
<p>I have the ViewModel set up such that the ViewModel takes an instance of the Model as an input argument. This is done to support Dependency Injection via the constructor to help with Unit Testing, but I am not using a Dependency Injection Framework.</p>
<pre><code>ViewModel(IModel ModelInstance){}
</code></pre>
<p>If the View is responsible for creating the View Model, is the following a violation of MVVM?</p>
<pre><code>View()
{
   Model myModel = new Model ();
   this.DataContext = new ViewModel(myModel);
}
</code></pre>
<p>This seems like an MVVM violation because the View knows about the Model, as it is explictly creating the Model.</p>
<p>Is this an MVVM violation? What have folks done to work around this problem?</p>
<p>I have read the other similar MVVM questions and I still wasn't seeing any concrete ways to address this. <a href=""https://stackoverflow.com/questions/13080172/how-should-a-model-get-passed-into-the-viewmodel"">How should a Model get passed into the ViewModel?</a></p>
<p>Specifically I'm asking if the View creates the ViewModel, who is responsible for creating the model that gets passed into the ViewModel</p>
",https://stackoverflow.com/questions/75102761/mvvm-view-creates-viewmodel-viewmodel-takes-model-as-a-constructor-argument-is,"['wpf', 'mvvm', 'viewmodel']",375,True,-1,3
Jest mock output for prisma.groupBy method,"<p>I have a litesql db with a prisma schema that looks like:</p>
<pre><code>model Rating {
    id      String @id @default(cuid())
    rating  Float
    userId  String
    videoId String

    @@unique([userId, videoId], name: &quot;user_video_rating&quot;)
}
</code></pre>
<p>and I'm trying to write a unit test for the following function:</p>
<pre class=""lang-js prettyprint-override""><code>const ratings = await prisma.rating.groupBy({
    by: [&quot;videoId&quot;],
    _avg: { rating: true },
    _count: true
});
</code></pre>
<p>I have written a Jest test as follows:</p>
<pre class=""lang-js prettyprint-override""><code>test(&quot;get all ratings&quot;, async () =&gt; {
    const prismaMock = mockDeep&lt;PrismaClient&gt;();
    // can't figure out how to make a mock output for groupBy()
});
</code></pre>
<p>As the comment says, I can't figure out how to make a mock output for groupBy(). I'm working in TS, and I've already tried using <code>prismaMock.rating.groupBy.mockResolvedValue()</code>, but <code>mockResolvedValue()</code> does not exist on <code>groupBy</code>. I also tried using the following jest spy codes:</p>
<pre class=""lang-js prettyprint-override""><code>const groupBySpy = jest.spyOn(prismaMock.rating, &quot;groupBy&quot;);
groupBySpy.mockReturnValue([]); // i've tried this
groupBySpy.mockImplementation(() =&gt; {}); // i've also tried this
</code></pre>
<p>but I couldn't get either to work because the types that they require seem to be not output data.</p>
<p>I'm not sure how to make a test function work with groupBy, but I don't want to switch <code>groupBy</code> to multiple <code>aggregate({where: })</code> calls in my logic just because I can't write a unit test for the <code>groupBy</code> method. Does anyone have suggestions on what to do regarding unit testing this method or have any experience writing unit tests for <code>prisma.#.groupBy()</code> that can help me figure out how to resolve this issue?</p>
",https://stackoverflow.com/questions/76083136/jest-mock-output-for-prisma-groupby-method,"['typescript', 'unit-testing', 'jestjs', 'prisma']",86,False,0,1
How to test unicorn.rb,"<p>I've actually been Unicorn for a few years now, but I've never really run any proper tests on my basic code for running a Unicorn application. So one of the first things I want to test is <code>unicorn.rb</code>. At the very least, I'd like to make sure it compiles, but, of course,  I want to eventually run more detailed tests on it.</p>
<p>But I can't figure out how to load the file. Obviously just running it from the command line doesn't accomplish anything. I'd like to run the code in the file without having to run Unicorn itself. That is, I want to do some basic unit testing before going much further with my application.</p>
<p>So the question is how do I load and run <code>unicorn.rb</code> by itself, with minimal extra required code.</p>
<p>If you're interested, here's my current <code>unicorn.rb</code>. I welcome your feedback, but my main goal right now is to find a way to run tests on just that file.</p>
<pre class=""lang-rb prettyprint-override""><code># Snout is a tiny application for experimenting with Unicorn.
# Nothing more, nothing less.

# path to data directory
snout_data_root = '/srv/apps/snout'

# path to app that will be used to configure unicorn
@dir = File.dirname(__FILE__)

# workers
worker_processes 5
working_directory @dir

# timeout
timeout 30

# set user and group
user 'www-data', 'www-data'

# Specify path to socket unicorn listens to
listen &quot;#{snout_data_root}/sockets/unicorn.sock&quot;, :backlog =&gt; 64

# Set process id path
pid &quot;#{snout_data_root}/pids/unicorn.pid&quot;

# Not exactly sure what this does, but the following page suggests it's
# generally a good idea to have this setting.
# https://bogomips.org/unicorn/Unicorn/Configurator.html
rewindable_input false

# avoid spawn loops
preload_app true

# paths to which Unicorn sends STDOUT and STDERR
stderr_path &quot;#{snout_data_root}/logs/unicorn.log&quot;
stdout_path &quot;#{snout_data_root}/logs/unicorn.log&quot;
</code></pre>
",https://stackoverflow.com/questions/76117186/how-to-test-unicorn-rb,"['ruby', 'unicorn']",37,False,0,0
Vite (vitest) config resolve.mainFields field - how should packages with TypeScript type definitions be handled?,"<p>for a few days now I have been migrating our unit testing setup from jest to vitest because of performance reasons. The setup was easy and with &quot;pure&quot; modules it works just fine. The problems come when I start importing npm packages with TypeScript type definitions into the project.</p>
<p>I was looking at the <code>resolve.mainFields</code> in the config because some of the packages only have <code>main</code> entry points, some only have <code>types</code> (they usually are the @types/* packages) and some have both.
I <em>think</em> it counts in what order you've passed the entry point to the <code>resolve.mainFields</code> because whenever it has to deal with a package that has &quot;normal&quot; and &quot;types&quot; entry points, whichever comes second would fail.</p>
<p>How should it be handled?</p>
<p>--- technical informations ---</p>
<p>Here is my current config:</p>
<pre><code>export default defineConfig({
  plugins: [react(), tsconfigPaths()],
  test: {
    globals: true,
    environment: &quot;happy-dom&quot;,
    setupFiles: &quot;./vitest.setup.ts&quot;,
  },
  resolve: {
    mainFields: [&quot;types&quot;, &quot;main&quot;, &quot;module&quot;, &quot;jsnext&quot;, &quot;files&quot;],
  },
});
</code></pre>
<p>And my pruned package.json:</p>
<pre><code>&quot;vitest&quot;: &quot;0.27.2&quot;,
&quot;@vitejs/plugin-react&quot;: &quot;3.0.1&quot;,
&quot;vite-tsconfig-paths&quot;: &quot;4.0.3&quot;
</code></pre>
<p>I've tried to move the different entry points within the <code>resolve.mainFields</code> array but whenever it had to deal with a package that had &quot;normal&quot; and &quot;types&quot; entry points, whichever came second failed.</p>
",https://stackoverflow.com/questions/75170354/vite-vitest-config-resolve-mainfields-field-how-should-packages-with-typescr,"['typescript', 'vite', 'vitest']",21,False,0,0
Microsoft Cognitive Services - Unsupported Audio Format,"<p>I am developing a web app in ASP.net Core MVC.</p>
<p>I am trying to record audio in Javascript through the users microphone and I achieve this by using <code>MediaRecorder()</code>. I send the blob with the audio data to the backend where I receive the data in the form of IFormFile.</p>
<p>Script to record audio:</p>
<pre><code>    navigator.mediaDevices.getUserMedia({ audio: true })
    .then(async function (stream) {
        var recordButton = document.getElementById(&quot;record-button&quot;);
        var stopButton = document.getElementById(&quot;stop-button&quot;);

        var microphone = await audioContext.createMediaStreamSource(stream);

        var gainNode = audioContext.createGain();
        var recorder = new MediaRecorder(stream);

        var destination = audioContext.createMediaStreamDestination();

        recordButton.addEventListener(&quot;click&quot;, function () {
            gainNode.connect(destination);
            recorder.start();
            recordButton.disabled = true;
            recordButton.style.pointerEvents = &quot;none&quot;;
        });

        stopButton.addEventListener(&quot;click&quot;, function () {
            microphone.disconnect();
            gainNode.disconnect();
            recorder.stop();
        });

        recorder.ondataavailable = (event) =&gt; 
        {
            var blob = event.data;

            var formData = new FormData();
            formData.append('audioBlob', blob);
            formData.append('sentence', $('#sentence-input').val());

            $.ajax({
                url: '@Url.Action(&quot;ProcessAudio&quot;, &quot;Sandbox&quot;)',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (data) {
                    $('#modalContent').html(data);

                    $('#myModal').modal('show');
                },
            });
        };
</code></pre>
<p>I then receive the data, copy it to a byte array, save it in a Temporary File in the desired sample rate that Microsoft Cognitive Services asks for, and send it to my API in Python where I invoke Microsoft's tool.</p>
<pre><code>@app.route(&quot;/pronunciation-assessment&quot;, methods=[&quot;POST&quot;])
def pronunciation_assessment():
    audioFile = request.files['audio_data']
    reftext = request.form.get(&quot;reftext&quot;)

    audioFile.save(&quot;audio.wav&quot;)

    audioFile = open(&quot;audio.wav&quot;, &quot;rb&quot;)
    def get_chunk(audio_source, chunk_size=1024):
        while True:
            chunk = audio_source.read(chunk_size)
            if not chunk:
                break
            yield chunk

    referenceText = reftext
    pronAssessmentParamsJson = &quot;{\&quot;ReferenceText\&quot;:\&quot;%s\&quot;,\&quot;GradingSystem\&quot;:\&quot;HundredMark\&quot;,\&quot;Dimension\&quot;:\&quot;Comprehensive\&quot;,\&quot;EnableMiscue\&quot;:\&quot;True\&quot;}&quot; % referenceText
    pronAssessmentParamsBase64 = base64.b64encode(bytes(pronAssessmentParamsJson, 'utf-8'))
    pronAssessmentParams = str(pronAssessmentParamsBase64, &quot;utf-8&quot;)

    url = &quot;https://%s.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=%s&amp;usePipelineVersion=0&quot; % (region, language)
    headers = {
    'Accept': 'application/json;text/xml',
    'Connection': 'Keep-Alive',
    'Content-Type': 'audio/wav; codecs=audio/pcm; samplerate=16000',
    'Ocp-Apim-Subscription-Key': subscription_key,
    'Pronunciation-Assessment': pronAssessmentParams,   
    'Transfer-Encoding': 'chunked',
    'Expect': '100-continue'
}

    response = requests.post(url=url, data=get_chunk(audioFile), headers=headers)

    audioFile.close()

    return response.json()
</code></pre>
<p>I have done unit testing on this endpoint prior with just a standard .wav file that was stored locally and it worked out fine. Furthermore, upon listening to audio.wav, I observe that everything was saved correctly and the audio is playable.</p>
<p>However, when I return the <code>response.json</code>, I get</p>
<blockquote>
<p>Expecting value: line 1 column 1 (char 0)</p>
</blockquote>
<p>And upon close inspection, the content of <code>response</code> is b'Unsupported audio format'</p>
<p>What shall I do?</p>
",https://stackoverflow.com/questions/76367673/microsoft-cognitive-services-unsupported-audio-format,"['javascript', 'python', 'audio', 'speech-recognition', 'azure-cognitive-services']",37,False,0,0
