title,body,link,tags,view_count,is_answered,score,answer_count
LocalDateTime Integration Testing,"<p>I am having assertion Error</p>
<p>Why the lenght of <code>second</code> is different in <code>toString()</code> and <code>DB Stored Value</code></p>
<pre><code>java.lang.AssertionError: 1 expectation failed.
JSON path _embedded.positionsSnapshotDToes.linkTime doesn't match.
Expected: &lt;[2022-11-09T10:01:03.152146400]&gt;
  Actual: [2022-11-09T10:01:03.152146]
</code></pre>
<p>Using JPA to store entities basically I have following Pojo</p>
<pre><code>@Column(name = &quot;LINK_TIME&quot;)
    private LocalDateTime linkTime;
</code></pre>
<p><strong>Here is the test code</strong></p>
<pre><code>@Test
shouldPassLinkTime()
{

        final LocalDateTime anyLinkTime = LocalDateTime.now();

        posSnapshotRepo.save(
                PositionsSnapshot.builder()
                        .linkTime(anyLinkTime)
                        .build()
        );

       SnapshotFilterDTO dto = SnapshotFilterDTO.builder()
                .build();

        given()
                .spec(correctCredentialsAndPortSpec)
                .log().ifValidationFails()
                .contentType(&quot;application/json&quot;)
                .body(MAPPER_HELPER.writeValueAsString(dto))
                .when()
                .post(&quot;service/unmatched&quot;)
                .then()
                .statusCode(200)
                .log().ifValidationFails()
                .and().body(&quot;_embedded.positionsSnapshotDToes.linkTime&quot;, equalTo(Arrays.asList(anyLinkTime.toString())))


                .and().body(&quot;page.totalPages&quot;, equalTo(1))
                .and().body(&quot;page.totalElements&quot;, equalTo(1))
                .and().body(&quot;page.number&quot;, equalTo(0));
    }
</code></pre>
",https://stackoverflow.com/questions/74371346/localdatetime-integration-testing,"['java', 'localdate', 'localdatetime']",156,False,1,1
Integration testing with XCtest,"<p>I'm trying to write some Unit and Integration testing using XCtest.
I have a part that I'm not sure if it is a unit test or Integration test :
I need to test uploading one document using an upload service .
My question : Since my function is going to interact with a different service &quot;upload service&quot; so I'm thinking that it is an Integration test more than a unit test.
Could anyone please confirm ?</p>
",https://stackoverflow.com/questions/73606106/integration-testing-with-xctest,"['integration-testing', 'xctest']",29,False,0,0
Integration Testing for Microprofile / OpenLiberty,"<p>I have joined a new project who are using Microprofile/Openliberty. I have searched around quite a bit on the internet and it doesnt look like there is a straight forward way to write integration tests using this framework.</p>
<p>Some tutorials pointed me towards arquillian etc which can only run in a maven build so no support for running the tests directly from Intellij/IDE. Others need a full installation of Openliberty on your drive.</p>
<p>I am ideally looking for some thing similar to @SpringBootTest. And if such functionality isnt available then at a minimum I need a way to hit the API Endpoints of my app using a test HTTP client where I can ensure that the JSON I send to the endpoint is parsed correctly and the query/path params are correctly interpreted etc. The deeper part of the App I can just mock.</p>
<p>Is there a programmatic or otherwise way of doing this using the microprofile/openliberty framework?</p>
<p>Thanks in Advance :)</p>
",https://stackoverflow.com/questions/71939026/integration-testing-for-microprofile-openliberty,"['jakarta-ee', 'integration-testing', 'jboss-arquillian', 'open-liberty', 'microprofile']",167,False,1,0
Integration Testing Adonisjs5 using Japa,"<p>been trying for a while find some resources online but i've been failing on that.</p>
<p>This could be a silly question but i've been struggling for a while now and no progress whatsoever.</p>
<p>I've been trying to test my post route. The intent is to create something and it's been working just fine but I must make this integration test and I should use only AdonisJS5 resource.</p>
<p>When I make this request from test I send all this info:</p>
<p>{
&quot;name&quot;: &quot;Profession name&quot;
}</p>
<p>That's the requirement.</p>
<p>My code:</p>
<pre><code>import { test } from '@japa/runner'
import Profession from 'App/Models/Profession'
import User from 'App/Models/User'

test.group('Professions post', () =&gt; {
  test('should create a profession', async ({ client }) =&gt; {
    const user = await User.find(1)
    const response = await client.post('/professions').loginAs(user!).send()
    console.log(response)
    response.assertStatus(201)
    response.assertBodyContains({
      name: 'Web Developer',
    })
  })
})
</code></pre>
<p>The return:</p>
<pre><code>✖ should create a profession

  Assertion Error: expected 422 to equal 201

- Expected  - 1
+ Received  + 1

- 201
+ 422

   at Object.executor tests/functional/controllers/profession/create.spec.ts:10
     5|   test.group('Professions post', () =&gt; {
     6|     test('should create a profession', async ({ client }) =&gt; {
     7|       const user = await User.find(1)
     8|       const response = await client.post('/professions').loginAs(user!).send()
     9|       console.log(response)
  ❯ 10|      response.assertStatus(201)
    11|      response.assertBodyContains({
    12|        name: 'Web Developer',
    13|      })
    14|    })
    15|  })
</code></pre>
<p>I appreciate every help possible.</p>
",https://stackoverflow.com/questions/73557738/integration-testing-adonisjs5-using-japa,"['javascript', 'testing', 'integration-testing', 'adonisjs-ace']",27,False,0,0
Integration Testing in CICD Pipeline,"<p>I have a spring boot project[App-Server], for which I want to test.
I have created Mock Server docker image also hosted in AWS/Dockerhub for the same.
Also I have used Rest Assured for API Testing. For this also docker image is available in AWS/Dockerhub.</p>
<p>Now before creating docker image for App-Server, I want to perform integration testing where I want Dockerfile.test for App-Server to load and create docker image, then on jenkins I want first the App-Server docker image to load, then Mock-Server docker image to load and after that the Rest Assured to load and do the testing which can be done via mvn test. Once the test is successful, I want to create the final docker image for App-Server.</p>
<p>Can this be done via Jenkins or AWS.</p>
",https://stackoverflow.com/questions/73707302/integration-testing-in-cicd-pipeline,"['amazon-web-services', 'spring-boot', 'docker', 'jenkins-pipeline']",39,False,-1,1
Selenium Integration Testing WebApplicationFactory&lt;Program&gt;,"<p>I got exception when tried Selenium Integration test.</p>
<pre><code>OpenQA.Selenium.WebDriverException
unknown error: net::ERR_CONNECTION_REFUSED
  (Session info: headless MicrosoftEdge=108.0.1462.54)
   at OpenQA.Selenium.WebDriver.UnpackAndThrowOnError(Response errorResponse, String commandToExecute)
   at OpenQA.Selenium.WebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.WebDriver.set_Url(String value)
   at OpenQA.Selenium.Navigator.GoToUrl(String url)
   at Brushtail.AspNetCore.Blazor.Pages.IndexTests.HomePageTest() in D:\Projects\Brushtail-Extensions\Brushtail.Extensions\Brushtail.AspNetCore\Brushtail.AspNetCore.Blazor\Pages\Index.Tests.cs:line 17
</code></pre>
<p>But HttpClient returns the status code 200</p>
<pre><code>var result = await Client.GetAsync(&quot;/&quot;);

result.IsSuccessStatusCode.ShouldBe(true);
</code></pre>
<p>Major I am using Blazor .NET 7, so I can't use old Startup. I am testing on real db server. Because In Memory database doesn't supports the NetTopologySuite.</p>
<pre><code>new WebApplicationFactory&lt;Program&gt;()
</code></pre>
",https://stackoverflow.com/questions/74938143/selenium-integration-testing-webapplicationfactoryprogram,"['asp.net', 'selenium', 'automated-tests', 'integration-testing', 'testserver']",81,False,0,0
How to do integration testing,"<pre><code>
def customer_menu():
    print(&quot;&gt;&gt; Customer MENU:\n&quot;)
    print(&quot;1. Deposit\n2. Withdrawal\n3. View Transaction\n4. Logout&quot;)
    opt_customer_menu=int(input(&quot;&gt; Please select your option (1/2/3/4): &quot;))
    while(opt_customer_menu !='4'):
        if (opt_customer_menu==1):
            customer_deposit()
        elif(opt_customer_menu==2):
            customer_withdraw()
        elif(opt_customer_menu==3):
            customer_view()
        elif(opt_customer_menu==4):
            print(&quot;*** Good bye! Have a nice day! ***\n\n&quot;)
            main_menu()
        else:
            print(&quot;!!! Invalid Option! Please read the option carefully! !!!\n&quot;)
        opt_customer_menu=int(input(&quot;&gt; Please select your option (1/2/3/4): &quot;))
        
def customer_deposit():
    print(&quot;\nYou choose '1. Deposit'&quot;)
    print(&quot;----------------------------------&quot;)
    deposit_id = str(input(&quot;&gt; Enter your Customer ID: &quot;))
    deposit_balance = str(input(&quot;&gt; Enter the BALANCE to be deposit: &quot;))
    deposit_pass = str(input(&quot;&gt; Enter your Password: &quot;))
    customer_file = open(&quot;customer_db.txt&quot;,&quot;r&quot;)
    transaction_file = open(&quot;transaction_db.txt&quot;,&quot;a&quot;)
    for line in customer_file:
        cust_deposit = line.strip().split(&quot;,&quot;)
        if (deposit_id == cust_deposit[0] and deposit_pass == cust_deposit[4]):
            transaction_file.write(deposit_id+&quot;,&quot;+deposit_balance+&quot;,Deposit\n&quot;)
            transaction_file.close()
            print(&quot;*** BALANCE SUCSSESFULLY DEPOSIT! ***&quot;)
            print(&quot;--- Return to Customer Menu ---\n&quot;)
            customer_menu()
            return True
    print(&quot;!!! You enter wrong ID or Password !!!&quot;)
    print(&quot;--- Return to Customer Menu ---\n\n&quot;)
    customer_menu()
    return False
    

#Customer withdraw transaction
def customer_withdraw():
    print(&quot;\nYou choose '2. Withdrawal'&quot;)
    print(&quot;----------------------------------&quot;)
    withdrawal_id = str(input(&quot;&gt; Enter your Customer ID: &quot;))
    withdrawal_balance = str(input(&quot;&gt; Enter the BALANCE to be withdraw: &quot;))
    withdrawal_pass = str(input(&quot;&gt; Enter your Password: &quot;))
    customer_file = open(&quot;customer_db.txt&quot;,&quot;r&quot;)
    transaction_file = open(&quot;transaction_db.txt&quot;,&quot;a&quot;)
    for line in customer_file:
        cust_withdrawal = line.strip().split(&quot;,&quot;)
        if (withdrawal_id == cust_withdrawal[0] and withdrawal_pass == cust_withdrawal[4]):
            transaction_file.write(withdrawal_id+&quot;,-&quot;+withdrawal_balance+&quot;,Withdrawal\n&quot;)
            transaction_file.close()
            print(&quot;*** WITHDRAWAL SUCCESS! ***&quot;)
            print(&quot;--- Return to Customer Menu ---\n&quot;)
            customer_menu()
            return True
    print(&quot;!!! You enter wrong ID or Password !!!&quot;)
    print(&quot;--- Return to Customer Menu ---\n\n&quot;)
    customer_menu()
    return False
    
)
    
customer_menu()
</code></pre>
<p>I'm do the unit test with using pytest successfully but I cant do the integration test. I can't imagine how to make a code for do integration test.I have no idea about that so.This is a simple banking app.need a testing code.i combine unit testing codes .but not working.please help me.</p>
",https://stackoverflow.com/questions/74547971/how-to-do-integration-testing,"['python', 'pytest']",28,False,0,0
Reporters for Flutter integration testing,"<p>I am looking for examples of integrations among Flutter Integration library and test management tools like TestRail or Xray.
For Cypress and other browser automation tools I can find plenty of solutions but for Flutter integration basically nothing.</p>
",https://stackoverflow.com/questions/72318331/reporters-for-flutter-integration-testing,"['flutter', 'testrail', 'jira-xray', 'flutter-integration-test', 'jfrog-xray']",679,True,0,2
Create order during integration testing,"<p>For my custom integration test, I need some dummy order (I want to update the tracking number later, as per my module).</p>
<p>Until now the best was I found is to copy</p>
<p><code>\Shopware\Core\Checkout\Test\Order\Listener\OrderStateChangeEventListenerTest::createOrder</code> to my test class. Is there a more convenient method, with less copy &amp; paste?</p>
",https://stackoverflow.com/questions/72436744/create-order-during-integration-testing,"['integration-testing', 'shopware6']",29,True,0,1
Integration testing with docker-compose,"<p>I am working on an application with multiple (10+) containers (microservices .NET, front-end React, 3rd party etc.) being started using docker-compose files.
How would you go about integration testing? Is there a testing framework which would allow a beforeAll() to clear containers, restart them, or clean volumes? Do you know of a well-performing setup to run multiple integration tests against a docker-compose environment?</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/72430520/integration-testing-with-docker-compose,"['docker-compose', 'continuous-integration', 'integration-testing']",205,False,0,1
Quarkus integration testing against running application,"<p>As described in the official <a href=""https://quarkus.io/guides/getting-started-testing#executing-against-a-running-application"" rel=""nofollow noreferrer"">documentation</a>, it should be possible to run the  <em>@QuarkusIntegrationTest</em> against a running application.
This feature looks incredibly useful, especially if I can run these integration test against a Quarkus service running on a test server, where it is integrated with all my other micro-services.</p>
<p>Unfortunately I never managed to make it work. I'm following step-by-step what's written in the documentation, but to me it looks it's not working at all.</p>
<p>Is there anyone who is using this feature and knows if it is actually working/supported by Quarkus v2.7?</p>
",https://stackoverflow.com/questions/71022998/quarkus-integration-testing-against-running-application,"['java', 'rest', 'integration-testing', 'quarkus', 'quarkus-rest-client']",605,True,2,2
Google Sign In Integration Testing Flutter,"<p>I have implemented Google Sign In using Firebase, but somehow while performing the Integration Testing, I am not able to click the different email address options when the default dialog box opens to sign in. Is there any way I can click on the email given in the dialog box and navigate to the next screen.
The test for finding the login button passess successfully, but the testing app closes once the test has passed not clicking any of the given email addressess on the dialog box.
Attaching screen shots of start screen and email dialog box for better understanding.
<a href=""https://i.stack.imgur.com/wnYte.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/wnYte.png"" alt=""enter image description here"" /></a>
<a href=""https://i.stack.imgur.com/tabav.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/tabav.png"" alt=""enter image description here"" /></a>
<a href=""https://i.stack.imgur.com/r5wLd.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/r5wLd.png"" alt=""enter image description here"" /></a></p>
<p>Code</p>
<pre><code>void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();
  group('end-to-end test', () {
    var log = find.byType(LoginButton);

    testWidgets('Login Button Test', (tester) async {
      app.main();
      await tester.pumpAndSettle();
      await tester.tap(log);
      await tester.pumpAndSettle();
    });
  });
}
</code></pre>
",https://stackoverflow.com/questions/74782015/google-sign-in-integration-testing-flutter,"['flutter', 'flutter-test']",93,False,1,0
Integration testing in Asp.Net Core 6,"<p>I am trying to implement integration tests in Asp.Net Core 6. I am trying to use a different database for testing as well as overriding endpoint authentication using the AllowAnonymousFilter. I am following <a href=""https://timdeschryver.dev/blog/how-to-test-your-csharp-web-api/"" rel=""nofollow noreferrer"">this</a> turorial.</p>
<p>The goal is to override the &quot;ConnectionStrings&quot; property in appsettings.json in the main project with the contents in integrationsettings.json. The contents from integrationtests.json shows up in api.Configuration.Providers[0].Data, so reading of that file seems to work. The actual appsettings.json is formatted the same way but with real data. However, the test still runs with the standard database.</p>
<p>The AllowAnonymousFilter does not work. Since this endpoint requires authorization I get a 401 code. I am new to dotnet and I don't really know how to troubleshoot this...</p>
<p>Test:</p>
<pre><code>public class UserControllerIntegrationTests
    {    

        [Fact]
        public async Task Get_ReturnsUserFromDbAsync()
        {
            var api = new ApiWebApplicationFactory();
            var client = api.CreateClient();
            var response = await client.GetStringAsync(&quot;api/user?id=08da26ac-9de8-4cd8-8ca9-ce21f4952a6d&quot;);

            var result = JsonConvert.DeserializeObject&lt;UserDto&gt;(response);

            Assert.Equal(&quot;FirstName&quot;, result.FirstName);
        }        
    }
</code></pre>
<p>ApiWebApplicationFactory:</p>
<pre><code>internal class ApiWebApplicationFactory : WebApplicationFactory&lt;Program&gt;
    {
        public IConfiguration Configuration { get;  private set; }
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration(config =&gt; 
            {
                Configuration = new ConfigurationBuilder()
                    .AddJsonFile(&quot;integrationsettings.json&quot;)
                    .Build();

                config.AddConfiguration(Configuration);
            });

            builder.ConfigureTestServices(services =&gt;
            {
                MvcServiceCollectionExtensions.AddMvc(services, options =&gt; options.Filters.Add(new AllowAnonymousFilter()));
            });
        }
    }

</code></pre>
<p>integrationsettings.json:</p>
<pre><code>{
  &quot;ConnectionStrings&quot;: {
    &quot;Database&quot;: &quot;Server=testserver;Database=testserver;User=testserver;Password=testserver;&quot;
  }
}
</code></pre>
",https://stackoverflow.com/questions/72028006/integration-testing-in-asp-net-core-6,"['asp.net-core', 'integration-testing']",984,False,1,1
Flutter Widget Testing and Integration Testing,"<p>I have a small to mid sized application having several individual components (eg:- primary button) and several screens (eg:- login screen) where screens are a composition of these individual components and other flutter built in widgets.</p>
<p>Should I be writing widget tests for individual components to check edge cases like handling long texts and overflow issues on smaller or larger devices or write widget tests for entire screens? Here I'll only be testing the cosmetic behaviour of the application screens or widgets?</p>
<p>As for integration testing, I'm assuming it would test the entire functionality of the app, i.e. the screens using blocs (PS: I'm using flutter bloc and redux in conjunction)</p>
",https://stackoverflow.com/questions/73559110/flutter-widget-testing-and-integration-testing,"['flutter', 'testing', 'integration-testing', 'widget-test-flutter']",56,True,0,1
Cassandra integration testing in Java 17,"<p>How do you write integration tests for Cassandra in Java 17? I tried using cassandra-unit but had no success with it since seems like this project is dead and has the lack of Java 17 support. Can't use testcontainers because of some specificity of CI environment in my company. Any other options?</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/74391053/cassandra-integration-testing-in-java-17,"['java', 'cassandra', 'integration-testing']",161,False,0,0
Spring Boot integration testing with JUnit,"<pre><code>package com.example.demo;

import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {

        System.out.println(&quot;Hello !&quot;);

        // SpringApplication.run(DemoApplication.class, args);

        SpringApplication application = new SpringApplication(DemoApplication.class);
        application.setBannerMode(Banner.Mode.OFF);
        application.run(args);
    }

}
</code></pre>
<p>And test</p>
<pre><code>package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest(classes = DemoApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class DemoApplicationTests {

    @Test
    void contextLoads() {
    }

}
</code></pre>
<p>DemoApplicationTest seems to not use or be aware anythig about DemoApplication (@Spring BootApplication).</p>
<p>And I can't figure out if Maven project has multiple maven modules, how can they be included in test. Seem to me that Spring app does not even care about profiles defined in test.</p>
<p>Please point to relevant example or documentation: how to configure the test, so that it works like Spring Boot service where running on its own.</p>
<p>CommandLineRunner however gets executed also when running from test class:</p>
<pre><code>@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    public static void main(String[] args) {

        System.out.println(&quot;Hello !&quot;);

        // SpringApplication.run(DemoApplication.class, args);

        SpringApplication application = new SpringApplication(DemoApplication.class);
        application.setBannerMode(Banner.Mode.OFF);
        application.run(args);
    }

    @Autowired
    ApplicationContext applicationContext;

    @Override
    public void run(String... args) throws Exception {
        String[] beans = applicationContext.getBeanDefinitionNames();
        Arrays.sort(beans);
        for (String bean : beans) {
            System.out.println(bean);
        }
        System.out.println(&quot;.............................&quot;);
    }
}
</code></pre>
<p>But with Spring-banner .</p>
",https://stackoverflow.com/questions/74495220/spring-boot-integration-testing-with-junit,"['spring-boot', 'integration-testing', 'junit5']",118,False,0,1
.Net Framework 4.6.1 MVC integration testing,"<p>I am having a hard time trying to find sources of how can I run Integration Tests on my old Net Framework 4.6.1 MVC application. I tried a lot of guides I found, but none of them works for one reason or another.</p>
<p>My application is way to big to upgrade it to Net 6, which would make this testing much easier. I tried running OWIN TestServer, but it always results in 404 errors.</p>
<p>So I would like to know, how to approach integration testing on a old mvc? Am I following the right path searching for a solution with OWIN TestServer? Anything else I could try? Thought of Selenium too, but couldnt get it to start a fake server just to run the tests automatically, I needs a command to initialize my app on IIS, and we need the tests to run automatically through azure CI pipeline.</p>
<p>My app is very old so I tried removing Global.asax and using only the owin pipeline through Startup.cs, but it showed an error message &quot;No HTTP resource was found that matches the request uri&quot;, tried many fixes for Route configuration and such, no success. Tried running OWIN TestServer with both global.asax and startup.cs on the solution but did not work, tried Selenium too but it does not start a fake server automatically, preferably in memory just like the most recent versions of TestServer for net core+.</p>
<p>Tried also following this: <a href=""https://www.strathweb.com/2013/12/owin-memory-integration-testing/"" rel=""nofollow noreferrer"">https://www.strathweb.com/2013/12/owin-memory-integration-testing/</a></p>
",https://stackoverflow.com/questions/74522848/net-framework-4-6-1-mvc-integration-testing,"['c#', 'selenium', 'integration-testing', 'owin', 'testserver']",266,True,0,1
Spring Integration testing a Files.inboundAdapter flow,"<p>I have this flow that I am trying to test but nothing works as expected. The flow itself works well but testing seems a bit tricky.
This is my flow:</p>
<pre><code>@Configuration
@RequiredArgsConstructor
public class FileInboundFlow {
    private final ThreadPoolTaskExecutor threadPoolTaskExecutor;
    private String filePath;
    
    @Bean
    public IntegrationFlow fileReaderFlow() {
      
        return IntegrationFlows.from(Files.inboundAdapter(new File(this.filePath))
                                .filterFunction(...)
                                .preventDuplicates(false),
                        endpointConfigurer -&gt; endpointConfigurer.poller(
                             Pollers.fixedDelay(500)
                                .taskExecutor(this.threadPoolTaskExecutor)
                                .maxMessagesPerPoll(15)))
                .transform(new UnZipTransformer())
                .enrichHeaders(this::headersEnricher)
                .transform(Message.class, this::modifyMessagePayload)
                .route(Map.class, this::channelsRouter)
                .get();
    }

   private String channelsRouter(Map&lt;String, File&gt; payload) {
          boolean isZip = payload.values()
                .stream()
                .anyMatch(file -&gt; isZipFile(file));

        return isZip ? ZIP_CHANNEL : XML_CHANNEL; // ZIP_CHANNEL and XML_CHANNEL are PublishSubscribeChannel
    }
  

    @Bean
    public SubscribableChannel xmlChannel() {
        var channel = new PublishSubscribeChannel(this.threadPoolTaskExecutor);
        channel.setBeanName(XML_CHANNEL);
        return channel;
    }
    
    @Bean
    public SubscribableChannel zipChannel() {
        var channel = new PublishSubscribeChannel(this.threadPoolTaskExecutor);
        channel.setBeanName(ZIP_CHANNEL);
        return channel;
    }

   //There is a @ServiceActivator on each channel

    @ServiceActivator(inputChannel = XML_CHANNEL)
    public void handleXml(Message&lt;Map&lt;String, File&gt;&gt; message) {
        ...
    }

    @ServiceActivator(inputChannel = ZIP_CHANNEL)
    public void handleZip(Message&lt;Map&lt;String, File&gt;&gt; message) {
        ...
    }

   //Plus an @Transformer on the XML_CHANNEL

    @Transformer(inputChannel = XML_CHANNEL, outputChannel = BUS_CHANNEL)
    private List&lt;BusData&gt; xmlFileToIngestionMessagePayload(Map&lt;String, File&gt; xmlFilesByName) {
        return xmlFilesByName.values()
                .stream()
                .map(...)
                .collect(Collectors.toList());
    }
}
</code></pre>
<p>I would like to test multiple cases, the first one is checking the message payload published on each channel after the end of <code>fileReaderFlow</code>.
So I defined this test classe:</p>
<pre><code>@SpringBootTest
@SpringIntegrationTest
@ExtendWith(SpringExtension.class)
class FileInboundFlowTest {
    
    @Autowired
    private MockIntegrationContext mockIntegrationContext;

    @TempDir
    static Path localWorkDir;

    @BeforeEach
    void setUp() {
        copyFileToTheFlowDir(); // here I copy a file to trigger the flow
    }

   
    @Test
    void checkXmlChannelPayloadTest() throws InterruptedException {
       
       Thread.sleep(1000); //waiting for the flow execution

        PublishSubscribeChannel xmlChannel = this.getBean(XML_CHANNEL, PublishSubscribeChannel.class); // I extract the channel to listen to the message sent to it.

        xmlChannel.subscribe(message -&gt; {
            assertThat(message.getPayload()).isInstanceOf(Map.class); // This is never executed
        });
    }
}
</code></pre>
<p>As expected that test does not work because the <code>assertThat(message.getPayload()).isInstanceOf(Map.class);</code> is never executed.
After reading the <a href=""https://docs.spring.io/spring-integration/reference/html/testing.html"" rel=""nofollow noreferrer"">documentation</a> I didn't find any hint to help me solved that issue. Any help would be appreciated! Thanks a lot</p>
",https://stackoverflow.com/questions/72104590/spring-integration-testing-a-files-inboundadapter-flow,"['testing', 'spring-integration', 'integration-testing', 'spring-test', 'spring-integration-dsl']",108,True,0,1
Groovy integration testing with executor service,"<p>I want to test optimistic locking on my resource. To do that I want to call my endpoint let's say 10 times and assert that in my database I only get 1 record. My test:</p>
<pre><code>given:
def request = someRequest()

when:
ExecutorService executorService = Executors.newFixedThreadPool(10)
CountDownLatch latch = new CountDownLatch(10)
10.times {
    executorService.execute(() -&gt; {
        restTemplate.postForEntity(localUri() + &quot;/resource&quot;, request, String.class)
        latch.countDown()
    })
}
latch.await()

then:
storage.findAll().size() == 1
</code></pre>
<p>Everytime I run this test I see that there are exactly 5 attempts while I expect 10 calls. As a database I use PostgreSQL image. I'm not an expert with concurrency, do you know where is the problem?</p>
",https://stackoverflow.com/questions/73276439/groovy-integration-testing-with-executor-service,"['java', 'testing', 'groovy', 'concurrency', 'integration']",50,False,0,0
Spring Boot Integration Testing - TestRestTemplate null,"<p>I am using <strong>Spring Boot 2.1.2</strong> and <strong>junit-jupiter-api-5.3.2</strong> and I am doing integration testing.</p>
<p>My test case is this:</p>
<pre><code>import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.ril.vms.hawkeye.otp.dto.SendOTPRequestDTO;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@SpringBootTest(classes = MyApplication.class,
        webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles(&quot;sit&quot;)
public class OtpControllerIntegrationTest
{
    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void sendOtpTest() throws Exception {

        SendOTPRequest otpRequest = new SendOTPRequestDTO();
        otpRequest.setClientId(&quot;default2&quot;);
        otpRequest.setTag(&quot;tag&quot;);
        otpRequest.setMobileNumber(&quot;9999999999&quot;);
        ResponseEntity&lt;String&gt; responseEntity = this.restTemplate
                .postForEntity(&quot;http://localhost:&quot; + port + &quot;/sendOtp&quot;, otpRequest, String.class);
        assertEquals(201, responseEntity.getStatusCodeValue());

    }
}
</code></pre>
<p>But I am getting <code>java.lang.NullPointerException</code> at below line.</p>
<p><code>ResponseEntity&lt;String&gt; responseEntity = this.restTemplate ...</code></p>
",https://stackoverflow.com/questions/71154294/spring-boot-integration-testing-testresttemplate-null,"['java', 'spring-boot', 'spring-test']",797,False,0,2
Code actions provider API for integration testing,"<p>I'm writing a CodeActions provider in <a href=""https://github.com/google/wireit/pull/174"" rel=""nofollow noreferrer"">https://github.com/google/wireit/pull/174</a> and using an integration testing setup similar to that documented at <a href=""https://code.visualstudio.com/api/working-with-extensions/testing-extension"" rel=""nofollow noreferrer"">https://code.visualstudio.com/api/working-with-extensions/testing-extension</a>.</p>
<p>I can't seem to find any APIs to get the code actions that my language server provides, nor to get VSCode to apply a code action so that I may assert on the effects.</p>
",https://stackoverflow.com/questions/72119902/code-actions-provider-api-for-integration-testing,"['visual-studio-code', 'vscode-extensions']",148,False,2,0
Setter in DTO just for integration testing?,"<p>I couldn't find the info I'm looking for hence posting here for suggestion and getting to know better approach.</p>
<p>I have an immutable DTO object like:</p>
<pre><code>import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDate;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AccountCreateDto {
    String name;
    Long accountNo;
    String email;
    LocalDate dob;
    String address;
    Long phone;
    Integer amount;
    LocalDate accountOpeningDate;
    Integer installmentAmount;
    Integer totalAmount;
    LocalDate installmentPaidDate;

    @JsonCreator
    public AccountCreateDto(
            @JsonProperty(&quot;name&quot;) String name,
            @JsonProperty(&quot;accountNo&quot;) Long accountNo,
            @JsonProperty(&quot;email&quot;) String email,
            @JsonProperty(&quot;dob&quot;) LocalDate dob,
            @JsonProperty(&quot;address&quot;) String address,
            @JsonProperty(&quot;phone&quot;) Long phone,
            @JsonProperty(&quot;amount&quot;) Integer amount,
            @JsonProperty(&quot;accountOpeningDate&quot;) LocalDate accountOpeningDate,
            @JsonProperty(&quot;installmentAmount&quot;) Integer installmentAmount,
            @JsonProperty(&quot;totalAmount&quot;) Integer totalAmount,
            @JsonProperty(&quot;installmentPaidDate&quot;) LocalDate installmentPaidDate
    ) {
        this.name = name;
        this.accountNo = accountNo;
        this.email = email;
        this.dob = dob;
        this.address = address;
        this.phone = phone;
        this.amount = amount;
        this.accountOpeningDate = accountOpeningDate;
        this.installmentAmount = installmentAmount;
        this.totalAmount = totalAmount;
        this.installmentPaidDate = installmentPaidDate;
    }
    // removing getters for brevity
}
</code></pre>
<p>Now I'm working on an integration test with testcontainer where I want the <code>accountOpeningDate</code> and <code>installmentPaidDate</code> to be dynamic value hence in order to set these values from Integration Tests, is it a good idea to add only 2 setters to this DTO which is only to be used for Integration Tests like below?</p>
<pre><code>    public void setAccountOpeningDate(LocalDate accountOpeningDate) {
        this.accountOpeningDate = accountOpeningDate;
    }

    public void setInstallmentPaidDate(LocalDate installmentPaidDate) {
        this.installmentPaidDate = installmentPaidDate;
    }
</code></pre>
<p>Or is there a better approach than this? Looking for recommendations.</p>
<p>TA</p>
",https://stackoverflow.com/questions/71429688/setter-in-dto-just-for-integration-testing,"['java', 'immutability', 'dto', 'jackson-databind']",122,True,1,1
Celery integration testing with pytest and monkeypatching,"<p>I'm trying to run some simple integration tests with Python 3.9.5, Celery 5.2.6, pytest 7.1.0 and FastAPI on docker.</p>
<p>Project structure:</p>
<pre><code>  📦
  ┣ 📂app
  ┣ ┣ 📂api
  ┣ ┣ ┣ 📂routes
  ┣ ┣ ┣ ┗ 📜celery.py
  ┣ ┗ 📂services
  ┣    ┗  📜operations.py
  ┣ ┣ 📂celery
  ┣ ┃ ┣ 📜tasks.py
  ┣ ┃ ┣ 📜utils.py
  ┣ ┃ ┗ 📜worker.py
  ┣ 📂tests
     ┣ 📜conftest.py
     ┗ 📜test_celery.py
</code></pre>
<p>The celery container is run with: <code>command: celery -A app.celery.worker:celery_app worker --loglevel INFO --logfile=./celery.log --hostname=worker_1_dev@%h</code>, and works as expected.</p>
<p>And the web server container with: <code>command: uvicorn app.api.server:app </code></p>
<p>Both have bind mounts of the complete project directory.</p>
<p>How should the celery fixtures be defined so that I can monkeypatch <code>operations.py</code> or the task itself?
Right now when my tests run the actual worker container picks up the real tasks and runs them, so I guess the problem lies
in the fixtures. Setting always eager does not change the behaviour, and isn't recommended either.
The worker and app instance fixtures return objects along the lines of:</p>
<pre><code>celery_worker: gen44@XXX
celery_app: &lt;Celery celery.tests at XXX&gt;
</code></pre>
<p>which seems correct, they're not the actual worker container or the <code>app.celery.worker:celery_app</code> instance.
I've tried messing with other fixtures in the docs, mocking approaches, etc. but I've spent way too much time on this and tests just
don't seem to work. Like I said, the actual container executes tasks as expected.</p>
<p><strong>app/api/routes/celery.py</strong></p>
<pre class=""lang-py prettyprint-override""><code>class TaskStatus(CoreModel):
    task_id: str
    task_status: Optional[str]
    task_result: Optional[Any]

@router.post(
  &quot;/operations/add-with-factor&quot;,
  name=&quot;celery:add-times-factor&quot;,
)
def add_times_factor(
  x: int = Query(..., gt=0),
  y: int = Query(..., gt=0),
):
  task = celery_app.send_task(
    &quot;add_times_factor&quot;,
    args=[x, y],
  )
  return {&quot;task_id&quot;: task.id}


@router.get(
    &quot;/tasks/{task_id}/&quot;,
    name=&quot;celery:get-task-status&quot;,
    response_model=TaskStatus,
)
def get_status(task_id):
    task_result = AsyncResult(task_id)
    return TaskStatus(
        task_id=task_id,
        task_status=task_result.status,
        task_result=task_result.result,
    )
</code></pre>
<p><strong>tests/conftest.py</strong></p>
<pre class=""lang-py prettyprint-override""><code>@pytest.fixture(scope=&quot;session&quot;)
def celery_enable_logging():
    return True

@pytest.fixture(scope=&quot;session&quot;)
def celery_config():
    return {
        &quot;broker_url&quot;: &quot;memory://&quot;,
        &quot;result_backend&quot;: &quot;rpc://&quot;,
        &quot;task_always_eager&quot;: True, # to be removed
    }

@pytest.fixture(scope=&quot;session&quot;)
def celery_worker_parameters():
    return {
        &quot;perform_ping_check&quot;: False,
    }

@pytest.fixture(scope=&quot;session&quot;)
def celery_includes():
    return [&quot;app.celery.tasks&quot;]

    ...
</code></pre>
<p><strong>app/celery/worker.py</strong></p>
<pre class=""lang-py prettyprint-override""><code>import os
from celery import Celery

celery_app = Celery(&quot;app.celery.worker&quot;)
celery_app.conf.task_serializer = &quot;json&quot;
celery_app.conf.result_serializer = &quot;json&quot;
celery_app.conf.accept_content = [&quot;application/json&quot;, &quot;application/x-python-serialize&quot;]
celery_app.conf.broker_url = os.environ.get(&quot;CELERY_BROKER_URL&quot;, &quot;redis://localhost:6379&quot;)
celery_app.conf.result_backend = os.environ.get(&quot;CELERY_RESULT_BACKEND&quot;, &quot;redis://localhost:6379&quot;)
celery_app.autodiscover_tasks([&quot;app.celery&quot;])
</code></pre>
<p><strong>app/celery/tasks.py</strong></p>
<pre class=""lang-py prettyprint-override""><code>from app.services.operations import OperationService

def async_to_sync(func):
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        return asyncio.run(func(*args, **kwargs))

    return wrapped

@shared_task(name=&quot;add_times_factor&quot;)
@async_to_sync
async def add_times_factor_task(x, y):
    operation_service = OperationService()
    result = await operation_service.add_times_factor(x, y)
    return {&quot;result&quot;: result}

</code></pre>
<p><strong>app/services/operations.py</strong></p>
<pre class=""lang-py prettyprint-override""><code>FACTOR = 2

class OperationService:
    async def add_times_factor(self, x, y):
        await something
        return (x + y) * FACTOR
</code></pre>
<p><strong>tests/test_celery.py</strong></p>
<pre class=""lang-py prettyprint-override""><code>import pytest
import app.services.operations as operations
pytestmark = pytest.mark.asyncio

class TestCelery:
    async def test_add_times_factor(self,
        celery_worker,
        celery_app: Celery,
        monkeypatch,
    ):
        monkeypatch.setattr(operations, &quot;FACTOR&quot;, 20) # ignored right now

        celery_app.set_current()
        res = await superuser_client.post(app.url_path_for(&quot;celery:add-times-factor&quot;), params={&quot;x&quot;: 1, &quot;y&quot;: 2})

        task_succeeded = False
        while not task_succeeded:
            task_status_res = await superuser_client.get(app.url_path_for(&quot;celery:get-task-status&quot;, task_id=task.id))
            assert task_status_res.status_code == HTTP_200_OK
            task_succeeded = task_status_res.json()[&quot;task_status&quot;] == &quot;SUCCESS&quot;
            await asyncio.sleep(0.5)

        assert json.loads(task_status_res.json()[&quot;task_result&quot;])[&quot;result&quot;] == 60 # fail 6 == 60


</code></pre>
",https://stackoverflow.com/questions/72129975/celery-integration-testing-with-pytest-and-monkeypatching,"['python-3.x', 'mocking', 'celery', 'pytest', 'fastapi']",1051,False,1,0
Spring Integration testing with MockMvc - service injection,"<p>I'm trying to make an integration test going all the way from the top (controller) down to the repositories (mocked). I'm having issue with getting an actual service (not mock) injected into a controller and mocking the service's repositories. Most examples I've seen either call the endpoint via MockMvc and test the controller that contains all the logic, so no services, or they just mock the service and return a set response which I see no point in testing at all. My classes work as such: Controller contains the service which contains the repository</p>
<p>Currently I have the following test class for that:</p>
<pre><code>@WebMvcTest(PatientRecordController.class)
public class PatientRecordControllerTests {

    @Autowired
    MockMvc mockMvc;

    @Autowired
    ObjectMapper mapper;

    @MockBean
    PatientRecordService patientRecordService;

    @Test
    public void createRecord_WhenDtoValid_CreateRecord() throws Exception {
        PatientRecordDto recordDto = PatientRecordDto.builder()
            .name(&quot;John Doe&quot;)
            .age(47)
            .address(&quot;New York USA&quot;)
            .build();

        PatientRecord record = ModelMapperUtil.convertTo(recordDto, PatientRecord.class);
        Mockito.when(patientRecordService.saveRecord(recordDto)).thenReturn(record);

        MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.post(&quot;/patient&quot;)
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
            .content(this.mapper.writeValueAsString(recordDto));

        mockMvc.perform(mockRequest)
            .andExpect(status().isOk())
            .andExpect(jsonPath(&quot;$&quot;, notNullValue()))
            .andExpect(jsonPath(&quot;$.name&quot;, is(&quot;John Doe&quot;)));
    }
}
</code></pre>
<p>What I would like to be able to do is something akin to following:</p>
<pre><code>@Autowired
@InjectMocks
private PatientRecordService patientRecordService;

@Mock
private PatientRecordRepository patientRecordRepository;
</code></pre>
<p>Theoretically, with this I'd get a bean of <code>PatientRecordService</code> that has <code>PatientRecordRepository</code> mock injected, and then instead of doing</p>
<pre><code>Mockito.when(patientRecordService.saveRecord(recordDto)).thenReturn(record);
</code></pre>
<p>I could do</p>
<pre><code>Mockito.when(patientRecordRepository.save(recordDto)).thenReturn(record);
</code></pre>
<p>And then the whole logic inside of the service would be tested and only repository response would be mocked. Obviously this is not how it works, so how would I go about in achieving this?</p>
",https://stackoverflow.com/questions/74109840/spring-integration-testing-with-mockmvc-service-injection,"['java', 'spring', 'mockito', 'integration-testing', 'mockmvc']",474,True,0,1
Springboot database URL change during integration testing,"<p>I am doing integration testing, and have 2 databases to test my project against. Rather than creating 2 profiles, is there a quick and easy way where I create 2 integration test classes, and one to test against the database originally written on my main profile, and another where I add some sort of annotation that changes the database url programatically, but otherwise keeps everything else the same, and run my tests through there?</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/74396107/springboot-database-url-change-during-integration-testing,"['spring', 'spring-boot', 'profile', 'spring-profiles', 'spring-properties']",154,True,0,2
How to test huge methods? (Integration Testing?),"<p>I am working on a dated system. It consists out of huge methods with sometimes thousands of lines. Most methods do multiple things.
There are no comments, there are no tests.
I have realized that testing is quite good to ensure that I find errors faster (obviously..). It´s quite easy to write some Unit Tests on smaller or at least specialized methods, but I dont know how to test bigger ones.</p>
<p>At the moment I am testing database methods with commit/rollback, which seems to work.</p>
<p>I would now like to know:</p>
<p>-&gt;How do I rollback the database from other modules?
When I am doing it directly with the database methods it´s easy, but what if I am in the UI, with: UI (code)-&gt;logic-&gt;API-&gt;database ? How can I ensure that the database reverts back? ...or since this is only the dev database, how to let the data in the db, without having to always input new values for the tests.</p>
<p>-&gt;How do I test huge methods?</p>
<p>I have in the UI very few methods, which do a LOT of things. Doing some things in the UI, taking in user input, validating it,starting other modules, querying the database, changing UI, a with dozen different cases depending in what case we are.
How do I test those and the modules behind them? The problem is that they often are dependent on other complex objects, be it as parameter or from other modules or data in the database, which is only added to it for this one session.</p>
<p>Would it be a useful idea to setup UI tests instead of testing the UI Code? However, I have never done UI tests and I don´t get time for any tests at all...</p>
<p>..I am not allowed to Refactor anything...</p>
",https://stackoverflow.com/questions/70778714/how-to-test-huge-methods-integration-testing,"['java', 'c#', 'unit-testing', 'testing', 'integration-testing']",76,False,0,0
Integration Testing for Pulumi Script in Python,"<p>I have a Pulumi script in Python for a simple service of AWS. I have designed successful unit tests for this script and I'm wondering how to design Integration Tests for the same.
Looking for any possible leads..</p>
",https://stackoverflow.com/questions/73123011/integration-testing-for-pulumi-script-in-python,"['python', 'integration-testing']",44,False,0,0
Using WebClient for Spring Boot integration testing,"<p>I'm trying to migrate some integration tests of a Spring Boot application from <code>RestTemplate</code> to <code>WebClient</code>. Currently, the tests use an autowired instance of <code>TestRestTemplate</code></p>
<pre><code>@Autowired
private TestRestTemplate restTemplate;
</code></pre>
<p>When the tests are run, <code>restTemplate</code> is configured to use the same base URL and (randomly chosen) port that the server runs on.</p>
<p>In one of my tests, I login and save the authorization response header value for use in subsequent API calls. I tried migrating this to <code>WebClient</code> like so</p>
<pre><code>WebClient webClient = WebClient.create()

var authResult = webClient.post()
    .uri(&quot;/api/authenticate&quot;)
    .contentType(MediaType.APPLICATION_JSON)
    .bodyValue(new LoginDetails(username, password))
    .retrieve()
    .toBodilessEntity()
    .block();

// save the token that was issued and use it for subsequent requests
this.authHeader = authResult.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
</code></pre>
<p>But when I create the <code>WebClient</code> instance like this it is not configured to use the same port as the application.</p>
<p>I tried instead to use a dependency-injected instance of <code>TestWebClient</code></p>
<pre><code>@Autowired
private WebTestClient webTestClient;
</code></pre>
<p>This does connect the web client to the server (same base URL and port), however the <code>WebTestClient</code> API has quite a different API to <code>WebClient</code>. Specifically, it only seems to allow the properties of the response to be asserted, e.g. you can assert that a particular response header value exists, but there's no way to save that header's value.</p>
<pre><code>var authResult = webTestClient.post()
    .uri(&quot;/api/authenticate&quot;)
    .contentType(MediaType.APPLICATION_JSON)
    .bodyValue(new LoginDetails(username, password))
    .exchange()
    .expectHeader()
    .exists(HttpHeaders.AUTHORIZATION);
</code></pre>
<p>Is there a way to either:</p>
<ul>
<li>Create a <code>WebClient</code> instance that is configured to use the same base URL and port as the server</li>
<li>Create a <code>WebTestClient</code> instance and <em>access</em> the response properties (rather than just asserting them)</li>
</ul>
",https://stackoverflow.com/questions/71396773/using-webclient-for-spring-boot-integration-testing,"['java', 'spring', 'spring-boot', 'integration-testing']",2235,True,0,1
Passing claims into HandleAuthenticateAsync for integration testing,"<p>While following Microsoft's ASP.NET Core guide for integration testing authentication, I have the following test built for Authentication:</p>
<pre><code>[Fact]
public async Task Get_SecurePageIsReturnedForAnAuthenticatedUser()
{
    // Arrange
    var client = _factory.WithWebHostBuilder(builder =&gt;
        {
            builder.ConfigureTestServices(services =&gt;
            {
                services.AddAuthentication(&quot;Test&quot;)
                    .AddScheme&lt;AuthenticationSchemeOptions, TestAuthHandler&gt;(
                        &quot;Test&quot;, options =&gt; {});
            });
        })
        .CreateClient(new WebApplicationFactoryClientOptions
        {
            AllowAutoRedirect = false,
        });

    client.DefaultRequestHeaders.Authorization = 
        new AuthenticationHeaderValue(&quot;Test&quot;);

    //Act
    var response = await client.GetAsync(&quot;/SecurePage&quot;);

    // Assert
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
</code></pre>
<p>What I want to do, is use the [Theory] option instead of [Fact] to test multiple Authentications so it will look like this:</p>
<pre><code>[Theory]
[InlineData(&quot;TestAuth1&quot;,&quot;12345&quot;)]
[InlineData(&quot;TestAuth2&quot;,&quot;23456&quot;)]
[InlineData(&quot;TestAuth3&quot;,&quot;34567&quot;)]
public async Task Get_SecurePageIsReturnedForAnAuthenticatedUser(string claim, string claimsIdentity)
{
   var claim = new Claim(claim, claimsIdentity);

.
.
.
</code></pre>
<p>However I'm not sure how to pass claim to TestAuthHandler through AddScheme&lt;AuthenticationSchemeOptions, TestAuthHandler&gt;</p>
<p>Here is the given TestAuthHandler</p>
<pre><code>public class TestAuthHandler : AuthenticationHandler&lt;AuthenticationSchemeOptions&gt;
{
    public TestAuthHandler(IOptionsMonitor&lt;AuthenticationSchemeOptions&gt; options, 
        ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
        : base(options, logger, encoder, clock)
    {
    }

    protected override Task&lt;AuthenticateResult&gt; HandleAuthenticateAsync()
    {
        var claims = new[] { new Claim(ClaimTypes.Name, &quot;Test user&quot;) };
        var identity = new ClaimsIdentity(claims, &quot;Test&quot;);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, &quot;Test&quot;);

        var result = AuthenticateResult.Success(ticket);

        return Task.FromResult(result);
    }
}
</code></pre>
<p>I would like to replace the claims variable in HandleAuthenticaAsync() with the claim passed into Get_SecurePageIsReturnedForAnAuthenticatedUser(Claim claim)</p>
<p>As a note they do have to be tested individually since my current authentication will pass as long as one correct authentication exists in the HandleAuthenticateAsync claims variable.</p>
<p>Thank you for any help provided.</p>
",https://stackoverflow.com/questions/73830338/passing-claims-into-handleauthenticateasync-for-integration-testing,"['c#', 'asp.net-core', 'integration-testing']",198,False,0,1
Desktop window size in flutter integration testing,"<p>Now that the Desktop embedding in flutter is almost stable it is interesting to perform the integration testing directly on the OS you are using during the development (instead of initialize every time an emulator and wait until is ready). It should also be interesting in the CI pipeline. Unfortunatly I can't find a way to set the window size dimension when I perform the test. This is needed for adaptive apps.</p>
<p>I tried with:</p>
<pre class=""lang-dart prettyprint-override""><code>tester.binding.window.physicalSizeTestValue = const Size(300, 300);
</code></pre>
<p>but it didn't worked for me</p>
",https://stackoverflow.com/questions/71814768/desktop-window-size-in-flutter-integration-testing,"['flutter', 'testing', 'integration-testing']",239,True,0,2
Flutter Integration testing failing when moving between tests,"<p>Currently in my project I am adding multiple integration tests separated in different files. When trying to run all tests running using <code>flutter test integration test</code>, it gives me this error when moving between tests</p>
<p><code>Error waiting for a debug connection: The log reader stopped unexpectedly, or never started.</code>
<code>TestDeviceException(Unable to start the app on the device.)</code></p>
<p>This error never occurs when running it on an iOS or Android emulator, but as this is a desktop application, I need to get the tests building on Linux which is where the error is occurring.</p>
",https://stackoverflow.com/questions/71674018/flutter-integration-testing-failing-when-moving-between-tests,"['flutter', 'flutter-integration-test']",647,False,2,2
FlutterFire: Integration testing against Firebase Emulator Suite / FirebaseStorage,"<p>Production wise, my code accesses live Storage successfully.</p>
<p>But implementing tests with FlutterFire against Firebase Emulator Suite fails:</p>
<p><strong>Error</strong></p>
<p><code>MissingPluginException(No implementation found for method Storage#useEmulator on channel plugins.flutter.io/firebase_storage)</code></p>
<p><strong>Code</strong></p>
<pre class=""lang-dart prettyprint-override""><code>Future&lt;void&gt; init() async {
  debugDefaultTargetPlatformOverride = TargetPlatform.android;
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform, // this is the LIVE config!
  );
  FirebaseStorage.instance.useStorageEmulator('localhost', 9199);
}

void main() async {
  await init();

  test('just dummy test', () async {
    final metadata = SettableMetadata(contentType: &quot;text/plain&quot;);
    final storageRef = FirebaseStorage.instance.ref();
    const path = 'test.txt';
    const payload = 'bla bla bla';
    try {
      await storageRef
          .child(path)
          .putString(payload, metadata: metadata, format: PutStringFormat.raw);
      expect(true, true); 
    } on FirebaseException catch (error) {
      print(error);
    }
  });
}
</code></pre>
<p><strong>Question</strong></p>
<p>How to provide a proper <code>firebase_storage</code> implementation for testing from the command line (<code>flutter test test.dart</code>) ?</p>
",https://stackoverflow.com/questions/71988381/flutterfire-integration-testing-against-firebase-emulator-suite-firebasestora,"['flutter', 'unit-testing', 'firebase-storage']",105,False,2,0
override virtual with Xunit ICLassFixture WebAppliationFactory Integration Testing,"<p>I don't work with xunit very often and am trying to understand how to go about overriding a method in my webAppliationFactory class that gets inherited in my fixture. I am needing to mock a service in my startup class and it would be awesome if I could override the response per class/test. I don't really want to get into a debate on why I want to mock a service in an integration test. I just want to.</p>
<p>My injection setup</p>
<pre><code>public class CreateWebAppFactory&lt;TStartup&gt;
: WebApplicationFactory&lt;TStartup&gt; where TStartup : class 
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
    builder.ConfigureServices(services =&gt;
    {
        var svc = services.SingleOrDefault(d =&gt; d.ServiceType == typeof(INeedToMockThis));
        services.Remove(svc);
        var svcMock= new Mock&lt;INeedToMockThis&gt; ();
        svcMock.Setup(x =&gt; x.Foo(It.IsAny&lt;long&gt; ()))
            .ReturnsAsync(TheMethodIwantToOverride()); &lt;-- How can I manage this? 
        services.AddScoped(x =&gt; svcMock.Object);
        ...
    }
protected virtual int TheMethodIwantToOverride()
 {
return 1;
}
</code></pre>
<p>My test</p>
<pre><code> public class GivenSomethingNeedsToBeTested: IClassFixture&lt;CreateWebAppFactory&lt;Startup&gt;&gt;
 
 private readonly CreateWebAppFactory&lt;Startup&gt; _factory;
 private HttpClient _client;

 public GivenSomethingNeedsToBeTested(CreateWebAppFactory&lt;Startup&gt; factory)
{
    _factory = factory;
    _client = factory.CreateClient();
}

public override int TheMethodIwantToOverride() &lt;-- This is not available to me to use.. 
{
    return 2; 
}
</code></pre>
<p>I hope this explanation is sufficient? Is this not possible?</p>
",https://stackoverflow.com/questions/72382020/override-virtual-with-xunit-iclassfixture-webappliationfactory-integration-testi,"['c#', 'polymorphism', 'integration-testing', 'xunit']",90,False,1,0
Can&#39;t setup apm-integration-testing for debugging kibana,"<p>I'm following the kibana developer's guide, and I want to debug the application using APM.
so I'm following this guide: <a href=""https://www.elastic.co/guide/en/kibana/master/kibana-debugging.html"" rel=""nofollow noreferrer"">https://www.elastic.co/guide/en/kibana/master/kibana-debugging.html</a> .</p>
<p>first I clone the apm-integration-testing repo, then I run <code>./scripts/compose.py start master --no-kibana</code></p>
<p>however after running the above code, I get this error:<code>Please start Docker before running the apm-integration-testing. </code></p>
<p>I understand that running apm requires docker and docker-compose, but there is no clear documentation on how to get it all to run.</p>
<p>If someone has setup apm-integration-testing successfully I can use some help.</p>
<p>Edit:
Here is the compose.py file:</p>
<pre><code>#!/usr/bin/env python
&quot;&quot;&quot;CLI for starting a testing environment using docker-compose.&quot;&quot;&quot;
from __future__ import print_function

import logging
import os
import subprocess
import sys

from modules.cli import LocalSetup


def main():
    # Enable logging
    logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s')
    setup = LocalSetup(sys.argv[1:])
    setup()


def verify_if_docker_is_installed():
    try:
        subprocess.check_output(
            'docker ps', stderr=open(os.devnull, 'w'), shell=True).decode('utf8').strip()
    except subprocess.CalledProcessError:
        print(&quot;Please start Docker before running the apm-integration-testing.&quot;)
        sys.exit(1)


if __name__ == '__main__':
    verify_if_docker_is_installed()
    main()
</code></pre>
",https://stackoverflow.com/questions/73687376/cant-setup-apm-integration-testing-for-debugging-kibana,"['docker', 'elasticsearch', 'docker-compose', 'kibana', 'elastic-apm']",65,True,0,1
Semi-integration testing using mocks and application context,"<p>I need to write an e2e test on REST level, that sends real requests. So I want to use application context instead of mocking beans.</p>
<p><code>RestController.class</code> has an autowired <code>MyService.class</code>, and this <code>MyService.class</code> is dependent on two repository classes. So I tried to mock <code>repositories</code> and inject them in the real <code>Service</code> in the following way:</p>
<pre><code>@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = MyService.class)
@AutoConfigureMockMvc
class MyControllerTest {

  @Mock private MyRepository repository;
  @Mock private AnotherRepository anotherRepository;
  @Autowired @InjectMocks private MyService service;
  @InjectMocks private MyController controller;

  @RepeatedTest(1)
  void someTest() throws Exception {
    MockHttpServletResponse response =
        mvc.perform(...); assertThat(...);
  }
}
</code></pre>
<pre><code>@Service
@RequiredArgsConstructor
public class MyService {
  private final MyRepository repository;
  private final AnotherRepository another; ...}
</code></pre>
<p>But I get the following error:
<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myRepository'</code></p>
<p>I also tried to use <code>@ContextConfiguration(classes = {MyConfig.class })</code> with no success:</p>
<pre><code>@EnableWebMvc
@Configuration
public class MyConfig {
  @Autowired private MyService service;
  @Mock private MyRepository repository;
  @Mock private AnotherRepository another;
}
</code></pre>
<p>Is there something I'm missing?</p>
",https://stackoverflow.com/questions/73352803/semi-integration-testing-using-mocks-and-application-context,"['java', 'spring', 'spring-boot', 'integration-testing', 'spring-boot-test']",56,True,0,2
Quarkus integration testing against running application with HTTPS,"<p>I would like to use Integration-Tests with the Quarkus feature &quot;testing against running application&quot;, as described in the <a href=""https://quarkus.io/guides/getting-started-testing#executing-against-a-running-application"" rel=""nofollow noreferrer"">documentation</a>.</p>
<p>I managed to make it work on local running instances, but I would like to test against our server which only accepts HTTPS requests.
Setting <code>quarkus.http.test-host</code> and <code>quarkus.http.test-port</code> as described in the documentation automatically leads to a HTTP request. I skimmed through the documentation of <a href=""https://quarkus.io/guides/all-config"" rel=""nofollow noreferrer"">all configuation options</a>, but could not find additional parameters that would help in this case.</p>
<p>Does anyone know how I could configure or customize the tests so that they would use HTTPS?</p>
",https://stackoverflow.com/questions/74012124/quarkus-integration-testing-against-running-application-with-https,"['integration-testing', 'quarkus']",148,False,0,0
Setting headers for JEST integration testing on Apollo,"<p>Hi i'm facing an error in my code, this is the code.
I am not able to set the headers inside executeOperation function of Apollo as i need accessToken to run next mutation or a query.
loginToken is being set and i can retrieve it's value . But when i set headers before query &quot;getClientConfiguration&quot; it gives me unauthorized response because of header.</p>
<pre><code>const { createServerWithSchema } = require('../../gql/server')

let loginToken;

describe('Space test suite', () =&gt; {
  
  it('returns login token', async () =&gt; {
    const testServer = await createServerWithSchema()

    const result = await testServer.executeOperation({
        query: `
        query loginFromEmail{
            loginFromEmail(
                email:&quot;qa+stadiumexperiencehost@pavemint.com&quot;
                password:&quot;Password1&quot;
            )
            {
                accessToken
            }
        }
    `
    })

    
    const { accessToken } = result.data.loginFromEmail
    loginToken = accessToken
    expect(result.errors).toEqual(undefined)
  })


  it('returns clientConfiguration', async () =&gt; {
    const testServer = await createServerWithSchema()

    const result = await testServer.executeOperation({
        http: {
            headers : {
                &quot;Authorization&quot;: `Bearer ${loginToken}`
            }
        },
        query: 'query getClientConfiguration { getClientConfiguration { GOOGLE_MAPS_API_KEY } }',
    })
    
    console.log(&quot;result&quot;, result)
  })
})
</code></pre>
",https://stackoverflow.com/questions/71664389/setting-headers-for-jest-integration-testing-on-apollo,['jestjs'],204,False,0,1
Use wsdl to create server for integration testing,"<p>I have a WSDL file from a server that implements some webservices. I have created client-code with Axis2, but want to build some integration tests that deal with server-timouts.</p>
<p>To do that, I want to create a server-stub and have the methods just <code>sleep</code> longer than the configured client-timeout.</p>
<p>Is there an easy way to generate an scaffold-like server running the services from the WSDL?</p>
",https://stackoverflow.com/questions/73384864/use-wsdl-to-create-server-for-integration-testing,"['java', 'maven', 'server', 'wsdl', 'code-generation']",125,True,0,1
"Integration Testing with GraphQL (Nexus, Apollo), Prisma, and PostgreSQL","<p>I am trying to follow <a href=""https://nexusjs.org/docs/getting-started/tutorial/chapter-testing-with-prisma"" rel=""nofollow noreferrer"">this tutorial</a> to establish integration tests on our web application. Our stack currently includes Nexus, Next, Apollo, Prisma, and PostgreSQL.</p>
<p>I am using ApolloClient in place of <code>GraphQLClient</code> from <code>graphql-request</code>, I opted to use <code>ApolloClient</code> instead, especially since our web application is server less.</p>
<p>This is currently what I have inside the <code>helper.ts</code>, and the <code>ApolloClient</code> does work when I execute mutations. However, after executing a mutation on ApolloClient and checking if the data persists through Prisma, I get a <code>null</code> value.</p>
<p>Did I do these adjustments correctly? I am definitely missing something if Prisma is not querying correctly. Maybe there is a disconnect here between ApolloClient and Prisma or ApolloClient and the database? Any help would be much appreciated.</p>
<p>All of the code is below.</p>
<p><strong>helper.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>function graphqlTestContext() {
 let serverInstance: ServerInfo | null = null;

 return {
   async before() {
     const rootUrl = getRootUrl();

     const httpLink = createHttpLink({
       uri: rootUrl + &quot;api/graphql&quot;,
       credentials: &quot;include&quot;,
       fetch
     });
   
     const client = new ApolloClient({
       // ssrMode: typeof window === &quot;undefined&quot;,
       link: httpLink,
       cache: new InMemoryCache(),
     });

     return client;
   },
   async after() {
     serverInstance?.server.close()
   },
 }
}

function prismaTestContext() {
 const prismaBinary = join(__dirname, '../../', 'node_modules', '.bin', 'prisma');
 let schema = '';
 let databaseUrl = '';
 let prismaClient: null | PrismaClient = null;

 return {
   async before() {
     // Generate a unique schema identifier for this test context
     schema = `test_${nanoid()}`;
     // Generate the pg connection string for the test schema
     databaseUrl = `${process.env.ROOT_DB_URL}/testing?schema=${schema}`;

     // Set the required environment variable to contain the connection string
     // to our database test schema
     process.env.DATABASE_URL = databaseUrl;

     // Run the migrations to ensure our schema has the required structure
     execSync(`${prismaBinary} migrate dev`, {
       env: {
         ...process.env,
         DATABASE_URL: databaseUrl,
       },
     });

     // Construct a new Prisma Client connected to the generated Postgres schema
     prismaClient = new PrismaClient();

     return prismaClient;
   },
   async after() {
     // Drop the schema after the tests have completed
     const client = new Client({
       connectionString: databaseUrl,
     });
     await client.connect();
     await client.query(`DROP SCHEMA IF EXISTS &quot;${schema}&quot; CASCADE`);
     await client.end();

     // Release the Prisma Client connection
     await prismaClient?.$disconnect();
   },
 }
</code></pre>
<p><strong>User.int.test.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>const ctx = createTestContext();

describe(&quot;User&quot;, () =&gt; {
  it(&quot;creates a new user with REGISTER_MUTATION&quot;, async () =&gt; {
    const userResult = await ctx.client.mutate({
      mutation: gql`
      mutation Register(
        $firstName: String!
        $lastName: String!
        $email: String!
        $password: String!
      ) {
        registerUser(
          firstName: $firstName
          lastName: $lastName
          email: $email
          password: $password
        ) {
          user {
            email
            firstName
          }
        }
      }
      `, 
      variables: {
        firstName: &quot;FirstName&quot;,
        lastName: &quot;LastName&quot;,
        email: &quot;test@email.com&quot;,
        password: &quot;password&quot;
      }
    });

    expect(userResult).toMatchInlineSnapshot(`
Object {
  &quot;data&quot;: Object {
    &quot;registerUser&quot;: Object {
      &quot;__typename&quot;: &quot;UserLoginPayload&quot;,
      &quot;user&quot;: Object {
        &quot;__typename&quot;: &quot;User&quot;,
        &quot;email&quot;: &quot;test@email.com&quot;,
        &quot;firstName&quot;: &quot;FirstName&quot;,
      },
    },
  },
}
`);
  });

  it(&quot;verifies that user persists&quot;, async () =&gt; {
    const persistedData = await ctx.prisma.user.findMany();

    expect(persistedData).toMatchInlineSnapshot(`Array []`);
  });
});
</code></pre>
",https://stackoverflow.com/questions/71621031/integration-testing-with-graphql-nexus-apollo-prisma-and-postgresql,"['postgresql', 'graphql', 'apollo', 'nexus', 'prisma']",326,False,2,1
How to use mockito correctly when conducting integration testing?,"<p>I have a function in which I want to substitute the behavior of some component parts (cosines, sines, ...), I'm trying to create an mock for these parts and pass them to the function.</p>
<pre><code>class Function1Test {
private static final double accuracy = 10e-5;
static Function1 firstFunction;
static Function2 secondFunction;
static TrFunc.MyCos cos;
static TrFunc.MySin sin;
static TrFunc.MyTan tan;
static TrFunc.MySec sec;
static LgFunc.Log2 log2;
static LgFunc.Log3 log3;
static LgFunc.Log5 log5;
static LgFunc.Log10 log10;
static Func_System sys;
@BeforeAll
static void setUp() {
    cos = mock(TrFunc.MyCos.class);
    sin = mock(TrFunc.MySin.class);
    tan = mock(TrFunc.MyTan.class);
    sec = mock(TrFunc.MySec.class);
    firstFunction = new Function1(cos, sin, tan, sec);
    log2 = mock(LgFunc.Log2.class);
    log3 = mock(LgFunc.Log3.class);
    log5 = mock(LgFunc.Log5.class);
    log10 = mock(LgFunc.Log10.class);
    secondFunction = new Function2(log2, log3, log5, log10);
    sys = new Func_System(firstFunction, secondFunction);
}

static Stream&lt;Arguments&gt; valuesRangeProvider(){
    return Stream.of(
            arguments(-6.282185307179586, 1001001.3330000667),
            arguments(-0.161592653589793, 33.496935752492160)
    );
}
@DisplayName(&quot;Integration Test with Mocks&quot;)
@ParameterizedTest(name = &quot;{index}: Check range of values, x = {0}&quot;)
@MethodSource(&quot;valuesRangeProvider&quot;)
void test_0(double value, double expected) throws Exception {
    when(firstFunction.sin.mySin(value, accuracy)).thenReturn(sin(value));
    when(firstFunction.cos.myCos(value, accuracy)).thenReturn(cos(value));
    when(firstFunction.tang.myTan(value, accuracy)).thenReturn(sin(value)/cos(value));
    when(firstFunction.sec.mySec(value, accuracy)).thenReturn(1/cos(value));
    assertEquals(expected, firstFunction.calculate(value, accuracy), accuracy);
}
</code></pre>
<p>The thing is, I get the following message:</p>
<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);
Also, this error might show up because:</p>
<ol>
<li>you stub either of: final/private/equals()/hashCode() methods.
Those methods <em>cannot</em> be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.</li>
<li>inside when() you don't call method on mock but on some other object.*</li>
</ol>
<p>None of the methods are private or final</p>
<pre><code>public class TrFunc {
public static class MyCos {
    public static double myCos(double x, double accuracy) throws Exception {
        if (accuracy &lt; 0){
            throw new Exception(&quot;The accuracy below zero&quot;);
        }
        double theta_norm = Math.abs(x);
        theta_norm -= Math.floor(theta_norm/Math.PI/2)*2*Math.PI;
        double result = 1;
        double step = 1;
        int i;
        for (i = 1; step &gt; accuracy &amp;&amp; i != Integer.MAX_VALUE; i++){
            step = step*theta_norm*theta_norm/(2*i-1)/(2*i);
            if (i % 2 == 1){
                result -= step;
            } else {
                result += step;
            }
        }
        if (!Double.isFinite(result) || i == Integer.MAX_VALUE-1){
            throw new Exception(&quot;Too many iterations&quot;);
        }
        return result;
    }


    private static double factorial(int numer) {
        double factorial = 1.0d;

        while (numer != 0) {
            factorial *= numer--;
        }

        return factorial;
    }
}

public static class MySin {
    public static double mySin(double x, double accuracy) throws Exception {
        return MyCos.myCos(Math.PI/2 - x, accuracy);
    }
}

public static class MyTan {
    public static double myTan(double x, double accuracy) throws Exception {
        double divisor =  MyCos.myCos(x, accuracy);
        if (Math.abs(divisor) &lt;= accuracy) throw new Exception(&quot;Division by zero&quot;);
        return MySin.mySin(x, accuracy) / divisor;
    }
}

public static class MySec {
    public static double mySec(double x, double accuracy) throws Exception {
        double divisor =  MyCos.myCos(x, accuracy);
        if (Math.abs(divisor) &lt;= accuracy) throw new Exception(&quot;Division by zero&quot;);
        if ((x + Math.PI / 2) / Math.PI % 1 == 0) throw new Exception(&quot;x can't be Pi*n-Pi/2&quot;);
        return 1 / divisor;
    }
}
}
</code></pre>
",https://stackoverflow.com/questions/71729089/how-to-use-mockito-correctly-when-conducting-integration-testing,"['java', 'testing', 'mockito']",291,True,1,1
Integration testing authorized endpoints with already specified authentication schemes,"<p>I am trying to set up integration tests for my ASP.NET Web API with authorized endpoints.</p>
<p>I have followed the documentation from Microsoft to add mock authentication to the integration tests to allow the test client to access the authorized endpoints. <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0</a></p>
<p>E.g.</p>
<pre><code>builder.ConfigureTestServices(services =&gt;
{
    services.AddAuthorization(options =&gt;
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
            .AddAuthenticationSchemes(&quot;Test&quot;)
            .RequireAuthenticatedUser()
            .Build();
    });
}
</code></pre>
<p>This works fine if you are using default authentication schemes that you can change on the startup of your integration tests to use the test scheme. But, my authorized endpoints are using specified <code>AuthenticationSchemes</code> so the test scheme will never be authorized for the endpoint. E.g.</p>
<pre><code>[Authorize(AuthenticationSchemes = &quot;Scheme1,Scheme2&quot;)]
public class AppVersionController : ControllerBase
{
    ...
}
</code></pre>
<p>I can get around this issue by specifying an environment variable when testing, checking this and dynamically adding the test scheme to the authorized endpoint. Yet, this adds a lot of test-specific logic to the app, which isn't nice to have in the main project.</p>
<p>This would work:</p>
<pre><code>// Test scheme added dynamically from an environment variable to get the below result
[Authorize(AuthenticationSchemes = &quot;Scheme1,Scheme2,Test&quot;)]
public class AppVersionController : ControllerBase
{
    ...
}
</code></pre>
<p>I get this done by creating a custom attribute that looks basically like this:</p>
<pre><code>public class AuthorizeAll : AuthorizeAttribute
{
    public AuthorizeAll()
    {
        var authenticationSchemes = &quot;Scheme1,Scheme2&quot;;
        if (Environment.GetEnvironmentVariable(&quot;ASPNETCORE_ENVIRONMENT&quot;) == &quot;Testing&quot;)
        {
            authenticationSchemes += &quot;,Test&quot;;
        }
        AuthenticationSchemes = authenticationSchemes;
    }
}
</code></pre>
<p>I just don't like how we will have to continue to maintain this test authentication scheme in the application layer as well as the security concerns with this approach.</p>
<h2>Questions</h2>
<p>What is the best way to authorize endpoints for .NET integration tests when specific authentication schemes are set?</p>
<p>Is it good practice to check environment variables in the app when unit testing to run specific logic that the tests need to work?</p>
<p>The main authentication scheme used at the moment is using JWTs, so is there a better way to mock JWTs for the tests?</p>
",https://stackoverflow.com/questions/73793608/integration-testing-authorized-endpoints-with-already-specified-authentication-s,"['c#', 'authorization', 'asp.net-core-webapi', 'integration-testing', '.net-6.0']",1130,True,1,2
Integration testing vs e2e testing on a finished application,"<p>What makes more sense? I am testing a finished application for a company which is already being used by its customers. The software really only displays data. Which type of testing makes most sense, end-to-end or integration testing?
EDIT: If it makes any difference, the software up to now is completely untested.</p>
",https://stackoverflow.com/questions/74965435/integration-testing-vs-e2e-testing-on-a-finished-application,"['angular', 'testing', 'integration-testing', 'integration', 'end-to-end']",85,True,0,1
Is chai HTTP considered unit testing or integration testing?,"<p>The project I am working on has Cloud Functions written in <code>user-controller.ts</code>, and I am writing tests for these cloud functions using chai HTTP functions. Here's a sample of a test I am writing</p>
<pre><code>it('should success and get all users', (done) =&gt; {
        chai.request(myFunctions.qa)
                .get('/getAllUsers')
                .set('x-api-key', API_KEY)
                .set('user-token', AdminToken)
                .set('content-type', 'application/json')
                .end((err, res) =&gt; {
                    res.should.have.status(200);
                    res.body.should.be.a('object').with.property('status', true);
                    res.body.should.have.a.property('data');
                    const data = res.body.data;
                    expect(data).to.be.an('object');
                    if (Object.keys(data).length &gt; 0) {
                        Object.values(data).map((user: any) =&gt; {
                            expect(user).to.have.property('firstName');
                            expect(user).to.have.property('lastName');
                        });
                    }
                    done();
                });
          });
</code></pre>
<p>I would like to know if this test is considered a unit test or integration test? If it's considered an integration test, how am I supposed to change it into a unit test?</p>
",https://stackoverflow.com/questions/71562679/is-chai-http-considered-unit-testing-or-integration-testing,"['mocha.js', 'chai', 'chai-http']",136,False,0,0
Integration testing an ionic modal with Jasmine in Angular,"<p>I'm trying to test the integration between my angular page and a component running in a modal. The modal is given some data and the component:</p>
<pre><code>const modal = await this.modalController.create({
      component: EditPositionModalComponent,
      componentProps: {orderPosition}
    });
    await modal.present();

    // Wait for the modal to close and process the received data
    let {data} = await modal.onDidDismiss();
</code></pre>
<p>Inside the modal the user can edit the data and submit the changes. With the tests I want to make sure that the data gets sent correctly to the modal and back to the page after it's dismissed.</p>
<p>This is how far I got:</p>
<pre><code>describe('OrderDetailPage/EditPosition Integrationtest', async () =&gt; {
  let component: OrderDetailPage;
  let fixture: ComponentFixture&lt;OrderDetailPage&gt;;
  let modalControllerSpy : Spy;

  beforeEach((() =&gt; {
    TestBed.configureTestingModule({
      declarations: [OrderDetailPage],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      imports: [
        CommonModule,
        IonicModule.forRoot(),
        HttpClientTestingModule,
        ReactiveComponentModule,
        ReactiveFormsModule,
        ComponentsModule,
        RouterTestingModule,
        TranslateModule.forRoot()],
      providers: [
        //Providing mocks
        provideMockStore({}),
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(OrderDetailPage);
    component = fixture.componentInstance;
    fixture.detectChanges();

    modalControllerSpy = spyOn(ModalController.prototype, 'create').and.callThrough();
    component.onEditPosition(new MouseEvent(''), testOrderPosition); //Click event call to open the modal
    fixture.detectChanges();
  }));

  it('should send correct data to modal', async () =&gt; {
    let modal: HTMLIonModalElement = await modalControllerSpy.calls.first().returnValue;
    await modal.present();
  });
});
</code></pre>
<p>I can get the HTMLIonModalElement created from the modalController through the spy. But I can't find a way to access the actual component doing this. The HTMLIonModalElement only contains the following:</p>
<pre><code>&lt;ion-modal class=&quot;md modal-default hydrated&quot; id=&quot;ion-overlay-1&quot; no-router=&quot;&quot; aria-modal=&quot;true&quot; tabindex=&quot;-1&quot; style=&quot;z-index: 20001;&quot;&gt;
   &lt;app-edit-position-modal _nghost-a-c317=&quot;&quot; class=&quot;ion-page&quot;&gt;
     &lt;!--container--&gt;&lt;!--container--&gt;
   &lt;/app-edit-position-modal&gt;
   &lt;app-edit-position-modal _nghost-a-c317=&quot;&quot; class=&quot;ion-page&quot;&gt;
     &lt;!--container--&gt;&lt;!--container--&gt;
   &lt;/app-edit-position-modal&gt;
&lt;/ion-modal&gt;
</code></pre>
<p>Even after I wait for the modal.present() or for some fakeAsync tick it won't contain anything I could test against.</p>
<p>Any help is appreciated.</p>
",https://stackoverflow.com/questions/72473169/integration-testing-an-ionic-modal-with-jasmine-in-angular,"['angular', 'ionic-framework', 'jasmine', 'integration-testing']",666,False,0,0
Flutter integration testing : Enter text into TextFormField by label,"<p>How do I enter text into <code>TextFormField</code> by using the label text? My issue is that I can't find the widget while doing an integration test. I was able to find the widget by adding a key but I don't want to change the source code of the app for doing integration testing.</p>
<pre><code>TextFormField(
                controller: usernameController,
                decoration: InputDecoration(border: UnderlineInputBorder(), labelText: &quot;Username&quot;),
              )
</code></pre>
<p>Tried something like this but it doesn't work:</p>
<pre><code>final usernameField = find.descendant(
  of: find.text(&quot;Username&quot;),
  matching: find.byType(EditableText),
);
</code></pre>
",https://stackoverflow.com/questions/73202977/flutter-integration-testing-enter-text-into-textformfield-by-label,"['flutter', 'flutter-test']",937,True,0,2
How can one log into Auth0 for integration testing?,"<p>I'm using <a href=""https://modern-web.dev/docs/test-runner/overview/"" rel=""nofollow noreferrer"">@web/test-runner</a> to perform e2e testing of a web application that uses Auth0. This has been a problem because Auth0 doesn't allow for wildcard path addition for redirects and @web/test-runner doesn't seem to allow different-origin navigation during test running. Does anyone know of a method of signing into Auth0 during integration/e2e testing?</p>
",https://stackoverflow.com/questions/72248356/how-can-one-log-into-auth0-for-integration-testing,"['javascript', 'integration-testing', 'web-component', 'e2e-testing', 'auth0']",177,False,0,1
How to use custom spring library for integration testing,"<p>I have a spring library which I use for spring boot applications. This library is an API client that can make HTTP requests on known API endpoints. This library has several packages and configuration classes that read the configuration values from the application.yaml file of the spring-boot application where this library is used at. i.e. API URL, API login credentials ...etc</p>
<p>I want to use this library for some integration testing. My integration test is not a spring-boot application therefore, I want to provide the configuration from a separate .property file or .yaml file. How do I achieve that? I want to run it as a junit5 test.</p>
<pre><code>//@SpringBootTest
@TestPropertySource(locations = &quot;classpath:api-config.yaml&quot;)
@EnableConfigurationProperties
@ExtendWith(SpringExtension.class)
public class APITest {

// this property is from the above library
@Autowired
private ApiClient apiClient;

@Test
  void testSomeAPIResponse() {
    String key = &quot;some-key&quot;;
    SomethingDTO somethingDTO = apiClient.getSomethingBykey(key);
    assertNotNull(somethingDTO);
  }
}
</code></pre>
<p>in the above code, api-config.yaml is the file where I have configuration values for APIClient.</p>
",https://stackoverflow.com/questions/73103924/how-to-use-custom-spring-library-for-integration-testing,"['java', 'spring', 'spring-test']",118,False,0,0
[Flutter Integration testing][iOS] deeplink not working with background,"<p>I'm working on e2e testing with <a href=""https://docs.flutter.dev/testing/integration-tests"" rel=""nofollow noreferrer"">Integration testing</a>.
I am trying to write test of deeplink(or any Universal links or AppLinks) by using <a href=""https://pub.dev/packages/url_launcher"" rel=""nofollow noreferrer"">url_launcher</a>.
However, Android works fine but iOS doesn't.
iOS　shows up this error.</p>
<pre><code>[BackgroundTask] Background Task 50 (&quot;Flutter debug task&quot;), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.
</code></pre>
<p>Does any one knows how to solve this problem?</p>
",https://stackoverflow.com/questions/73969459/flutter-integration-testingios-deeplink-not-working-with-background,"['ios', 'flutter', 'dart', 'integration-testing']",122,False,0,0
How to drop database in Integration Testing mysql TypeOrm Nestjs,"<p>I am using mysql as database, I searched on the internet and the methods I tried were not up to date. I want the db to reset itself in every test. But I couldn't find the appropriate method, can you help?</p>
<pre><code>describe('Authentication System', () =&gt; {
  let app: INestApplication;

  beforeEach(async () =&gt; {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();
    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('if user already in database', async () =&gt; {
    await request(app.getHttpServer())
      .post('/auth/signup')
      .send({name:&quot;muti&quot;})
      .expect(HttpStatus.BAD_REQUEST)
      .then((res) =&gt; {
        const { access_token } = res.body;
        expect(access_token).not.toBeDefined();
      });
  });
</code></pre>
",https://stackoverflow.com/questions/73209480/how-to-drop-database-in-integration-testing-mysql-typeorm-nestjs,"['mysql', 'node.js', 'nestjs']",739,True,2,1
"Integration testing with .NET 6, EF Core 6, and xUnit","<p>Has anyone had any success in setting up integration testing for web applications written in .NET 6 and EntityFramework Core 6, and using SQLite in-memory database? I am having issues with test setup/teardown, so tests which run fine in isolation, start randomly failing when running all tests together.</p>
<p>My test context is set up based on the Microsoft examples:</p>
<pre><code>public class TestApplication : AutofacWebApplicationFactory&lt;Startup&gt;
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureTestServices(services =&gt;
        {
            services.AddAuthentication(options =&gt;
            {
                options.DefaultAuthenticateScheme = FakeJwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = FakeJwtBearerDefaults.AuthenticationScheme;
            }).AddFakeJwtBearer();

            services.AddAuthorization(options =&gt;
            {
                options.DefaultPolicy = new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(FakeJwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser()
                    .Build();
            });

            var connectionString = new SqliteConnectionStringBuilder($&quot;DataSource=file:{Guid.NewGuid()}?cache=shared&amp;mode=memory&quot;);
            var connection = new SqliteConnection(connectionString.ToString());
            connection.Open();

            var descriptor = services.SingleOrDefault(d =&gt; d.ServiceType == typeof(DbContextOptions&lt;MyDbContext&gt;));
            if (descriptor != null)
            {
                services.Remove(descriptor);
            }

            services.AddDbContext&lt;MyDbContext&gt;(options =&gt;
            {
                options.UseSqlite(connection);
            });

            var sp = services.BuildServiceProvider();

            using var scope = sp.CreateScope();
            var scopedServices = scope.ServiceProvider;
            var db = scopedServices.GetRequiredService&lt;MyDbContext&gt;();
            var logger = scopedServices.GetRequiredService&lt;ILogger&lt;TestApplication&gt;&gt;();

            db.Database.EnsureDeleted();
            db.Database.EnsureCreated();

            try
            {
                logger.LogInformation(&quot;Initialising in-memory database with test data&quot;);
                TestData.Initialise(db);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, &quot;An error occurred seeding the database with test messages. Error: {Message}&quot;, ex.Message);
            }
        });
    }
}
</code></pre>
<p>which will be used in my test fixtures something like this:</p>
<pre><code>public class WhenGettingPartners
{
    [Fact]
    public async Task ItShouldAcceptValidRequests()
    {
        await using var app = new TestApplication();
                
        var client = app.CreateClient().WithRoles(Scopes.PartnerRead);
        
        var result = await client.GetAsync(&quot;/Partners&quot;);
        result.Should().BeSuccessful();

        var data = await result.Content.ReadAsType&lt;Partner[]&gt;();
        data.Should().NotBeEmpty();
    }

    [Fact]
    public async Task ItShouldRejectUnauthorisedRequests()
    {
        await using var app = new TestApplication();
                
        var client = app.CreateClient();
        
        var result = await client.GetAsync(&quot;/Partners&quot;);
        result.Should().HaveStatusCode(HttpStatusCode.Unauthorized);
    }
}
</code></pre>
<p>If I select an individual test case and run it, it works fine; if I select the entire text fixture and run it, it works fine. But when I run the entire test project, then tests will fail randomly, usually when it tries to recreate the database and finds the tables already exist.</p>
<p>I've tried using xUnit's <code>IClassFixture</code> interface to share one instance of <code>TestApplication</code> across all tests in the fixture:</p>
<pre><code>public abstract class ApiTestFixture : IClassFixture&lt;TestApplication&gt;
{
    public ApiTestFixture(TestApplication application)
    {
        App = application;
    }

    public TestApplication App { get; }
}

public class WhenGettingClients : ApiTestFixture
{
    public WhenGettingClients(TestApplication app) : base(app)
    {
    }

    [Fact]
    public async Task ItShouldAcceptValidRequests()
    {
        var client = App.CreateClient().WithRoles(Scopes.ClientRead);
        
        var result = await client.GetAsync(&quot;/Clients&quot;);
        result.Should().BeSuccessful();

        var data = await result.Content.ReadAsType&lt;Client[]&gt;();
        data.Should().HaveCount(2);
    }

    [Fact]
    public async Task ItShouldRejectUnauthorisedRequests()
    {
        var client = App.CreateClient();
        
        var result = await client.GetAsync(&quot;/Clients&quot;);
        result.Should().HaveStatusCode(HttpStatusCode.Unauthorized);
    }
}
</code></pre>
<p>but that fails in exactly the same way.</p>
<p><strong>Update</strong></p>
<p>I am developing using the Rider IDE from JetBrains; the same issue occurs if I run the tests in Visual Studio. However, I noticed that if I test with code coverage in Rider, then the tests all pass! Similarly, if I test with profiling in Rider, then the tests all pass; so I'm wondering if there's something more esoteric going on, that the code coverage runner somehow forces the tests to execute in a manner which is more deterministic or less likely to result in test pollution.</p>
",https://stackoverflow.com/questions/72123391/integration-testing-with-net-6-ef-core-6-and-xunit,"['integration-testing', '.net-6.0', 'xunit.net', 'ef-core-6.0']",780,False,1,0
Authorize camera access in integration testing with flutter integration_test package,"<p>I want to test Add Picture (using camera) feature for my app using integration_test package for app. When app tries to open a camera it asks for camera permission and I could not find a way to tap allow permission as its a system dialog.</p>
<p>I am looking for two solution.</p>
<p>1 - Find a way to control System dialog so I can tap allow button using Widget Tester.
2 - I want to set a all permission when I start the app for Testing. Please note that I want to do only for testing.</p>
",https://stackoverflow.com/questions/72540424/authorize-camera-access-in-integration-testing-with-flutter-integration-test-pac,"['integration-testing', 'android-permissions', 'flutter-test', 'permission-denied']",537,True,1,1
How to configure the database image for Springboot integration testing,"<p>There is a situation that I want to use a database image to integration test my service layer. Here is the code I developed to setup my Postgres container image:</p>
<pre><code>@SpringBootTest(classes = EventhandlerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public abstract class BaseIT {

public static final PostgreSQLContainer&lt;?&gt; postgresDB = new PostgreSQLContainer&lt;&gt;
        (&quot;postgres:12-alpine&quot;)
        .withDatabaseName(&quot;test-db&quot;)
        .withUsername(&quot;postgres&quot;)
        .withPassword(&quot;password&quot;);

static {
    postgresDB.start();
}

@DynamicPropertySource
public static void properties(DynamicPropertyRegistry registry) {
    registry.add(&quot;spring.datasource.url&quot;, postgresDB::getJdbcUrl);
    registry.add(&quot;spring.datasource.username&quot;, postgresDB::getUsername);
    registry.add(&quot;spring.datasource.password&quot;, postgresDB::getPassword);
}
}
</code></pre>
<p>Now I want to use the test database to call my service layer methods and inspect the results, here is my integration test example:</p>
<pre><code>public class SampleServiceTesting extends BaseIT {

@Autowired
private SampleService sampleService;


@Test
@Transactional
void testIntegrationFlow() {
    SampleService.exampleMethod();
}
}
</code></pre>
<p>But when I run the test, it returns the following error:</p>
<pre><code>org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
</code></pre>
<p>How I can fix this issue on runing  my test please?</p>
",https://stackoverflow.com/questions/74805334/how-to-configure-the-database-image-for-springboot-integration-testing,"['java', 'spring-boot', 'integration-testing', 'testcontainers']",92,True,1,1
How to manually set finbuckle current tenant for integration testing,"<p>I am trying to &quot;integration test&quot; a multi-tenant dotnet core application, since repositories and DbContexts requires the current tenant information which is normally set using the Mediator during requests.</p>
<p>In integration test I need to set the tenant manually,
I have tried to create httpcontext object and use the TrySetTenantInfo function but it gives error</p>
<blockquote>
<p>Value cannot be null. (Parameter 'provider')</p>
</blockquote>
<p>here is the code I tried for httpcontext setting</p>
<pre><code>_httpContextAccessor =_servicesProvider.GetRequiredService&lt;IHttpContextAccessor&gt;();
_httpContextAccessor.HttpContext = new DefaultHttpContext();

TenantInfo ti = new TenantInfo
        {
            Id = &quot;**&quot;,
            Identifier = &quot;**&quot;,
            ConnectionString = &quot;**&quot;,
            Name = &quot;***&quot;
        };
//here is the error thrown 
        if (_httpContextAccessor.HttpContext.TrySetTenantInfo(ti, true))
        {
        
        }
</code></pre>
<p>Thanks</p>
",https://stackoverflow.com/questions/74296152/how-to-manually-set-finbuckle-current-tenant-for-integration-testing,"['unit-testing', 'asp.net-core', '.net-core', 'integration-testing', 'multi-tenant']",216,False,1,0
Unit and Integration testing of custom Kong plugin using busted,"<p>I have been trying to explore unit and integration testing frameworks for custom kong plugins. I'm very new to Lua and I started exploring busted and I was <strong>not</strong> able to successfully run tests on the plugin.</p>
<p>Here are the steps I followed -</p>
<ol>
<li>I ran a Docker container of kong version 2.5.0</li>
<li>Inside the kong docker container I cloned <a href=""https://github.com/Kong/kong"" rel=""nofollow noreferrer"">https://github.com/Kong/kong</a> repo</li>
<li>when I try to run some tests from the above repository's spec folder i get error as <code>./kong/tools/utils.lua:37: attempt to index global 'ngx' (a nil value)</code></li>
</ol>
<p>I'm following <a href=""https://docs.konghq.com/gateway/latest/plugin-development/tests/"" rel=""nofollow noreferrer"">this</a> documentation, to understand writing and running unit and integrtion tests in kong, but I'm having hard time setting up the environment.</p>
<p>Any help in setting up a docker container to run unit and integration tests in kong using busted is appreciated.</p>
",https://stackoverflow.com/questions/74068456/unit-and-integration-testing-of-custom-kong-plugin-using-busted,"['lua', 'kong', 'kong-plugin', 'lua-busted']",325,False,1,0
How to deploy Spring Boot Integration Testing in the Pipeline,"<p>I have a microservice which has 2 modules</p>
<p>my-microservice-app</p>
<p>my-microservice-it</p>
<p>(gonna refer them as &quot;app&quot; and &quot;it&quot;)</p>
<p>Right now I am writing integration tests for graphql and here is how I run this on my local.</p>
<p>1- I added &quot;app&quot; as a dependency to the &quot;it&quot; (to pom.xml)</p>
<p>2- Import my main class from &quot;app&quot; module to one of the configuration classes of &quot;it&quot; module</p>
<pre><code>@Configuration
@Import(SomeClass.class)
public class Application {
</code></pre>
<p>3- Set my configuration class in SpringBootTest annotation</p>
<pre><code>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class)
@ActiveProfiles(&quot;test&quot;)
public class GraphQLIT extends AbstractTestNGSpringContextTests {
</code></pre>
<p>Only thing I override in the application-test.yml file is postgre db because I don't want any crud operations in my prod db every time this integration tests run.</p>
<p>I will have a postgre db instance in the pipeline but I can't figure out how I am supposed to create an environment to run this integration test module in GitLab pipeline.</p>
",https://stackoverflow.com/questions/71556909/how-to-deploy-spring-boot-integration-testing-in-the-pipeline,"['spring-boot', 'integration-testing', 'gitlab-ci', 'gitlab-ci-runner', 'spring-boot-test']",194,False,1,0
Maven Integration Testing Framework forces dependency resolution from central repository,"<p>I'm using the <a href=""https://github.com/khmarbaise/maven-it-extension"" rel=""nofollow noreferrer"">Maven Integration Testing Framework</a> plugin to test one goal of a custom-developed plugin. As far as the tests go, everything works well. However, there is one unexpected and undesired technicality that I have noticed:</p>
<p>The local repositories created for individual test cases in <code>target/maven-it/.../test-case/.m2/repository</code> are always populated remotely - from the <a href=""https://mvnrepository.com/repos/central"" rel=""nofollow noreferrer"">Maven Central Repository</a>. If I run <code>mvn clean integration-test</code> without being connected to the Internet, the dependency resolution results in an error after a failed connection attempt. I would expect it, however, to look for the dependencies in the &quot;standard&quot; cache located in <code>USER/.m2/repository</code> first, where the dependencies were already present in my experiment.</p>
<p>It's interesting that even after adding the <code>--offline</code> option to <code>mvn clean integration-test</code>, online dependency resolution is still attempted.</p>
<p>My main question is - should this be happening? Is this the expected behavior when using the Maven Integration Testing Framework? Or do you think there might be something wrong with the way I'm using it?</p>
<p>Related dependencies from the <code>pom.xml</code> of the tested custom-developed plugin:</p>
<pre><code>        &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;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-params&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.platform&lt;/groupId&gt;
            &lt;artifactId&gt;junit-platform-suite&lt;/artifactId&gt;
            &lt;version&gt;${junit.platform.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.assertj&lt;/groupId&gt;
            &lt;artifactId&gt;assertj-core&lt;/artifactId&gt;
            &lt;version&gt;3.16.1&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.soebes.itf.jupiter.extension&lt;/groupId&gt;
            &lt;artifactId&gt;itf-jupiter-extension&lt;/artifactId&gt;
            &lt;version&gt;0.11.0&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.soebes.itf.jupiter.extension&lt;/groupId&gt;
            &lt;artifactId&gt;itf-assertj&lt;/artifactId&gt;
            &lt;version&gt;0.11.0&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
</code></pre>
<p>Related plugins:</p>
<pre><code>            &lt;plugin&gt;
                &lt;groupId&gt;com.soebes.itf.jupiter.extension&lt;/groupId&gt;
                &lt;artifactId&gt;itf-maven-plugin&lt;/artifactId&gt;
                &lt;version&gt;0.11.0&lt;/version&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;id&gt;installing&lt;/id&gt;
                        &lt;phase&gt;pre-integration-test&lt;/phase&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;install&lt;/goal&gt;
                            &lt;goal&gt;resources-its&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt;
                &lt;version&gt;3.0.0-M5&lt;/version&gt;
                &lt;configuration&gt;
                  &lt;systemProperties&gt;
                    &lt;maven.version&gt;${maven.version}&lt;/maven.version&gt;
                    &lt;maven.home&gt;${maven.home}&lt;/maven.home&gt;
                  &lt;/systemProperties&gt;
                &lt;/configuration&gt;
                &lt;executions&gt;
                  &lt;execution&gt;
                    &lt;goals&gt;
                      &lt;goal&gt;integration-test&lt;/goal&gt;
                      &lt;goal&gt;verify&lt;/goal&gt;
                    &lt;/goals&gt;
                  &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
</code></pre>
",https://stackoverflow.com/questions/70702126/maven-integration-testing-framework-forces-dependency-resolution-from-central-re,"['maven', 'integration-testing', 'maven-plugin']",148,True,1,1
"Unit Testing, Widget Testing and Integration Testing in a flutter?","<p>What is Unit Testing, Widget Testing and Integration Testing in a flutter? Someone can explain to me?</p>
",https://stackoverflow.com/questions/71377404/unit-testing-widget-testing-and-integration-testing-in-a-flutter,['flutter'],107,False,-2,1
How do I bypass a Custom Attribute when Integration Testing?,"<p>Basically, I would like to do a clean Integration Testing using net6.0. I want to invoke the endpoints of my controller which will eventually go into the database and write some data. Afterward, I will assert some aspects of the inserted data.</p>
<p>I can bypass the Bearer Token used by <code>[Authorize]</code> attribute but cannot bypass my custom attribute named as <code>[HasPermission]</code></p>
<p>I have this custom attribute:</p>
<pre><code>public class HasPermission : TypeFilterAttribute
{
    public HasPermission(string resource, string scope) 
        : base(typeof(HasPermissionAuthorize))
    {
        Arguments = new object[] { resource, scope };
    }
};

public class HasPermissionAuthorize : IAuthorizationFilter
{
    private readonly string _resource;
    private readonly string _scope;
    private readonly IAuthService _authService;
    
    public HasPermissionAuthorize(string resource, string scope, IAuthService authService)
    {
        _resource = resource;
        _scope = scope;
        _authService = authService;

    }
    public async void OnAuthorization(AuthorizationFilterContext context)
    {
        string token = context.HttpContext.Request.Headers[&quot;Authorization&quot;];

        token = token.Replace(&quot;Bearer &quot;, &quot;&quot;);

        bool hasPermission = await _authService.HasClaimAsync(token, &quot;permission&quot;, _resource + &quot;.&quot; + _scope);

        if (!hasPermission)
        {
            context.Result = new UnauthorizedResult();
        }
    }
</code></pre>
<p>And this is my controller:</p>
<pre><code>[Authorize] //&lt;-- I can bypass this
[Route(&quot;v1/[controller]&quot;)]
[ApiController]
public class MachinesController : ControllerBase
{
    [HasPermission(&quot;Machines&quot;, &quot;Create&quot;)] //&lt;-- How do I bypass this?
    [HttpPost]
    public async Task&lt;IActionResult&gt; Post([FromBody] AddMachineRequest request)
    {
        //some logic
    }
}
</code></pre>
<p>In my Integration Testing</p>
<pre><code>public class ApiWebApplicationFactory : WebApplicationFactory&lt;Startup&gt;
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =&gt;
        {
            //I'm bypassing the [Authorize] attribute here
            //However, I do not know how to bypass [HasPermission] attribute
            services.AddMvc(options =&gt;
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .AddAuthenticationSchemes(&quot;Test&quot;)
                    .Build();

                options.Filters.Add(new AuthorizeFilter(policy));
            });
            services.AddAuthentication(options =&gt;
                {
                    options.DefaultAuthenticateScheme = &quot;Test&quot;;
                    options.DefaultChallengeScheme = &quot;Test&quot;;
                    options.DefaultScheme = &quot;Test&quot;;
                }) //TestAuthHandler is written somewhere else
                .AddScheme&lt;AuthenticationSchemeOptions, TestAuthHandler&gt;(&quot;Test&quot;, options =&gt; { });
        }
    }
}
</code></pre>
<p>I'm testing my code using <code>IClassFixture&lt;ApiWebApplicationFactory&gt;</code>. Even though I can bypass <code>[Authorize]</code> attribute, I could NOT find an elegant way to bypass <code>[HasPermission]</code> attribute.</p>
",https://stackoverflow.com/questions/70944661/how-do-i-bypass-a-custom-attribute-when-integration-testing,"['c#', 'asp.net-mvc', 'integration-testing']",63,True,0,1
Github Integration testing Error: Process completed with exit code 1,"<p><a href=""https://i.stack.imgur.com/Df8gU.png"" rel=""nofollow noreferrer"">When i create test for my project this error is seen, how can i fix this?</a></p>
<p><a href=""https://i.stack.imgur.com/pmYjI.png"" rel=""nofollow noreferrer"">Error</a></p>
<p><a href=""https://i.stack.imgur.com/4gO5r.png"" rel=""nofollow noreferrer"">my gradle.yml file in workflow directory</a></p>
<p>PS: It says that I am nor allowed to embed image to my post, i hope u will be able to see the photos in this way also</p>
",https://stackoverflow.com/questions/74088404/github-integration-testing-error-process-completed-with-exit-code-1,"['github', 'gradle', 'integration-testing', 'integration']",260,False,0,0
Mock Refit SDK injection with a Mock HttpClient for Integration Testing,"<p>For a .Net Core 3.1 WebApi project, I want to test the full pipeline of my application while mocking out the external calls (not a unit test, full test). This app uses Refit SDK to inject SDKs for external calls. I want to be able to override the SDK on this test so that all the code is reached but dynamic responses are returned depending on what the request was. While I am using richardszalay.mockhttp for testing, I'm more than willing to switch mockers if it gets me what I need.</p>
<p>I know I can have different expects depending on values inside the request (I have just psudo code in my example). So I can get this far.</p>
<p>What I need though, is that for this particular workflow, the service will return a ReferenceId value in the response that was passed in via the request. Any thoughts on how to dynamically create the ReferenceId field in the response when its based on the ReferenceId field in the request? Is it simply not possible?</p>
<pre><code> using var mockHttp = new MockHttpMessageHandler(); 
        var settings = new RefitSettings { HttpMessageHandlerFactory = () =&gt; mockHttp };           
        mockHttp.Expect(HttpMethod.Post, &quot;https://api.github.com/junk/url/example&quot;).With(req =&gt; req.PaymentId == 4).Respond(resp =&gt; responseMessage);
        var apiServiceMock = RestService.For&lt;IRealTimePayment&gt;(&quot;https://api.github.com&quot;, settings);
        return await apiServiceMock.InitiatePaymentAsync(request: request, headers: null).ConfigureAwait(false);
</code></pre>
",https://stackoverflow.com/questions/70807142/mock-refit-sdk-injection-with-a-mock-httpclient-for-integration-testing,"['c#', 'asp.net-web-api', 'httpclient', 'integration-testing', 'mockhttpmessagehandler']",1460,True,1,1
Integration testing a CRUD application - how can I create maintainable tests,"<p>I have small CRUD application that I would like to create integration tests for. I've seen the recommendation that &quot;tests depending on other tests&quot; is a no go. But how can I keep the code maintainable while at the same time not using the data from other tests?</p>
<p>So what I mean is easier to show by example with some pseudo code</p>
<pre class=""lang-java prettyprint-override""><code>TestCreateUser {
  make POST to API creating a user
  verify the a 200 is received back
}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>TestReadUser {
  GET the user from the previous test.
  verify its the same user
}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>TestUpdateUser {
  PATCH the user from the previous test.
  verify the user have the new data.
}
</code></pre>
<p>So this would be bad since all tests depend on the first one. So what are the alternatives? I guess I could use a beforeEach</p>
<pre class=""lang-java prettyprint-override""><code>@BeforeEach
public void initEach(){
  make POST to API creating a user
  verify the a 200 is received back
}
</code></pre>
<p>And then just skip the create user test. But this might create unnecessary calls if i for example have a test like this</p>
<pre class=""lang-java prettyprint-override""><code>TestCreateUserWithSpecialData {
  make POST to API creating a user with additional data
  verify the a 200 is received back
  verify the additional data is correctl
}
</code></pre>
<p>Then the beforEach would just create a user that the test does not need. Whats a good solution to solving this? Should I split them up into smaller classes and more files? Or are there a better solution? I suppose i could create if statements in the beforEach but that feels like a hack.</p>
",https://stackoverflow.com/questions/72956049/integration-testing-a-crud-application-how-can-i-create-maintainable-tests,"['java', 'testing', 'junit', 'integration-testing']",210,False,0,2
Separate DbContext replaced for Integration testing with WebApplicationFactory not executing migrations,"<p>Im writing integration tests for my WebAPI and for them im swapping implementation of DbContext that my app is using. I'm doing this so I can run configurations that seed my DB with data that are necessary for testing.</p>
<p>My test DbContext inherits from DbContext used by my app and it looks like this:</p>
<pre><code>{
    public TestNeverLateContext(DbContextOptions&lt;NeverLateContext&gt; options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.ApplyConfigurationsFromAssembly(GetType().Assembly);
    }
}
</code></pre>
<p>The problem is that while i swap this implementation my WebApi is not performing migrations. While DB is created migrations column is created but its not populated.
I guess it is because migration classes contain this attribute</p>
<pre><code>[DbContext(typeof(NeverLateContext))]
</code></pre>
<p>Is there a way to execute those migrations with my inherited TestNeverLateContext?
I could just copy this migrations and recreate them with</p>
<pre><code>[DbContext(typeof(TestNeverLateContext))]
</code></pre>
<p>but maybe there is another approach.</p>
",https://stackoverflow.com/questions/73347185/separate-dbcontext-replaced-for-integration-testing-with-webapplicationfactory-n,"['c#', '.net', 'entity-framework', 'webapi']",105,False,0,0
.NET MAUI Integration Testing - FileNotFoundException: Could not load file or assembly Microsoft.Maui.Essentials,"<p>I'm attempting to integration test a .NET MAUI application utilizing entity framework core.
When the code gets to the line 'this.Database.EnsureCreated()', it gives a file not found exception.</p>
<p>The first thought was trying to reference Microsoft.Maui.Essentials, though when I search for it in NuGet, all I can find is Microsoft.Maui.Essentials.Ref.___ which doesn't seem compatible with my project.</p>
<p>If I try to install it, I get the error 'The package Microsoft.Maui.Essentials.Ref.any 6.0.547 has a package type DotnetPlatform that is incompatible with this project'</p>
<p>How can I resolve this error?</p>
<p>The full length exception is:
System.IO.FileNotFoundException: 'Could not load file or assembly 'Microsoft.Maui.Essentials, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.'</p>
<p>Integration test code:</p>
<pre><code>...
var options = new DbContextOptionsBuilder&lt;DataContext&gt;()
                .UseInMemoryDatabase(databaseName: &quot;Test_Database&quot;)
                .Options;
            var mockDataContext = new Mock&lt;DataContext&gt;(options);
            mockDataContextCreator
                .Setup(x =&gt; x.CreateDbContext())
                .Returns(new DataContext(options));
...
</code></pre>
<p>DataContext.cs</p>
<pre><code>public class DataContext : DbContext

...

public DataContext(DbContextOptions options)
            : base(options)
        {
            SQLitePCL.Batteries_V2.Init();

            if (!this.Database.EnsureCreated())
            {
                this.Database.Migrate();
            }
        }
</code></pre>
<p>The Database property is of type 'Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade' and is defined in the base class 'DbContext'.</p>
<p>Integration Test CSPROJ File:</p>
<pre><code>...
&lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net6.0&lt;/TargetFramework&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;

    &lt;IsPackable&gt;false&lt;/IsPackable&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.EntityFrameworkCore.InMemory&quot; Version=&quot;7.0.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Maui.Dependencies&quot; Version=&quot;6.0.547&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Maui.Extensions&quot; Version=&quot;6.0.547&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;17.1.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Moq&quot; Version=&quot;4.18.2&quot; /&gt;
    &lt;PackageReference Include=&quot;NUnit&quot; Version=&quot;3.13.3&quot; /&gt;
    &lt;PackageReference Include=&quot;NUnit3TestAdapter&quot; Version=&quot;4.2.1&quot; /&gt;
    &lt;PackageReference Include=&quot;NUnit.Analyzers&quot; Version=&quot;3.3.0&quot; /&gt;
    &lt;PackageReference Include=&quot;coverlet.collector&quot; Version=&quot;3.1.2&quot; /&gt;
  &lt;/ItemGroup&gt;
...
</code></pre>
",https://stackoverflow.com/questions/74605011/net-maui-integration-testing-filenotfoundexception-could-not-load-file-or-as,"['entity-framework-core', 'moq', 'maui']",655,True,2,1
asp.net core web Api integration testing with startup having static file configuration,"<p>I was trying to implement integration testing for my api. But, it is saying     System.IO.DirectoryNotFoundException : ..WebApi.IntegrationTest\bin\Debug\net6.0\Files\ while I run the test</p>
<p>here is my startup code</p>
<pre><code> public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
     
            }
            app.UseBlazorFrameworkFiles();
            
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @&quot;Files&quot;)),
                RequestPath = new PathString(&quot;/Files&quot;)
            });
            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseCors(&quot;CorsPolicy&quot;);
             app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =&gt;
            {
                endpoints.MapControllers();
            });
            app.Initialize(Configuration);
        }
</code></pre>
<p>when I comment out UseStaticFiles it passes the test else it fails with the above. exception</p>
<p>here is my CustomWebApplicationFactory</p>
<pre><code> public class CustomWebApplicationFactory&lt;TStartup&gt; : WebApplicationFactory&lt;TStartup&gt; where TStartup : class
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =&gt;
        {
            services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
            {
                options.UseInMemoryDatabase(&quot;ApplicationDbContextInMemoryTest&quot;);
            })
            .AddControllers()
            .AddApplicationPart(typeof(Startup).Assembly);

            var sp = services.BuildServiceProvider();
            using (var scope = sp.CreateScope())
            {
                var scopedService = scope.ServiceProvider;
                var context = scopedService.GetRequiredService&lt;ApplicationDbContext&gt;();
                var logger = scopedService.GetRequiredService&lt;ILogger&lt;CustomWebApplicationFactory&lt;TStartup&gt;&gt;&gt;();

                context.Database.EnsureCreated();
                try
                {
                    Utilities.InitializeDbForTests(context);
                }
                catch (Exception ex)
                {

                    logger.LogError(ex, $&quot;An error occured seeding the database with test messages, Error: {ex.Message}&quot;);
                }
            }
        });
    }
    protected override IHost CreateHost(IHostBuilder builder)
    {
        builder.UseContentRoot(Directory.GetCurrentDirectory());
        return base.CreateHost(builder);
    }
    public HttpClient GetAnonymousClient()
    {
        return CreateClient();
    }
}
</code></pre>
<p>I tried a lot to fix it but I was not able, please help me, thank you!</p>
",https://stackoverflow.com/questions/71941540/asp-net-core-web-api-integration-testing-with-startup-having-static-file-configu,"['asp.net-core', 'asp.net-web-api', 'integration-testing', 'asp.net-core-staticfile']",286,False,1,0
How to do Flutter web integration testing with BrowserStack / Sauce Labs etc?,"<p>I'm trying to run integration tests of a Flutter web (not Android/iOS) app on a hosted device farm like BrowserStack or Sauce Labs. It seems that the Flutter driver or integration tester are only designed to run on the local machine you're testing on. They require a custom driver for the browser and that driver doesn't seem able to connect to a remote browser. Has anyone found a way through port forwarding or something clever to overcome this limitation? Or does the device farm host have to run the Flutter driver themselves?</p>
<p>The ability to run automated tests on a variety of browsers and devices is critical to CI/CD and it seems odd that Flutter doesn't support this short of managing your own device farm.</p>
<p>A screenshot of <code>flutter drive -h</code>:
<a href=""https://i.stack.imgur.com/r4TEK.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/r4TEK.png"" alt=""enter image description here"" /></a></p>
<p>We can't use a regular Selenium grid/driver because Flutter is rendering to a canvas or SVG through shadow dom elements which makes it pretty infeasible to drive with traditional HTML/CSS selectors.</p>
",https://stackoverflow.com/questions/71651423/how-to-do-flutter-web-integration-testing-with-browserstack-sauce-labs-etc,"['flutter', 'integration-testing', 'browserstack', 'saucelabs']",671,True,1,2
How to do integration testing on Spring Boot with fake GCS Bucket?,"<p>I have an application that connect to GCS Bucket with Spring Boot. I want to do an integration test with fake gcs server here: <a href=""https://github.com/fsouza/fake-gcs-server"" rel=""nofollow noreferrer"">https://github.com/fsouza/fake-gcs-server</a> . But I'm very clueless how to do it.</p>
",https://stackoverflow.com/questions/70743277/how-to-do-integration-testing-on-spring-boot-with-fake-gcs-bucket,"['java', 'spring-boot', 'google-cloud-storage', 'integration-testing']",815,True,0,1
ASP.NET Core 6.0 Web API integration testing after migration to minimal hosting model,"<p>ASP.NET Core 6.0 introduces a new minimal hosting model:
<a href=""https://learn.microsoft.com/en-us/aspnet/core/migration/50-to-60-samples?view=aspnetcore-6.0"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/migration/50-to-60-samples?view=aspnetcore-6.0</a></p>
<p>After switching to the minimal hosting model, I wonder how to migrate the <code>IWebHost</code> building to be compatible with the new minimal hosting model.</p>
<p>Sample how we are currently building our <code>IWebHost</code> for integration tests (.NET 5):</p>
<pre><code>ServiceDescriptor[] grabbedServices = null;

var host = new WebHostBuilder()
    .UseStartup&lt;Startup&gt;()
    .ConfigureAppConfiguration((hostingContext, config) =&gt;
    {
        //some configuration here
    })
    .UseDefaultServiceProvider(x =&gt; x.ValidateScopes = true)
    .ConfigureTestServices(services =&gt; { grabbedServices = services.ToArray(); })
    .Build();
</code></pre>
<p>As after switching to minimal hosting model we do not have <code>Startup</code> anymore, this does not compile.
I sense that we should replace the <code>UseStartup&lt;Startup&gt;</code> part with <code>Configure</code>? If so, what's  the correct way how to construct the <code>IApplicationBuilder</code>?
Maybe there is some other way to build <code>IWebHost</code>?</p>
",https://stackoverflow.com/questions/74476594/asp-net-core-6-0-web-api-integration-testing-after-migration-to-minimal-hosting,"['c#', 'integration-testing', '.net-6.0', 'asp.net-core-6.0']",243,False,2,0
Integration testing with Testcontainers/Localstack and Spring Boot: Set directory for temporary files,"<p>I am using Testcontainers' (Localstack Module)[https://www.testcontainers.org/modules/localstack/] for advanced integration testing with Spring Boot, replacing the AmazonS3 client with the one from Localstack. I have set up my integration test roughly as follows (only relevant parts):</p>
<pre class=""lang-kotlin prettyprint-override""><code>// FurnitureDetailsControllerIT.kt

@Testcontainers
@SpringBootTest
@ExtendWith(SpringExtension::class)
@AutoConfigureMockMvc
@DirtiesContext
class FurnitureDetailsControllerIT {

  @Autowired
  private val amazonS3: AmazonS3? = null

  
  companion object {
    @Container
    var localStack: LocalStackContainer =
      LocalStackContainer(DockerImageName.parse(&quot;localstack/localstack:latest&quot;)).withServices(LocalStackContainer.Service.S3)

    @JvmStatic
    @DynamicPropertySource
    fun properties(registry: DynamicPropertyRegistry) {
      registry.add(&quot;cloud.aws.s3.endpoint&quot;) { localStack.getEndpointOverride(LocalStackContainer.Service.S3) }
      registry.add(&quot;cloud.aws.credentials.access-key&quot;) { localStack.accessKey }
      registry.add(&quot;cloud.aws.credentials.secret-key&quot;) { localStack.secretKey }
    }
  }
(...)
}
</code></pre>
<p>Everything runs fine when running the integration test locally (from my IDE or command line using Maven), meaning I can see the localstack container spinning up in the logs:</p>
<pre><code>13:54:16.360 [main] INFO 🐳 [remote-docker.artifactory.mycompany.com/localstack/localstack:0.13.0] - Container remote-docker.artifactory.mycompany.com/localstack/localstack:0.13.0 started in PT4.6099665S

</code></pre>
<p>However, when running on Jenkins, the build fails because of an error message.</p>
<pre><code>
2022-09-28 14:27:19.971  INFO 1185 --- [           main] ?.a.s.com/localstack/localstack:latest]  : Container remote-docker.artifactory.mycompany.com/localstack/localstack:latest is starting: ec383bda85f2636c3bef3f6b3938ac169636e4542244e3067b5184b6b03a6e35

2022-09-28 14:28:20.612 ERROR 1185 --- [           main] ?.a.s.com/localstack/localstack:latest]  : Could not start container

org.testcontainers.containers.ContainerLaunchException: Timed out waiting for log output matching '.*Ready\.
</code></pre>
<p>I guess it has to do with the temporary directory needed by Localstack. When running on my Windows machine I have to manually click on &quot;Share It&quot; before the test resumes:</p>
<p><a href=""https://i.stack.imgur.com/O4Akk.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/O4Akk.png"" alt=""Docker Desktop notification for file sharing (Windows)"" /></a></p>
<p>I suppose since the test is failing on Jenkins (because I cannot click on &quot;Share It&quot; there) starting the container will eventually time out and the test will fail.</p>
<p>I read that you can configure the directory using the <code>TMPDIR</code> environment variable as described in <a href=""https://docs.localstack.cloud/localstack/configuration/"" rel=""nofollow noreferrer"">https://docs.localstack.cloud/localstack/configuration/</a>. But using that variable is deprecated. What is the best way to set the temp directory to Jenkins working directory without having to explicitly conset to sharing that directory?</p>
<p>Note: I am already using Testcontainers' <a href=""https://www.testcontainers.org/modules/databases/mongodb/"" rel=""nofollow noreferrer"">MongoBD module</a> successfully, which starts a dockerized MongoDB instance. That works flawlessly, so I am not sure if it's an issue with Testcontainers or Localstack.</p>
",https://stackoverflow.com/questions/73881179/integration-testing-with-testcontainers-localstack-and-spring-boot-set-director,"['java', 'spring-boot', 'jenkins', 'testcontainers', 'localstack']",2106,True,1,1
Unable to inject custom filter while performing integration testing using Spring boot test,"<p>I have POST method in spring controller and I am trying to run test method on the controller using Test Rest template exchange.</p>
<p>Controller.java</p>
<pre><code>    @RequestMapping(path = &quot;/rest/projects&quot;)
    @RestController
    public class Controller {
    public static final Logger LOGGER = LoggerFactory.getLogger(Controller.class);
    private JwtTokenProvider jwtTokenProvider;
    private MailsService mailsService;

    @Autowired
    public Controller(MailsService mailsService, JwtTokenProvider jwtTokenProvider) {
        this.mailsService = mailsService;
        this.jwtTokenProvider = jwtTokenProvider;
    }

@PostMapping(value = &quot;/{projectId}/mails/filter/{type}&quot;)
    public ListDto getMails(@PathVariable(&quot;type&quot;) String mailType, @PathVariable(&quot;projectId&quot;) String projectId,
        @RequestParam(value = &quot;page_number&quot;, required = false) String pageNumber,
        @RequestParam(value = &quot;page_size&quot;, required = false) String pageSize,
        @RequestParam(value = &quot;search_query&quot;, required = false) String searchKeyword,
        @RequestParam(value = &quot;sort&quot;, required = false) String sortBy,
        @RequestParam(value = &quot;sort_direction&quot;, required = false) String sortDirection,
        @RequestBody MailSearchModel mailSearchModel) throws BackendError {
        //calls service 
    }
}
</code></pre>
<p>Here is my test method</p>
<p>ControllerTest.java</p>
<pre><code>    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public class ControllerTest {

    @Autowired
    private MockMvc mock;

    @Autowired
    private WebApplicationContext wac;

    @Autowired
    private RequestHeaderFilter requestHeaderFilter;

    @LocalServerPort
    private int port;

    TestRestTemplate restTemplate = new TestRestTemplate();

    HttpHeaders headers = new HttpHeaders();

    //Here i am trying to load Filter class in setup method

    @Before
    public void setUp() {
    mock = MockMvcBuilders.webAppContextSetup(wac)
            .addFilter(requestHeaderFilter).build();
    }


    @Test
    public void singleFieldProjectFields() throws Exception {

    ObjectMapper mapper = new ObjectMapper();
    MailSearchModel mailSearchModel = mapper.readValue(new File(&quot;./src/test/resources/SingleValueSchema.json&quot;),
            MailSearchModel.class);
    LinkedMultiValueMap&lt;String, String&gt; requestParams = new LinkedMultiValueMap&lt;&gt;();
    requestParams.add(&quot;sort_direction&quot;, &quot;DESC&quot;);
    requestParams.add(&quot;page_number&quot;, &quot;1&quot;);
    requestParams.add(&quot;sort&quot;, &quot;sentdate&quot;);
    requestParams.add(&quot;page_size&quot;, &quot;100&quot;);

    HttpEntity&lt;MailSearchModel&gt; entity = new HttpEntity&lt;MailSearchModel&gt;(mailSearchModel, headers);
    ResponseEntity&lt;String&gt; response = restTemplate.exchange(
            createURLWithPort(&quot;/rest/projects/{projectId}/mails/filter/{type}&quot;), HttpMethod.POST, entity,
            String.class,&quot;1879053221&quot;,&quot;inbox&quot;,requestParams);

    String actual = response.getHeaders().get(HttpHeaders.LOCATION).get(0);

    assertTrue(actual.contains(&quot;/mails&quot;));
}
</code></pre>
<p>Here is how my custom filter looks like</p>
<p>RequestHeaderFilter.java</p>
<pre><code>    @WebFilter(urlPatterns = &quot;/rest/*&quot;)
    @Order(1)
    public class RequestHeaderFilter implements Filter {
    private LocalizationHelper localizationHelper;
    private ObjectMapper jacksonObjectMapper;
    private JwtTokenProvider jwtTokenProvider;
    private BabylonCookieProvider babylonCookieProvider;
    private BabylonSessionService babylonSessionService;

    @Autowired
    public RequestHeaderFilter(LocalizationHelper localizationHelper, ObjectMapper 
    jacksonObjectMapper,
    JwtTokenProvider jwtTokenProvider, BabylonCookieProvider babylonCookieProvider, 
    BabylonSessionService babylonSessionService) {
    this.localizationHelper = localizationHelper;
    this.jacksonObjectMapper = jacksonObjectMapper;
    this.jwtTokenProvider = jwtTokenProvider;
    this.babylonCookieProvider = babylonCookieProvider;
    this.babylonSessionService = babylonSessionService;
    }

    @Override
    public void init(FilterConfig filterConfig) {
    // Do nothing
    }

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    // Add RequestId in request scope bean
    addRequestIdInSessionScope(httpRequest);

    // Check request authentication
    String auth = httpRequest.getHeader(&quot;Authorization&quot;);
    if (Utility.isNullOrEmpty(auth)) {
        ErrorDto errorDto = getErrorDto(HttpStatus.BAD_REQUEST, JwtConstants.TOKEN_MISSING);
        postErrorResponse(httpResponse, errorDto);
    } else {
        auth = auth.replace(JwtConstants.TOKEN_TYPE_BEARER, &quot;&quot;).trim();
        String tokenStatus = parseJweToken(auth);
        afterValidation(request, response, chain, auth, tokenStatus);
    }
  }
}
</code></pre>
<p>Here is the Main class</p>
<p>MobileApplication.java</p>
<pre><code>    @SpringBootApplication
    @ServletComponentScan
    public class MobileApplication {
       public static void main(String[] args) {
         SpringApplication.run(MobileApplication.class, args);
       }
     }
</code></pre>
<p>While i try to run my test i am getting the following error</p>
<pre><code>    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.oracle.cegbu.aconex.filter.RequestHeaderFilter': Cannot create inner bean '(inner bean)#6221ac7d' of type [com.oracle.cegbu.aconex.filter.RequestHeaderFilter] while setting bean property 'filter'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '(inner bean)#6221ac7d' defined in file [/Users/sachinhr/Aconex/ora-acx-spring-bff/build/classes/java/main/com/oracle/cegbu/aconex/filter/RequestHeaderFilter.class]: Unsatisfied dependency expressed through constructor parameter 4; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'babylonSessionService' defined in file [/Users/sachinhr/Aconex/ora-acx-spring-bff/build/classes/java/main/com/oracle/cegbu/aconex/service/auth/BabylonSessionService.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bffRestTemplate' defined in file [/Users/sachinhr/Aconex/ora-acx-spring-bff/build/classes/java/main/com/oracle/cegbu/aconex/common/delegate/BffRestTemplate.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseUrlProvider': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Circular placeholder reference 'instance' in property definitions
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:389) ~[spring-beans-5.3.15.jar:5.3.15]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:134) ~[spring-beans-5.3.15.jar:5.3.15]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1707) ~[spring-beans-5.3.15.jar:5.3.15]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1452) ~[spring-beans-5.3.15.jar:5.3.15]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619) ~[spring-beans-5.3.15.jar:5.3.15]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar:5.3.15]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar:5.3.15]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar:5.3.15]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar:5.3.15]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213) ~[spring-beans-5.3.15.jar:5.3.15]
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:212) ~[spring-boot-2.5.9.jar:2.5.9]
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:203) ~[spring-boot-2.5.9.jar:2.5.9]
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addServletContextInitializerBeans(ServletContextInitializerBeans.java:97) ~[spring-boot-2.5.9.jar:2.5.9]
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.&lt;init&gt;(ServletContextInitializerBeans.java:86) ~[spring-boot-2.5.9.jar:2.5.9]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getServletContextInitializerBeans(ServletWebServerApplicationContext.java:260) ~[spring-boot-2.5.9.jar:2.5.9]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.selfInitialize(ServletWebServerApplicationContext.java:234) ~[spring-boot-2.5.9.jar:2.5.9]
at org.springframework.boot.web.embedded.tomcat.TomcatStarter.onStartup(TomcatStarter.java:53) ~[spring-boot-2.5.9.jar:2.5.9]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5219) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_312]
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134) ~[na:1.8.0_312]
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:835) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_312]
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134) ~[na:1.8.0_312]
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:263) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:432) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:927) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.startup.Tomcat.start(Tomcat.java:486) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:123) ~[spring-boot-2.5.9.jar:2.5.9]
... 63 common frames omitted 
</code></pre>
<p>Its not able to instantiate Filter class and failing.</p>
",https://stackoverflow.com/questions/74203660/unable-to-inject-custom-filter-while-performing-integration-testing-using-spring,"['spring-boot', 'spring-mvc', 'integration-testing', 'spring-boot-test', 'mockmvc']",370,False,0,0
Override Host configuration in Integration Testing using ASP NET Core 6 Minimal APIs model,"<p>Being able to customize the Host configuration in integration tests is useful to avoid calling services that shouldn't run at all during testing. This was easily achievable using the standard <code>Startup</code> model, overriding the <code>CreateHostBuilder</code> from the <code>WebApplicationFactory</code>. I tried many many things using the &quot;Minimal APIs&quot; approach and couldn't figure it out.</p>
<p>A full example of what was possible using the <code>Startup</code> model, would be something like this:</p>
<p>Program.cs:</p>
<pre class=""lang-cs prettyprint-override""><code>public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =&gt;
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =&gt; { webBuilder.UseStartup&lt;Startup&gt;(); })
            // This is a service that downloads Configuration from the internet, to be used
            // as a source for `IConfiguration`, just like any `appsettings.json`.
            // I don't want this running during testing
            .AddConfigServer();
}
</code></pre>
<p>As you can imagine, the <code>AddConfigServer</code> calls an external web server to download the configuration I want to use in my app startup, but I definitely don't want my integration tests calling this external web server for several reasons: don't want to depend on external services, don't want to hammer my config server with testing requests, don't want my server customizations to be exposed to my tests, etc.</p>
<p>Using the <code>Startup</code> model, I could easily change this behavior with this:</p>
<pre class=""lang-cs prettyprint-override""><code>public class MyWebApplicationFactory : WebApplicationFactory&lt;Program&gt;
{
    protected override IHostBuilder CreateHostBuilder() =&gt;
        Host.CreateDefaultBuilder()
            // No AddConfigServer for my integration tests
            .ConfigureWebHostDefaults(webBuilder =&gt; { webBuilder.UseStartup&lt;Startup&gt;(); });
    }

    //... other customizations
}
</code></pre>
<p>However, trying this same approach throws an exception on my integration test startup:</p>
<pre><code>System.InvalidOperationException : No application configured. Please specify an application via IWebHostBuilder.UseStartup, IWebHostBuilder.Configure, or specifying the startup assembly via StartupAssemblyKey in the web host configuration.
</code></pre>
<p>Since I don't have a <code>Startup</code> class, I couldn't figure out how to properly do this. In fact, since this is common in all my web projects, I abandoned Minimal APIs altogether for the moment, until I figure out how to properly achieve this without a <code>Startup</code> class.</p>
<p>PS.: I have all the &quot;partial Program&quot; and &quot;InternalsVisibleTo&quot; in place, as described <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0#basic-tests-with-the-default-webapplicationfactory"" rel=""nofollow noreferrer"">here</a>.</p>
",https://stackoverflow.com/questions/72679169/override-host-configuration-in-integration-testing-using-asp-net-core-6-minimal,"['c#', 'asp.net-core', 'integration-testing', 'minimal-apis']",1380,False,3,1
How do you set jobrunr in run now/eager mode for spring integration testing,"<p>I must be missing something obvious. I've got a couple of jobrunr jobs where i'm using the lambda enqueue format version 5.1.6. Like this:</p>
<pre><code>JobId jobId = BackgroundJob.&lt;MyService&gt;enqueue(x -&gt; x.doWork());
</code></pre>
<p>I would like to validate the plumbing and work in the jobs is executing via some integration tests with Spring, but don't see the options to run now, eager mode, etc?  Thanks</p>
",https://stackoverflow.com/questions/73169265/how-do-you-set-jobrunr-in-run-now-eager-mode-for-spring-integration-testing,['jobrunr'],211,True,1,1
How to make a request to the database for integration testing in Jenkins pipeline?,"<p>When compiling a spring boot project, integration tests are performed with requests to an external database, but a connection error occurs in Jenkins at the compilation stage. How do I set up a database connection?
The screenshots show an error message.</p>
<p><a href=""https://i.stack.imgur.com/qcee4.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
",https://stackoverflow.com/questions/72280245/how-to-make-a-request-to-the-database-for-integration-testing-in-jenkins-pipelin,"['spring', 'jenkins', 'jenkins-pipeline', 'jenkins-plugins', 'integration-testing']",168,False,0,0
Spring Boot Integration Testing error with Junit5 and h2 “java.lang.IllegalStateException: Failed to load ApplicationContext”,"<p>I have been trying to run this integration test, but I keep getting this error message saying that <code>java.lang.IllegalStateException: Failed to load ApplicationContextat</code></p>
<pre><code>org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:248)
</code></pre>
<p>And I’m not exactly sure why this is happening in terms of how I set up the file. If anyone knows the reason let me know pls.</p>
<p>this is the file inside src/test/java/com/flexcar.task_manager</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>package com.flexcar.task_manager;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flexcar.task_manager.task.Task;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.WebApplicationContext;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class TaskControllerIntegrationTest {
    @LocalServerPort
    private int port;

    private String baseUrl = ""http://localhost"";
    @Autowired
    private WebApplicationContext webApplicationContext;
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    private static RestTemplate restTemplate;

    @Autowired
    private TestH2Repository h2Repository;
    @BeforeAll
    public static void init() {
        restTemplate = new RestTemplate();
    }

    @BeforeEach

    public void setUp() {
        baseUrl = baseUrl.concat("":"").concat(port + """").concat(""/api/v1"");
    }



    @Test
    public void postTaskCheck() throws Exception {
        Task first = new Task(2L, System.currentTimeMillis(), ""car break"", ""Pls finish ASAP"", ""A"", ""B"", ""C"", ""D"", ""E"", 1234567891011L, false, ""H"", true);
//        String postValue = OBJECT_MAPPER.writeValueAsString(first);
//        MvcResult result = mockMvc.perform(post(""/api/v1/newtask"")
//                .contentType(MediaType.APPLICATION_JSON)
//                .content(postValue))
//                .andExpect(status().isCreated())
//                .andDo(print())
//                .andReturn();
//        return OBJECT_MAPPER.readValue(result.getResponse().getContentAsString(), Task.class);
        Task response = restTemplate.postForObject(baseUrl.concat(""newtask""), first, Task.class);
        assertEquals(""car break"", response.getType());
        assertEquals(4, h2Repository.findAll().size());
    }

}</code></pre>
</div>
</div>

this is the file for pom.xml</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>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns=""http://maven.apache.org/POM/4.0.0"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
    xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd""&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.7.4&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;
    &lt;groupId&gt;com.flexcar&lt;/groupId&gt;
    &lt;artifactId&gt;task_manager&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
    &lt;name&gt;task_manager&lt;/name&gt;
    &lt;description&gt;Provide a logic based task management solution for vehicle service team members at Flexcar.&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.junit.vintage&lt;/groupId&gt;
            &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
            &lt;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.hamcrest&lt;/groupId&gt;
                    &lt;artifactId&gt;hamcrest-core&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.h2database&lt;/groupId&gt;
            &lt;artifactId&gt;h2&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&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-web&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-validation&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.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter&lt;/artifactId&gt;
            &lt;version&gt; 5.6.2&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
            &lt;artifactId&gt;spring-security-test&lt;/artifactId&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;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.mockito&lt;/groupId&gt;
            &lt;artifactId&gt;mockito-junit-jupiter&lt;/artifactId&gt;
            &lt;version&gt;3.2.4&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.postgresql&lt;/groupId&gt;
            &lt;artifactId&gt;postgresql&lt;/artifactId&gt;
            &lt;scope&gt;runtime&lt;/scope&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;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;junit&lt;/groupId&gt;
                    &lt;artifactId&gt;junit&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.jayway.jsonpath&lt;/groupId&gt;
            &lt;artifactId&gt;json-path&lt;/artifactId&gt;
            &lt;version&gt;2.5.0&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.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
            &lt;/plugin&gt;
&lt;!--            &lt;plugin&gt;--&gt;
&lt;!--                &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;--&gt;
&lt;!--                &lt;version&gt;2.22.0&lt;/version&gt;--&gt;
&lt;!--            &lt;/plugin&gt;--&gt;
        &lt;/plugins&gt;
        &lt;resources&gt;
            &lt;resource&gt;
                &lt;directory&gt;src/main/resources&lt;/directory&gt;
                &lt;filtering&gt;true&lt;/filtering&gt;
            &lt;/resource&gt;
        &lt;/resources&gt;
    &lt;/build&gt;

&lt;/project&gt;</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/74136765/spring-boot-integration-testing-error-with-junit5-and-h2-java-lang-illegalstate,"['java', 'spring-boot', 'integration', 'h2', 'junit5']",267,False,0,0
How to save entities along with their related entities in spring boot integration testing?,"<p>I have an integration test on a endpoint of creating a user with its related entities. It turns out that the related entities were not persisted with the user entity.</p>
<p>However, it is working fine when running the normal spring boot application. Is it possible to achieve this during testing?</p>
<p>This is the log when running the integration test of the endpoint</p>
<p><a href=""https://i.stack.imgur.com/7bi14.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/7bi14.png"" alt=""This is the log when running the integration test of the endpoint"" /></a></p>
<p>And this is the log when calling from Postman to the normal application</p>
<p><a href=""https://i.stack.imgur.com/Q7DEg.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Q7DEg.png"" alt=""this is the log when calling from Postman to the normal application"" /></a></p>
<p>as you can notice the roles are not inserted to the <code>rel_mi_user__mi_user_role</code> table during integration testing.</p>
<p>The setup source code for the integration test is shown below</p>
<pre><code>@Autowired
private PasswordEncoder passwordEncoder;

@Autowired
private MockMvc mockMvc;

@Autowired
private MiMiUserRepository miMiUserRepository;

private static Logger log = LoggerFactory.getLogger(MiMiUserResourceIT.class);

@Test
@Transactional
void testRegisterBackOfficeUser() throws Exception {
    MiMiUserRegistrationDTO userRegistrationDTO = new MiMiUserRegistrationDTO();
    userRegistrationDTO.setPassword(&quot;test12345&quot;);
    userRegistrationDTO.setEmail(&quot;john@gmail.com&quot;);
    userRegistrationDTO.setContactNo(&quot;0188991122&quot;);
    userRegistrationDTO.setUserRoles(List.of(&quot;BACKOFFICE&quot;));
    MiMiUserProfileRegistrationDTO profile = new MiMiUserProfileRegistrationDTO();
    profile.setSalutation(&quot;Mr&quot;);
    profile.setFirstName(&quot;John&quot;);
    profile.setLastName(&quot;Lee&quot;);
    userRegistrationDTO.setProfile(profile);

    mockMvc
        .perform(
            post(&quot;/v1/p/user/register/back-office&quot;)
                .contentType(MediaType.APPLICATION_JSON)
                .content(TestUtil.convertObjectToJsonBytes(userRegistrationDTO))
        )
        .andExpect(status().isCreated());
    MiUser u = miMiUserRepository.findOneWithMiUserRolesByEmailIgnoreCase(userRegistrationDTO.getEmail()).get();
    assertThat(u.getUserStatus()).isEqualTo(UserStatus.NEW);
}
</code></pre>
",https://stackoverflow.com/questions/72216243/how-to-save-entities-along-with-their-related-entities-in-spring-boot-integratio,"['java', 'spring-boot', 'spring-data-jpa', 'integration-testing']",250,False,0,1
How do I separate between integration testing and unit testing using Hapi in Node.js?,"<p>How do I separate between integration testing and unit testing using Hapi in Node.js?</p>
<p>I am trying to reduce the testing time in our automations for every time we update a unit within our API.</p>
<p>I was wondering can I just create two new folders test/unit and test/int to separate the scripts and what would the update to the package.json require?</p>
<p>I have the following in the package.json which runs the .labrc.js
package.json</p>
<pre><code>    &quot;test&quot;: &quot;npm run version-stamp &amp;&amp; lab --bail -t 80 -r html -o coverage.html -r console -o stdout -r junit -o TestResult.xml -r lcov -o coverage.dat&quot;,
    &quot;simple-test&quot;: &quot;npm run version-stamp &amp;&amp; lab&quot;,
    &quot;test-int&quot;: &quot;not sure what to put here&quot;,
</code></pre>
<p>labrc.js</p>
<pre><code>module.exports = {
    verbose: true,
    timeout: 7500,
    lint: true,
    paths: [
        &quot;test/init/aws&quot;,
        &quot;test/unit/plugins&quot;,
        &quot;test/unit/utils&quot;,
        &quot;test/unit/routes&quot;
    ],
</code></pre>
",https://stackoverflow.com/questions/74690668/how-do-i-separate-between-integration-testing-and-unit-testing-using-hapi-in-nod,"['node.js', 'unit-testing', 'jestjs', 'nunit', 'hapi.js']",52,False,0,1
"When and where to use JUnit, Mockito and Integration testing in Spring Boot Application?","<p>I'm very novice to Unit Testing, I have created a Spring Boot Application and now I want to do some testing what's confusing me is where to use what e.g. I have classes and interfaces Controllers, Service, Repository I know each will have it's own Test class, so what will I be using let's say in Controllers, JUnit or Mockito ? similar question for Service and Repository.</p>
",https://stackoverflow.com/questions/74489307/when-and-where-to-use-junit-mockito-and-integration-testing-in-spring-boot-appl,"['java', 'spring-boot', 'mockito', 'junit5']",208,True,0,1
How is Flink integration testing working without the documented flink-test-utils dependency or MiniClusterWithClientResource?,"<p>I'm using Flink 1.15.1 and JUnit5. I would like to know how the following integration test, adapted from the <a href=""https://nightlies.apache.org/flink/flink-docs-release-1.15/docs/dev/datastream/testing/#testing-flink-jobs"" rel=""nofollow noreferrer"">documentation</a>, works without the inclusion of the <code>flink-test-utils</code> dependency and the <code>MiniClusterWithClientResource</code> static instance.</p>
<pre><code>package com.mypackage;

import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.junit.jupiter.api.Test;

public class ExampleIntegrationTest {

  @Test
  public void testIncrementPipeline() throws Exception {
    StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

    // configure your test environment
    env.setParallelism(2);

    // values are collected in a static variable
    CollectSink.values.clear();

    // create a stream of custom elements and apply transformations
    env.fromElements(1L, 21L, 22L).map(n -&gt; n + 1).addSink(new CollectSink());

    // execute
    env.execute();

    // verify your results
    assertTrue(CollectSink.values.containsAll(List.of(2L, 22L, 23L)));
  }

  // create a testing sink
  private static class CollectSink implements SinkFunction&lt;Long&gt; {

    // must be static
    public static final List&lt;Long&gt; values = Collections.synchronizedList(new ArrayList&lt;&gt;());

    @Override
    public void invoke(Long value, SinkFunction.Context context) throws Exception {
      values.add(value);
    }
  }
}
</code></pre>
<p>Am I missing something crucial by not including the <code>flink-test-utils</code> dependency and the <code>MiniClusterWithClientResource</code> static instance that make my integration tests incorrect? The documentation is specific that those are required.</p>
",https://stackoverflow.com/questions/73297418/how-is-flink-integration-testing-working-without-the-documented-flink-test-utils,"['apache-flink', 'flink-streaming']",435,True,1,2
Integration testing with Quarkus and Redis how do I set a state with the redis?,"<p>Hi I have my test class annotated with the</p>
<pre class=""lang-java prettyprint-override""><code>@QuarkusIntegrationTest
</code></pre>
<p>I wanna run the following test</p>
<pre class=""lang-java prettyprint-override""><code>
        given()
                .contentType(MediaType.APPLICATION_JSON)
                .pathParam(&quot;id&quot;, id)
                .when()
                .get(&quot;/user/presence/{id}&quot;)
                .then()
                .statusCode(Response.Status.OK.getStatusCode())
    }
</code></pre>
<p>This gets the user presence and the presence is stored inside a redis cache.</p>
<p>I wanna do a setup step that puts the presence into my redis cache before the test begins. However, my redis cache is not exposed on any endpoint so i'm not able to set it via HTTP calls.</p>
<p>The redis class i want to test is</p>
<pre class=""lang-java prettyprint-override""><code>@ApplicationScoped
</code></pre>
<p>This seems to be needed since the constructor sets a RedisDataSoruce</p>
<pre class=""lang-java prettyprint-override""><code>    public MyRedisCache(RedisDataSource ds) {
        this.commands = ds.string(MyClass.class);
    }
</code></pre>
<p>But this makes me unable to use this perticular class instance inside my integration tests. So how can I put values into this redis before my test begins</p>
",https://stackoverflow.com/questions/74059658/integration-testing-with-quarkus-and-redis-how-do-i-set-a-state-with-the-redis,"['java', 'testing', 'redis', 'integration', 'quarkus']",260,False,0,1
sync problem with 2 InMemory DbContext with same name and different Models in integration testing,"<p>We have an application in which we have separated read model and write model.
write model is a DDD approach with rich domain models and read model is just a class library in which we have scaffolded the database. its an anemic domain model just for read purposes.</p>
<p>this is write model DbContext:</p>
<pre><code>public class AppraisalDbContext : DbContext
{
    public AppraisalDbContext(DbContextOptions&lt;AppraisalDbContext&gt; options) : base(options)
    {
    }

    public DbSet&lt;Appraisal&gt; Appraisals { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppraisalMapping).Assembly);

    }
}
</code></pre>
<p>this is Appraisal in write model(domain model):</p>
<pre><code>public class Appraisal : BaseEntity, IAggregateRoot
{

    protected Appraisal()
    {

    }
    public Appraisal(string title)
    {
        SetTitle(title);
    }
    .
    .
    .
}
</code></pre>
<p>and this is read model DbContext:</p>
<pre><code>public partial class Appraisal360DbContext : DbContext
{
    public Appraisal360DbContext()
    {
    }

    public Appraisal360DbContext(DbContextOptions&lt;Appraisal360DbContext&gt; options)
        : base(options)
    {
    }
    public virtual DbSet&lt;Appraisal&gt; Appraisals { get; set; } = null!;
}
</code></pre>
<p>and this is read model Appraisal:</p>
<pre><code>public partial class Appraisal
{
    public string Title { get; set; } = null!;
}
</code></pre>
<p>As you can see we have 2 different DbContext with different models.</p>
<p>Now I have created a custom class which is derived from WebApplicationFactory:</p>
<pre><code>public class CustomWebApplicationFactory : WebApplicationFactory&lt;Program&gt;
{
    private static readonly InMemoryDatabaseRoot InMemoryDatabaseRoot = new InMemoryDatabaseRoot();
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        
        builder.ConfigureAppConfiguration(configurationBuilder =&gt;
        {
            var integrationConfig = new ConfigurationBuilder()
                .AddJsonFile(&quot;appsettings.json&quot;)
                .AddEnvironmentVariables()
                .Build();

            configurationBuilder.AddConfiguration(integrationConfig);
        });

        builder.ConfigureServices((builder, services) =&gt;
        {
            services
                .Remove&lt;DbContextOptions&lt;Appraisal360DbContext&gt;&gt;()
                .AddDbContext&lt;Appraisal360DbContext&gt;((sp, options) =&gt;
                    options.UseInMemoryDatabase(&quot;AppraisalDb&quot;,InMemoryDatabaseRoot));

            services
                .Remove&lt;DbContextOptions&lt;AppraisalDbContext&gt;&gt;()
                .AddDbContext&lt;AppraisalDbContext&gt;((sp, options) =&gt;
                    options.UseInMemoryDatabase(&quot;AppraisalDb&quot;, InMemoryDatabaseRoot));
        });
        
        builder.UseEnvironment(&quot;Test&quot;);

    }
}
</code></pre>
<p>We expect both DbContexts to refer to one in-memory database. but when we create an Appraisal using AppraisalDbContext(write model) the data is not persisted in Appraisal360DbContext(read model) and vice versa.</p>
<p>I tried to use Sqlite but since I have a column with BIN2_COLLATE, Sqlite doesn't support this option. I have also configured Always Encrypted and that is another reason why I can't use Sqlite in-memory database.</p>
<p>I appriciate any help. any suggestion. any recommendation.</p>
<p>Thank you for your time.</p>
",https://stackoverflow.com/questions/74613514/sync-problem-with-2-inmemory-dbcontext-with-same-name-and-different-models-in-in,"['c#', 'entity-framework', 'integration-testing', 'in-memory-database']",34,False,0,0
Dotnet 6 Xunit integration testing EnsureSuccessStatusCode gives Response status code does not indicate success: 500,"<p>Hello I'm learning integration testing and I want to test a 'POST' method from my controller using xunit and WebApplicationFactory But I'm getting this exception</p>
<p>System.Net.Http.HttpRequestException : Response status code does not indicate success: 400 (Bad Request).</p>
<p>This is my Test:</p>
<pre><code>using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
using System.Text;
using Newtonsoft.Json;

namespace integrationtest.IntegrationTests;

public class ControllerTest  : IClassFixture&lt;TestingWebAppFactory&lt;Program&gt;&gt;
{
    private readonly HttpClient _client;
    public ControllerTest(TestingWebAppFactory&lt;Program&gt; factory) 
        =&gt; _client = factory.CreateClient();

    

    [Fact]
    public async Task AddAccountTest()
    {
        var postRequest = new HttpRequestMessage(HttpMethod.Post, &quot;/api/Accounts/Register&quot;);
        
        var formModel = new RegisterInputModel{
            UserName= &quot;newuser111&quot;,
            Email = &quot;newuser@example.com&quot;,
            PhoneNumber = &quot;111222333&quot;,
            Password= &quot;Gamma2205!&quot;,
            ConfirmPassword= &quot;Gamma2205!&quot;
            } ; 
        var stringPayload = JsonConvert.SerializeObject(formModel);
        postRequest.Content = new StringContent(stringPayload, Encoding.UTF8, &quot;application/json&quot;);


        var response = await _client.SendAsync(postRequest); 

        response.EnsureSuccessStatusCode(); 
        response.IsSuccessStatusCode.Equals(true); 

        var responseString = await response.Content.ReadAsStringAsync(); 
        Assert.Contains(&quot;1&quot;, responseString); 
    }
}
</code></pre>
<p>This is my controller function</p>
<pre><code>[AllowAnonymous]
        [HttpPost]
        public async Task&lt;ActionResult&lt;Response&gt;&gt; Register(RegisterInputModel userRegiterModel)
        {
            HttpContext.Items.Add(&quot;action&quot;,&quot;Accounts.Register&quot;);
            await _accountsService.Register(userRegiterModel);
            return Ok(new ResponseSuccess(&quot;User Registered Successfully&quot;, &quot;Accounts.Register&quot;));
        }
</code></pre>
<p>This is the service</p>
<pre><code>public async Task&lt;IdentityResult&gt; Register(RegisterInputModel userRegiterModel)
        {
        
            try
            {
                ApplicationUser registrationUser = new ApplicationUser()
                {
                    Email = userRegiterModel.Email,
                    UserName = userRegiterModel.UserName,
                    PhoneNumber = userRegiterModel.PhoneNumber
                };
               

                IdentityResult result = await _userManager.CreateAsync(registrationUser, userRegiterModel.Password);
                if (!result.Succeeded)
                {
                    IdentityErrorDescriber errorDescriber = new IdentityErrorDescriber();
                    IdentityError primaryError = result.Errors.FirstOrDefault();

                    if (primaryError.Code == nameof(errorDescriber.DuplicateEmail))
                    {
                        throw new Exception(&quot;Email already exists.&quot;);
                    }
                    else if (primaryError.Code == nameof(errorDescriber.DuplicateUserName))
                    {
                        //_logger.LogError($&quot;Username already exists: {registrationUser.UserName}&quot;);
                        throw new Exception(&quot;Username already exists.&quot;);
                    }
                    else
                    {
                        throw new Exception(primaryError.Description);
                    }
                }
                else
                {
                    return result;
                }
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex.ToString());
                throw new Exception(ex.Message);
            }

        }
</code></pre>
",https://stackoverflow.com/questions/71515164/dotnet-6-xunit-integration-testing-ensuresuccessstatuscode-gives-response-status,"['c#', 'asp.net', '.net', 'xunit.net']",353,False,0,0
TRPC Test Wrapper for unit and integration testing using jest and react testing library - client mock,"<p>How do you mock the TRPC client for unit and integration testing using jest and react testing library?</p>
",https://stackoverflow.com/questions/74530192/trpc-test-wrapper-for-unit-and-integration-testing-using-jest-and-react-testing,"['reactjs', 'react-native', 'unit-testing', 'testing', 'trpc.io']",333,False,0,1
Integration testing for if JMS Message sent to SQS queue ends up in Dead Letter Queue,"<p>I'm trying to create integration tests for a <a href=""https://docs.oracle.com/javaee/7/api/javax/jms/MessageListener.html"" rel=""nofollow noreferrer"">MessageListener</a> that is processing messages from a SQS queue. One of the test cases I would like to verify is that an improperly formatted message sent to the <code>MessageListener</code> ends up in the Dead Letter Queue (also an SQS queue) that has been setup in the AWS console.</p>
<p>I'm having difficulty figuring out how to test this though, as you cannot search the Dead Letter Queue queue for a specific message id (i.e. see if it contains a message) without sifting through all the messages. My initial thought was to poll the dead letter queue and verify that the message id exists in there but it seems like that will have some problems. The integration test will send a message to the actual queue in our testing environment, so there may be an unknown number of other messages already present in the dead letter queue (and the messages in the dead letter queue could be continuously increasing). I also tried using some of the properties associated with a <a href=""https://docs.oracle.com/javaee/7/api/javax/jms/Message.html"" rel=""nofollow noreferrer"">JMS message</a>, but it seems like they aren't updated in my local instance of the message when the message goes from the test -&gt; SQS queue -&gt; <code>MessageListener</code>. Any ideas on how to test this scenario?</p>
<p>Here's an example of how the <code>MessageListener</code> is setup:</p>
<pre class=""lang-java prettyprint-override""><code>public class ExampleMessageListener implements MessageListener {

    @Override
    public void onMessage(final Message message) {
        // message handling logic
        
        // if something goes wrong in message handling logic message won't be acknowledged
        // and should end up in the DLQ 
        message.acknowledge()

    }
}
</code></pre>
<p>How I'm sending the message to the queue the <code>MessageListener</code> is consuming in my integration test:</p>
<pre class=""lang-java prettyprint-override""><code>SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
    new ProviderConfiguration(),
    AmazonSQSClientBuilder.standard()
                          .withRegion(config.getRegion().getName())
                          .withCredentials(config.getCredentialsProvider())
   );
        
SQSConnection connection = connectionFactory.createConnection();
session = connection.createSession(false, SQSSession.UNORDERED_ACKNOWLEDGE);
final Queue queue = session.createQueue(&quot;SQS-queue-name&quot;);
this.messageProducer = session.createProducer(queue);
final TextMessage textMessage = session.createTextMessage(&quot;improper message&quot;);
messageProducer.send(textMessage);
</code></pre>
<p>One additional note: There's a database that the <code>MessageListener</code> is modifying, and I'm able to use that to check if the properly formatted messages are changing data as expected. Improperly formatted messages don't end up interacting with this database though.</p>
<p>Keep in mind that Amazon SQS <a href=""https://github.com/awslabs/amazon-sqs-java-messaging-lib/issues/4"" rel=""nofollow noreferrer"">doesn't support message selectors</a> via their JMS client implementation.</p>
",https://stackoverflow.com/questions/73815351/integration-testing-for-if-jms-message-sent-to-sqs-queue-ends-up-in-dead-letter,"['testing', 'jms', 'integration-testing', 'amazon-sqs']",367,False,0,0
"C# MVC Integration Testing, I Can&#39;t Get Logout Test to Succeed. I Created A Minimum Reproducable Example","<p>I build a small C# App with Identity and I Scaffolded Register, Login, LogOut, and RegisterConfirmation. It has a sqlite database and I built it for the purpose of creating an Integration Test that properly logs a user in and then out. I can register a user easily in an integration test like this:</p>
<pre><code>var newAntiForg = await client.GetAsync(&quot;/Identity/Account/Register&quot;);
var antiForgeryValues = await AntiForgeryTokenExtractor.ExtractAntiForgeryValues(newAntiForg);
var postRequest2 = new HttpRequestMessage(HttpMethod.Post, &quot;/Identity/Account/Register&quot;);
postRequest2.Headers.Add(&quot;Cookie&quot;, new CookieHeaderValue(AntiForgeryTokenExtractor.AntiForgeryCookieName, antiForgeryValues.cookieValue).ToString());
var formModel = new Dictionary&lt;string, string&gt;
{
    { AntiForgeryTokenExtractor.AntiForgeryFieldName, antiForgeryValues.fieldValue },
    { &quot;Input.Email&quot;, &quot;test2@example.com&quot; },                
    { &quot;Input.Password&quot;, &quot;pas3w02!rRd&quot; },
    { &quot;Input.ConfirmPassword&quot;, &quot;pas3w02!rRd&quot; }
};

postRequest2.Content = new FormUrlEncodedContent(formModel);
var response = await client.SendAsync(postRequest2);
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
</code></pre>
<p>But I can't logout. My attempt at logout fails on EnsureSuccessStatusCode():</p>
<pre><code>var postRequestLogout = new HttpRequestMessage(HttpMethod.Post, &quot;/Identity/Account/Logout&quot;);
postRequestLogout.Headers.Add(&quot;Cookie&quot;, new CookieHeaderValue(AntiForgeryTokenExtractor.AntiForgeryCookieName, antiForgeryValues.cookieValue).ToString());
var formModel2 = new Dictionary&lt;string, string&gt;
{
    { AntiForgeryTokenExtractor.AntiForgeryFieldName, antiForgeryValues.fieldValue },
};
postRequestLogout.Content = new FormUrlEncodedContent(formModel2);

var logoutAnswer = await client.SendAsync(postRequestLogout);
Console.WriteLine(logoutAnswer.StatusCode);
logoutAnswer.EnsureSuccessStatusCode();
</code></pre>
<p>I have all of the source code for my example here: <a href=""https://github.com/ChristianOConnor/amaranth-minal-testing-example.git"" rel=""nofollow noreferrer"">https://github.com/ChristianOConnor/amaranth-minal-testing-example.git</a>.</p>
<p>How do I get the logout in an Integration Test to succeed?</p>
",https://stackoverflow.com/questions/72591299/c-mvc-integration-testing-i-cant-get-logout-test-to-succeed-i-created-a-mini,"['c#', 'asp.net', 'sqlite', 'razor', 'integration-testing']",81,False,0,0
How can we test the fromDate and toDate in integration testing. following are the code for the Date,"<p>How to test the last and current 3 month date in the flutter.
Is anyone having the solution for that.</p>
<pre><code>    RichText(
                        text: TextSpan(children: [
                          TextSpan(
                              text: DateTimeHelper.getFormattedDateTime(fromDate,
                                  dateFormat: DateTimeHelper.dateOnlyText),
                              style: TextStyle(
                                  fontSize: 16, fontWeight: FontWeight.w600)),
                          TextSpan(text: &quot; to &quot;),
                          TextSpan(
                              text: DateTimeHelper.getFormattedDateTime(toDate,
                                  dateFormat: DateTimeHelper.dateOnlyText),
                              style: TextStyle(
                                  fontSize: 16, fontWeight: FontWeight.w600)),
                        ]),
                      ),


  
</code></pre>
",https://stackoverflow.com/questions/71467039/how-can-we-test-the-fromdate-and-todate-in-integration-testing-following-are-th,"['flutter', 'dart', 'flutter-dependencies', 'flutter-web', 'flutter-integration-test']",86,False,0,2
How to do unit testing and how it is different from integration testing in frameworks like Django and fastapi?,"<p>Let's say I have a Fastapi application like this (This code is taken from documentations):</p>
<pre class=""lang-py prettyprint-override""><code>app = FastAPI()

@app.get(&quot;/foo&quot;)
async def read_main():
    return {&quot;msg&quot;: &quot;Hello World&quot;}
</code></pre>
<p>I believe there are two ways of testing this view. The first one is by the use of a client object. For instance:</p>
<pre class=""lang-py prettyprint-override""><code>client = TestClient(app)

def test_read_main():
    response = client.get(&quot;/&quot;)
    assert response.status_code == 200
    assert response.json() == {&quot;msg&quot;: &quot;Hello World&quot;}
</code></pre>
<p>However, I think this is not a unit test. It is more like an integration test. Because we are actually running fastapi codes as well.
The second option which in my opinion is closer to unit test definition is to run the function directly:</p>
<pre class=""lang-py prettyprint-override""><code>def test_read_main():
    response = read_main()
    assert response == {&quot;msg&quot;: &quot;Hello World&quot;}
</code></pre>
<p>Similarly, in Django, we can directly call the view function, or by using a client object.
My first question is which one is better?</p>
<p>Let's say we chose one of them and now in order to prevent calling the database I have mocked the database. Now I want to test a view that just checks if something exists in the database. My second question is what is the point of testing such view? Becuase after mocking the database, we know what would happen when calling the database with given arguments.</p>
",https://stackoverflow.com/questions/71957694/how-to-do-unit-testing-and-how-it-is-different-from-integration-testing-in-frame,"['django', 'unit-testing', 'mocking', 'integration-testing', 'fastapi']",297,False,0,0
How to automate native features (like take image in camera) or pop-ups (tapping on allow or deny) in flutter integration testing,"<p>Every time I log in to my flutter app using integration test script &quot;Allow user to access contact&quot; pop up will be displayed which is a native component. I could not access or tap those pop ups using flutter test driver. Is there a way to automate those process or any work around for it?</p>
",https://stackoverflow.com/questions/73402232/how-to-automate-native-features-like-take-image-in-camera-or-pop-ups-tapping,"['flutter', 'flutter-test', 'automation-testing']",187,True,1,1
"C# NetCore WebAPI integration testing: HttpClient uses HTTPS for GET request, but then uses only HTTP for the POST request, and fails with Forbidden","<p>I am working on some very simple API endpoints using Net Core 6. Along with these endpoints, I want to implement integration test for them.</p>
<p>For the integration tests, I am using <a href=""https://xunit.net/"" rel=""nofollow noreferrer"">xunit</a> together with <a href=""https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.testing?view=aspnetcore-6.0"" rel=""nofollow noreferrer"">Microsoft.AspNetCore.Mvc.Testing</a>, particularly <a href=""https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.testing.webapplicationfactory-1?view=aspnetcore-6.0"" rel=""nofollow noreferrer"">WebApplicationFactory</a> to set up the SUT.</p>
<p>So far, I have two API endpoints:</p>
<ol>
<li>Ping: Accepts GET. Always returns &quot;pong&quot;.</li>
<li>SignIn: Accepts POST. Implements a SignIn functionality.</li>
</ol>
<p>PROBLEM: The test for the Ping request is successful. The SUT seems to be set up correctly, the HttpClient does de request, and I get the expected result &quot;pong&quot;. HOWEVER, when I run the test for SignIn, the SUT seems to be running correctly, but <strong>the POST request never reaches the backend. The response of the request is a 403 Forbidden, instead of the expected 401 Unauthorized.</strong></p>
<p>My debugging so far:</p>
<ol>
<li>The SignIn and Ping endpoints work as expected. When I run the WebAPI project on Kestrel, and issue requests from Postman, I get the expected results. The problem is inside the integration tests.</li>
<li>The base URL for the HttpClient in both tests is supposed to be http://localhost. When the Ping test is executed, the RequestUri is then changed to https://localhost. I assume this happens because I have <code>app.UseHttpsRedirection()</code> . <strong>However, when the SignUp test is executed, the RequestUri is not changed to https. I think this is the cause of the 403 response, but so far I haven't been able to solve the issue</strong>.</li>
</ol>
<p>The HTTP response for PingTest</p>
<pre><code>response
{StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Content-Type: text/plain; charset=utf-8
}}
    Content: {System.Net.Http.StreamContent}
    Headers: {}
    IsSuccessStatusCode: true
    ReasonPhrase: &quot;OK&quot;
    RequestMessage: {Method: GET, RequestUri: 'https://localhost/api/template/ping', Version: 1.1, Content: &lt;null&gt;, Headers:
{
}}
    StatusCode: OK
    TrailingHeaders: {}
    Version: {1.1}

</code></pre>
<p>The HTTP response for SigInTest:</p>
<pre><code>response
{StatusCode: 403, ReasonPhrase: 'Forbidden', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Content-Type: application/problem+json; charset=utf-8
}}
    Content: {System.Net.Http.StreamContent}
    Headers: {}
    IsSuccessStatusCode: false
    ReasonPhrase: &quot;Forbidden&quot;
    RequestMessage: {Method: POST, RequestUri: 'http://localhost/api/template/sign-in', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Content-Type: application/json; charset=utf-8
  Content-Length: 35
}}
    StatusCode: Forbidden
    TrailingHeaders: {}
    Version: {1.1}
    _content: {System.Net.Http.StreamContent}
    _disposed: false
    _headers: {}
    _reasonPhrase: null
    _requestMessage: {Method: POST, RequestUri: 'http://localhost/api/template/sign-in', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Content-Type: application/json; charset=utf-8
  Content-Length: 35
}}
    _statusCode: Forbidden
    _trailingHeaders: {}
    _version: {1.1}
</code></pre>
<p>I appreciate any help that you, my fellow computer guy, can offer.</p>
<p>My code:</p>
<p>Program.cs</p>
<pre><code>using System.Text;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var services = builder.Services;

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection(); // &lt;-- IMPORTANT

app.UseAuthorization();
app.UseAuthentication();

app.MapControllers();

app.Run();

public partial class Program { } 

</code></pre>
<p>TemplateController.cs (API endpoints)</p>
<pre><code>namespace foo;

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[Route(&quot;api/template&quot;)]
[RequireHttps]
[ApiController]
public class TemplateController : ControllerBase
{
    public TemplateController(){    }

    [Route(&quot;sign-in&quot;)]
    [HttpPost]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status403Forbidden)]
    [ProducesResponseType(StatusCodes.Status500InternalServerError)]
    public ActionResult&lt;User&gt; SignIn(AuthRequestDto credentials)
    {
        if (credentials == null) return Unauthorized(&quot;Missing credentials.&quot;); //Integration tests never reach this line. If I reach this line, I am good. 

        try
        {
            //Call to auth library 
            var (user, tokens) = _authService.SignIn(credentials.UserName, credentials.Password);
            //Handle library's response. 
            return Ok();
        }
        catch (ArgumentException e) //&lt;-- Thrown when auth fails. Replies with a 401, not a 403 
        {
            return Unauthorized(e.Message);
        }
        catch (InvalidOperationException e)
        {
            return Problem(detail: e.Message, title: &quot;Server error&quot;);
        }
    }

    [Route(&quot;ping&quot;)]
    [HttpGet]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public ActionResult&lt;string&gt; Ping()
    {
        return Ok(&quot;pong&quot;);
    }
}

</code></pre>
<p>AuthRequestDto.cs</p>
<pre><code>using System.ComponentModel.DataAnnotations;

namespace foo;
public sealed class AuthRequestDto
{
    [Required]
    public string UserName { get; set; } = string.Empty;
    [Required]
    public string Password { get; set; } = string.Empty;
}
</code></pre>
<p>TemplateControllerTest.cs (The integration tests)</p>
<pre><code>using Microsoft.AspNetCore.Mvc.Testing;
using System.Net;
using Xunit;

namespace AuthWebTemplateTest.Controllers;

public class TemplateControllerTest
{
    [Fact]
    public async void SignInTest()
    {
        var app = new WebApplicationFactory&lt;Program&gt;()
            .WithWebHostBuilder(builder =&gt; { }); 

        var client = app.CreateClient(); //&lt;-- Get the HttpClient
        
        string userName = &quot;foo&quot;;
        string password = &quot;bar&quot;;

        var body = new JsonContent(new { userName, password }); //&lt;-- JsonContent is a custom class. Definition is below
        var resource = &quot;/api/template/sign-in&quot;;
        var response = await client.PostAsync(resource, body);
        Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); //&lt;-- response.StatusCode is 403 Forbidden instead
    }

    [Fact]
    public async void PingTest()
    {
        var app = new WebApplicationFactory&lt;Program&gt;()
            .WithWebHostBuilder(builder =&gt; { }); 

        var client = app.CreateClient();

        var response = await client.GetAsync(&quot;/api/template/ping&quot;);
        Assert.Equal(HttpStatusCode.OK, response.StatusCode); //Good!
        Assert.Equal(&quot;pong&quot;, await response.Content.ReadAsStringAsync()); //Also Good!
    }
}

</code></pre>
<p>JsonContent.cs</p>
<pre><code>using Newtonsoft.Json;
using System.Net.Http;
using System.Text;

namespace AuthWebTemplateTest.util;
internal class JsonContent : StringContent
{
    public JsonContent(object obj)
        : base(JsonConvert.SerializeObject(obj), Encoding.UTF8, &quot;application/json&quot;)
    { }
}
</code></pre>
",https://stackoverflow.com/questions/70900451/c-netcore-webapi-integration-testing-httpclient-uses-https-for-get-request-bu,"['c#', 'asp.net-mvc', 'asp.net-core', 'integration-testing', 'dotnet-httpclient']",1642,True,0,1
"Why integration testing in jest is too slow when I am testing for first time, but testing second time is fast in ubuntu, in mac O.S there is no issue","<p><strong>Running First time - 1480 seconds</strong></p>
<p>PASS  tests/integration/CompanyProductIntegration.test.ts (1480.081 s)
✓ Find company products (63 ms)</p>
<p>Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1480.125 s
Ran all test suites matching /tests/integration/CompanyProductIntegration.test.ts/i.</p>
<p><strong>Running this test second time - 42.5 seconds</strong></p>
<p>PASS  tests/integration/CompanyProductIntegration.test.ts (42.551 s)
✓ Find company products (52 ms)</p>
<p>Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        42.588 s, estimated 1481 s
Ran all test suites matching /tests/integration/CompanyProductIntegration.test.ts/i.</p>
<p><em>But in mac O.S this issue is not there. Can anybody help me out??</em></p>
",https://stackoverflow.com/questions/70878350/why-integration-testing-in-jest-is-too-slow-when-i-am-testing-for-first-time-bu,"['jestjs', 'integration-testing', 'ubuntu-16.04', 'ts-jest']",373,False,2,0
How to create integration test for this?,"<p>everyone. Need some help with integration testing, absolutely new guy for this. How does one start with integration testing this? I was told that there is no point in trying unit test this, so I'm left with one option (Integration tests). Thank you!</p>
<pre><code>exports.view = (req, res) =&gt; {
  connection.query('SELECT * FROM user WHERE status = &quot;active&quot;', (err, rows) =&gt; {
    if (!err) {
      let removedUser = req.query.removed;
      res.render('home', { rows, removedUser });
    } else {
      console.log(err);
    }
    console.log('The data from user table: \n', rows);
  });
}

exports.find = (req, res) =&gt; {
  let searchTerm = req.body.search;
  connection.query('SELECT * FROM user WHERE (first_name LIKE ? OR last_name LIKE ?) AND status = &quot;active&quot;', ['%' + searchTerm + '%', '%' + searchTerm + '%'], (err, rows) =&gt; {
    if (!err) {
      res.render('home', { rows });
      res.send
    } else {
      console.log(err);
    }
    console.log('The data from user table: \n', rows);
  });
}

exports.form = (req, res) =&gt; {
  res.render('add-user');
}

exports.create = (req, res) =&gt; {
  const { first_name, last_name, email, phone, comments } = req.body;
  let searchTerm = req.body.search;
  connection.query('INSERT INTO user SET first_name = ?, last_name = ?, email = ?, phone = ?, comments = ?', [first_name, last_name, email, phone, comments], (err, rows) =&gt; {
    if (!err) {
      res.render('add-user', { alert: '' });
    } else {
      console.log(err);
    }
    console.log('The data from user table: \n', rows);
  });
}



exports.edit = (req, res) =&gt; {
  connection.query('SELECT * FROM user WHERE id = ?', [req.params.id], (err, rows) =&gt; {
    if (!err) {
      res.render('edit-user', { rows });
    } else {
      console.log(err);
    }
    console.log('The data from user table: \n', rows);
  });
}
</code></pre>
",https://stackoverflow.com/questions/73519228/how-to-create-integration-test-for-this,"['javascript', 'integration-testing']",40,False,0,0
Apache Airflow | Testing,"<p>I am new to Apache airflow and have been assigned a task to determine frameworks which can be used to unit and integration testing of Airflow DAGs. Until now I have seen examples of pytest and Python unittest frameworks.</p>
<p>Can we use other Python test frameworks for Airflow unit and integration testing? Also which one should be taken for implementation? Any links to related articles will help me a lot.</p>
<p>Thank you.</p>
",https://stackoverflow.com/questions/74953780/apache-airflow-testing,"['python', 'airflow', 'python-unittest', 'doctest', 'nose2']",282,True,1,1
"Unit Testing, Widget Testing and Integration Testing in a flutter?","<p>What is Unit Testing, Widget Testing and Integration Testing in a flutter? Someone can explain to me?</p>
",https://stackoverflow.com/questions/71377404/unit-testing-widget-testing-and-integration-testing-in-a-flutter,['flutter'],107,False,-2,1
Azure Event Hub Integration test,"<p>I have written some code to push and pull data from Azure Event Hub. Searching through the internet couldn't find me any example of how to do the integration testing. In the past I was able to use <a href=""https://www.testcontainers.org/"" rel=""nofollow noreferrer"">testcontainers</a> for pulsar and mqtt integration testing but couldn't find anything for Azure Event Hub. Test containers does have something called cosmodb which doesn't seem like the right thing. Would appreciate if anyone has any pointer.</p>
",https://stackoverflow.com/questions/73464946/azure-event-hub-integration-test,"['azure', 'integration-testing', 'azure-eventhub', 'akka-stream']",590,False,0,0
TRPC Test Wrapper for unit and integration testing using jest and react testing library - client mock,"<p>How do you mock the TRPC client for unit and integration testing using jest and react testing library?</p>
",https://stackoverflow.com/questions/74530192/trpc-test-wrapper-for-unit-and-integration-testing-using-jest-and-react-testing,"['reactjs', 'react-native', 'unit-testing', 'testing', 'trpc.io']",333,False,0,1
Attach database to sqlite while also specifying schema,"<p>I am integration testing my company's application and I have been tasked with using sqlite specifically to mock our SQL Server. In the integration testing, I am calling some mssql queries. These queries go something like this:</p>
<pre><code>SELECT
    column1
    ,column2
FROM
    [databaseName].dbo.TableName t1
</code></pre>
<p>I am able to attach <code>dbo</code> in sqlite, like so:</p>
<pre><code>import sqlite3

con = sqlite3.connect(&quot;:memory:&quot;, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cur = con.cursor()
attach = &quot;ATTACH DATABASE ? AS dbo&quot;
cur.execute(attach, (&quot;:memory:&quot;,))

table = &quot;&quot;&quot;CREATE TABLE dbo.TableName(
Column1 INT PRIMARY KEY NOT NULL
,Column2 INT
);&quot;&quot;&quot;
cur.execute(table)

query = &quot;&quot;&quot;INSERT INTO dbo.TableName (Column1, Column2) VALUES (?, ?);&quot;&quot;&quot;
cur.execute(query, (1, 999))
</code></pre>
<p>I have been unsuccessful in creating a solution where <code>DatabaseName</code> can be called- something like,</p>
<pre><code>CREATE TABLE databaseName.dbo.TableName(....);
</code></pre>
<p>I have already tried this code, which fails:</p>
<pre><code>attach = &quot;ATTACH DATABASE ? AS databaseName.dbo&quot;
cur.execute(attach, (&quot;:memory:&quot;,))
</code></pre>
<p>How can I implement this kind of solution in Python?</p>
",https://stackoverflow.com/questions/72664944/attach-database-to-sqlite-while-also-specifying-schema,"['python', 'sqlite']",359,True,0,1
How to copy a directory from parent to child module with Maven,"<p>I have a spring boot project, built by maven. I have to use a directory included in the parent project for integration testing in the child project. (Liquibase changelog files.)</p>
<p>What is the best practice to copy it under the child module's testing resources?</p>
<pre><code>parent
├── my_directory
|
└── child
    └──src
       ├── main
       └── test
           └── resources
</code></pre>
<p>So I would like to copy my_directory under child/src/main/test/resources which I use in integration testing. Do you have any idea which is the best practice to do it from the child's pom.xml?</p>
",https://stackoverflow.com/questions/71568244/how-to-copy-a-directory-from-parent-to-child-module-with-maven,"['java', 'spring-boot', 'maven', 'integration-testing', 'liquibase']",134,False,0,1
How do I bypass a Custom Attribute when Integration Testing?,"<p>Basically, I would like to do a clean Integration Testing using net6.0. I want to invoke the endpoints of my controller which will eventually go into the database and write some data. Afterward, I will assert some aspects of the inserted data.</p>
<p>I can bypass the Bearer Token used by <code>[Authorize]</code> attribute but cannot bypass my custom attribute named as <code>[HasPermission]</code></p>
<p>I have this custom attribute:</p>
<pre><code>public class HasPermission : TypeFilterAttribute
{
    public HasPermission(string resource, string scope) 
        : base(typeof(HasPermissionAuthorize))
    {
        Arguments = new object[] { resource, scope };
    }
};

public class HasPermissionAuthorize : IAuthorizationFilter
{
    private readonly string _resource;
    private readonly string _scope;
    private readonly IAuthService _authService;
    
    public HasPermissionAuthorize(string resource, string scope, IAuthService authService)
    {
        _resource = resource;
        _scope = scope;
        _authService = authService;

    }
    public async void OnAuthorization(AuthorizationFilterContext context)
    {
        string token = context.HttpContext.Request.Headers[&quot;Authorization&quot;];

        token = token.Replace(&quot;Bearer &quot;, &quot;&quot;);

        bool hasPermission = await _authService.HasClaimAsync(token, &quot;permission&quot;, _resource + &quot;.&quot; + _scope);

        if (!hasPermission)
        {
            context.Result = new UnauthorizedResult();
        }
    }
</code></pre>
<p>And this is my controller:</p>
<pre><code>[Authorize] //&lt;-- I can bypass this
[Route(&quot;v1/[controller]&quot;)]
[ApiController]
public class MachinesController : ControllerBase
{
    [HasPermission(&quot;Machines&quot;, &quot;Create&quot;)] //&lt;-- How do I bypass this?
    [HttpPost]
    public async Task&lt;IActionResult&gt; Post([FromBody] AddMachineRequest request)
    {
        //some logic
    }
}
</code></pre>
<p>In my Integration Testing</p>
<pre><code>public class ApiWebApplicationFactory : WebApplicationFactory&lt;Startup&gt;
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =&gt;
        {
            //I'm bypassing the [Authorize] attribute here
            //However, I do not know how to bypass [HasPermission] attribute
            services.AddMvc(options =&gt;
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .AddAuthenticationSchemes(&quot;Test&quot;)
                    .Build();

                options.Filters.Add(new AuthorizeFilter(policy));
            });
            services.AddAuthentication(options =&gt;
                {
                    options.DefaultAuthenticateScheme = &quot;Test&quot;;
                    options.DefaultChallengeScheme = &quot;Test&quot;;
                    options.DefaultScheme = &quot;Test&quot;;
                }) //TestAuthHandler is written somewhere else
                .AddScheme&lt;AuthenticationSchemeOptions, TestAuthHandler&gt;(&quot;Test&quot;, options =&gt; { });
        }
    }
}
</code></pre>
<p>I'm testing my code using <code>IClassFixture&lt;ApiWebApplicationFactory&gt;</code>. Even though I can bypass <code>[Authorize]</code> attribute, I could NOT find an elegant way to bypass <code>[HasPermission]</code> attribute.</p>
",https://stackoverflow.com/questions/70944661/how-do-i-bypass-a-custom-attribute-when-integration-testing,"['c#', 'asp.net-mvc', 'integration-testing']",63,True,0,1
Can&#39;t setup apm-integration-testing for debugging kibana,"<p>I'm following the kibana developer's guide, and I want to debug the application using APM.
so I'm following this guide: <a href=""https://www.elastic.co/guide/en/kibana/master/kibana-debugging.html"" rel=""nofollow noreferrer"">https://www.elastic.co/guide/en/kibana/master/kibana-debugging.html</a> .</p>
<p>first I clone the apm-integration-testing repo, then I run <code>./scripts/compose.py start master --no-kibana</code></p>
<p>however after running the above code, I get this error:<code>Please start Docker before running the apm-integration-testing. </code></p>
<p>I understand that running apm requires docker and docker-compose, but there is no clear documentation on how to get it all to run.</p>
<p>If someone has setup apm-integration-testing successfully I can use some help.</p>
<p>Edit:
Here is the compose.py file:</p>
<pre><code>#!/usr/bin/env python
&quot;&quot;&quot;CLI for starting a testing environment using docker-compose.&quot;&quot;&quot;
from __future__ import print_function

import logging
import os
import subprocess
import sys

from modules.cli import LocalSetup


def main():
    # Enable logging
    logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s')
    setup = LocalSetup(sys.argv[1:])
    setup()


def verify_if_docker_is_installed():
    try:
        subprocess.check_output(
            'docker ps', stderr=open(os.devnull, 'w'), shell=True).decode('utf8').strip()
    except subprocess.CalledProcessError:
        print(&quot;Please start Docker before running the apm-integration-testing.&quot;)
        sys.exit(1)


if __name__ == '__main__':
    verify_if_docker_is_installed()
    main()
</code></pre>
",https://stackoverflow.com/questions/73687376/cant-setup-apm-integration-testing-for-debugging-kibana,"['docker', 'elasticsearch', 'docker-compose', 'kibana', 'elastic-apm']",65,True,0,1
scroll_to_index-2.1.1: Warning: Operand of null-aware operation &#39;!&#39; has type &#39;SchedulerBinding&#39; which excludes null,"<p>I'm trying to implement integration testing for my flutter app but I'm getting this error when writing something very straightforward.</p>
<p><code>ERROR: ../../../snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/scroll_to_index-2.1.1/lib/scroll_to_index.dart:358:57: Warning: Operand of null-aware operation '!' has type 'SchedulerBinding' which excludes null.</code></p>
<p>Please help me in resolving this error.</p>
",https://stackoverflow.com/questions/72728617/scroll-to-index-2-1-1-warning-operand-of-null-aware-operation-has-type-sc,"['flutter', 'dart', 'flutter-test', 'pubspec']",110,True,1,1
Is there is any way to capture print() statement during integration test,"<p>Is there is any way during the integration testing to monitor or save or read whatever the print() statement is printing to the console. I m using <code>integration_test</code> for testing.</p>
",https://stackoverflow.com/questions/72475450/is-there-is-any-way-to-capture-print-statement-during-integration-test,"['flutter', 'dart', 'flutter-test', 'flutter-integration-test']",860,True,2,1
How do I load properties from application file for Testcontainer?,"<p>Currently, I am using Testcontainer to implement integration testing for database in spring boot. How do I init the Testcontainer with the application.yml. I don't want to use @DynamicPropertySource.</p>
<pre class=""lang-java prettyprint-override""><code>public static PostgreSQLContainer container = new PostgreSQLContainer(&quot;postgres:12&quot;)
</code></pre>
<pre><code>spring:
  datasource:
    driverClassName: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/db
    username: user
    password: password
</code></pre>
",https://stackoverflow.com/questions/71643063/how-do-i-load-properties-from-application-file-for-testcontainer,"['java', 'spring-boot', 'integration-testing', 'testcontainers']",1243,True,2,1
Spring Boot Integration Testing - TestRestTemplate null,"<p>I am using <strong>Spring Boot 2.1.2</strong> and <strong>junit-jupiter-api-5.3.2</strong> and I am doing integration testing.</p>
<p>My test case is this:</p>
<pre><code>import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.ril.vms.hawkeye.otp.dto.SendOTPRequestDTO;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@SpringBootTest(classes = MyApplication.class,
        webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles(&quot;sit&quot;)
public class OtpControllerIntegrationTest
{
    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void sendOtpTest() throws Exception {

        SendOTPRequest otpRequest = new SendOTPRequestDTO();
        otpRequest.setClientId(&quot;default2&quot;);
        otpRequest.setTag(&quot;tag&quot;);
        otpRequest.setMobileNumber(&quot;9999999999&quot;);
        ResponseEntity&lt;String&gt; responseEntity = this.restTemplate
                .postForEntity(&quot;http://localhost:&quot; + port + &quot;/sendOtp&quot;, otpRequest, String.class);
        assertEquals(201, responseEntity.getStatusCodeValue());

    }
}
</code></pre>
<p>But I am getting <code>java.lang.NullPointerException</code> at below line.</p>
<p><code>ResponseEntity&lt;String&gt; responseEntity = this.restTemplate ...</code></p>
",https://stackoverflow.com/questions/71154294/spring-boot-integration-testing-testresttemplate-null,"['java', 'spring-boot', 'spring-test']",797,False,0,2
launchFragmentinHiltContainer throws Method addObserver must be called on the main thread,"<p>I am trying to perform integration testing and use <code>launchFragmentInHiltContainer</code> to start my fragment for specific scenario. However I receive and error
<code>java.lang.IllegalStateException: Method addObserver must be called on the main thread</code> on the <code>navController.setGraph(R.navigation.nav_graph)</code> line. Below I have provided my test class and the launchFragmentInHiltContainer.</p>
<pre><code>@HiltAndroidTest
class SensorsTests {

    @get:Rule
    var hiltRule = HiltAndroidRule(this)

    @Inject
    lateinit var repository: MockRepositoryImpl

    @BeforeAll
    fun beforeAll() {
        hiltRule.inject()
    }

    @Test
    fun userSensorsAreVisible() {
        val navController = TestNavHostController(ApplicationProvider.getApplicationContext())
        navController.setGraph(R.navigation.nav_graph)

        launchFragmentInHiltContainer&lt;SensorsFragment&gt;(navHostController = navController)

        Thread.sleep(10000)
    }

}
</code></pre>
<pre class=""lang-kotlin prettyprint-override""><code>inline fun &lt;reified T : Fragment&gt; launchFragmentInHiltContainer(
    fragmentArgs: Bundle? = null,
    @StyleRes themeResId: Int = R.style.Theme_SensorsTracker,
    navHostController: NavHostController? = null,
    crossinline action: Fragment.() -&gt; Unit = {}
) {
    val startActivityIntent = Intent.makeMainActivity(
        ComponentName(
            ApplicationProvider.getApplicationContext(),
            HiltTestActivity::class.java
        )
    ).putExtra(
        &quot;androidx.fragment.app.testing.FragmentScenario.EmptyFragmentActivity.THEME_EXTRAS_BUNDLE_KEY&quot;,
        themeResId
    )

    ActivityScenario.launch&lt;HiltTestActivity&gt;(startActivityIntent).onActivity { activity -&gt;
        val fragment: Fragment = activity.supportFragmentManager.fragmentFactory.instantiate(
            Preconditions.checkNotNull(T::class.java.classLoader),
            T::class.java.name
        )

        fragment.arguments = fragmentArgs

        fragment.viewLifecycleOwnerLiveData.observeForever { viewLifecycleOwner -&gt;
            if (viewLifecycleOwner != null) {
                navHostController?.let {
                    Navigation.setViewNavController(fragment.requireView(), it)
                }
            }
        }

        activity.supportFragmentManager
            .beginTransaction()
            .add(android.R.id.content, fragment, &quot;&quot;)
            .commitNow()

        fragment.action()
    }
}
</code></pre>
",https://stackoverflow.com/questions/73909838/launchfragmentinhiltcontainer-throws-method-addobserver-must-be-called-on-the-ma,"['android', 'kotlin', 'dagger-hilt']",276,False,1,1
Are there any alternatives to flapdoodle for embedded mongodb?,"<p>I have tried using flapdoodle's embedded mongodb for integration testing in my SpringBoot application and it runs well locally. However, it fails to run in a docker container when deployed. Are there any alternatives to flapdoodle for embedded mongodb?</p>
",https://stackoverflow.com/questions/71763942/are-there-any-alternatives-to-flapdoodle-for-embedded-mongodb,"['mongodb', 'spring-boot', 'flapdoodle-embed-mongo']",1004,False,3,1
Cpp integration tests,"<p>I'm trying to learn a methodology or some design pattern for integration testing.
I'm not talking about unit testing or using mocks for unit testing.</p>
<p>I want to test some fetcher that involve several functions or some flow E2E.</p>
",https://stackoverflow.com/questions/72748920/cpp-integration-tests,"['c++', 'unit-testing', 'integration-testing']",114,False,0,0
"IAM users and roles for development, testing, production, operation support, automation","<p>setting up an on prem cloud using kubernetes. Developers have their own credentials, accessing K8 via LDAP.</p>
<p>Would like to know what users and roles to setup to support
development, integration testing, UAT, production deployment, operation support, automation scripts.</p>
",https://stackoverflow.com/questions/73873749/iam-users-and-roles-for-development-testing-production-operation-support-aut,['cloud'],14,False,0,0
Is it possible to have a private module named `lib` if I specify a separate lib target in Cargo.toml?,"<p>I have a <strong>binary</strong> application I'm developing in Rust with a <code>lib</code> directory of helpers, and I want to know how to export helper functions for integration testing—e.g.</p>
<pre><code>src
|- data_access_layer.rs
|- main.rs
|- lib
   |- util.rs
</code></pre>
<p>When I tried to export data_access_layer helpers for integration testing I added a <code>[lib]</code> configuration to my Cargo.toml pointing at <code>test_lib.rs</code></p>
<pre class=""lang-rust prettyprint-override""><code>// test_lib.rs

pub mod data_access_layer;

</code></pre>
<p>with a file structure that now looks like this:</p>
<pre><code>src
|- data_access_layer.rs
|- main.rs
|- lib
   |- util.rs
|- test_lib.rs
</code></pre>
<p>...but when I try to run (or test) my application now, I get errors like <strong>&quot;could not find <code>lib</code> in the crate root&quot;</strong></p>
<p>Here's my Cargo.toml file.</p>
<pre class=""lang-ini prettyprint-override""><code>[package]
name = &quot;api-service&quot;
version = &quot;0.11.14&quot;
edition = &quot;2018&quot;

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
diesel = { version = &quot;2&quot;, features = [&quot;mysql&quot;, &quot;extras&quot;, &quot;chrono&quot;, &quot;r2d2&quot;] }

[dev-dependencies]
pretty_assertions = &quot;1.2.1&quot;


[lib]
name = &quot;test_lib&quot;
path = &quot;src/test_lib.rs&quot;

</code></pre>
<p>What would you advise in this situation? Is it just a bad idea to store my own helpers under a collision file name like this? I would expect my TOML config to free up the word <code>lib</code> for use...</p>
",https://stackoverflow.com/questions/74439725/is-it-possible-to-have-a-private-module-named-lib-if-i-specify-a-separate-lib,"['rust', 'cargo']",82,True,0,1
How to Unit Test CrudRepository without @DataJpaTest in Spring Framework,"<p>I wanted to write unit test for the following UserRepository in Spring Framework application:</p>
<pre><code>@Repository
public interface UserRepository extends CrudRepository&lt;User, Long&gt; {
    User findByEmail(String email);
}
</code></pre>
<p>But canFindUserByEmail() test fails because underTest is null</p>
<pre><code>@ExtendWith(MockitoExtension.class)
public class UserRepositoryTest {

    @Autowired
    private UserRepository underTest;


    @Test
    public void canFindUserByEmail() {
        // given
        User expectedUser = new User();
        expectedUser.setEmail(&quot;user@gmail.com&quot;);
        underTest.save(expectedUser);

        // when
        final User actualUser = underTest.findByEmail(expectedUser.getEmail());

        // then
        assertThat(actualUser).isEqualTo(expectedUser);
    }
}
</code></pre>
<p>When I add the next annotations it works, but are they intended for integration testing, not for unit testing?</p>
<pre><code>@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {SpringConfig.class})
@WebAppConfiguration()
</code></pre>
<p>Thanks!</p>
",https://stackoverflow.com/questions/71936676/how-to-unit-test-crudrepository-without-datajpatest-in-spring-framework,"['java', 'spring', 'junit', 'spring-data-jpa', 'crud-repository']",1081,False,0,0
[Flutter Integration testing][iOS] deeplink not working with background,"<p>I'm working on e2e testing with <a href=""https://docs.flutter.dev/testing/integration-tests"" rel=""nofollow noreferrer"">Integration testing</a>.
I am trying to write test of deeplink(or any Universal links or AppLinks) by using <a href=""https://pub.dev/packages/url_launcher"" rel=""nofollow noreferrer"">url_launcher</a>.
However, Android works fine but iOS doesn't.
iOS　shows up this error.</p>
<pre><code>[BackgroundTask] Background Task 50 (&quot;Flutter debug task&quot;), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.
</code></pre>
<p>Does any one knows how to solve this problem?</p>
",https://stackoverflow.com/questions/73969459/flutter-integration-testingios-deeplink-not-working-with-background,"['ios', 'flutter', 'dart', 'integration-testing']",122,False,0,0
Dotnet 6 Xunit integration testing EnsureSuccessStatusCode gives Response status code does not indicate success: 500,"<p>Hello I'm learning integration testing and I want to test a 'POST' method from my controller using xunit and WebApplicationFactory But I'm getting this exception</p>
<p>System.Net.Http.HttpRequestException : Response status code does not indicate success: 400 (Bad Request).</p>
<p>This is my Test:</p>
<pre><code>using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
using System.Text;
using Newtonsoft.Json;

namespace integrationtest.IntegrationTests;

public class ControllerTest  : IClassFixture&lt;TestingWebAppFactory&lt;Program&gt;&gt;
{
    private readonly HttpClient _client;
    public ControllerTest(TestingWebAppFactory&lt;Program&gt; factory) 
        =&gt; _client = factory.CreateClient();

    

    [Fact]
    public async Task AddAccountTest()
    {
        var postRequest = new HttpRequestMessage(HttpMethod.Post, &quot;/api/Accounts/Register&quot;);
        
        var formModel = new RegisterInputModel{
            UserName= &quot;newuser111&quot;,
            Email = &quot;newuser@example.com&quot;,
            PhoneNumber = &quot;111222333&quot;,
            Password= &quot;Gamma2205!&quot;,
            ConfirmPassword= &quot;Gamma2205!&quot;
            } ; 
        var stringPayload = JsonConvert.SerializeObject(formModel);
        postRequest.Content = new StringContent(stringPayload, Encoding.UTF8, &quot;application/json&quot;);


        var response = await _client.SendAsync(postRequest); 

        response.EnsureSuccessStatusCode(); 
        response.IsSuccessStatusCode.Equals(true); 

        var responseString = await response.Content.ReadAsStringAsync(); 
        Assert.Contains(&quot;1&quot;, responseString); 
    }
}
</code></pre>
<p>This is my controller function</p>
<pre><code>[AllowAnonymous]
        [HttpPost]
        public async Task&lt;ActionResult&lt;Response&gt;&gt; Register(RegisterInputModel userRegiterModel)
        {
            HttpContext.Items.Add(&quot;action&quot;,&quot;Accounts.Register&quot;);
            await _accountsService.Register(userRegiterModel);
            return Ok(new ResponseSuccess(&quot;User Registered Successfully&quot;, &quot;Accounts.Register&quot;));
        }
</code></pre>
<p>This is the service</p>
<pre><code>public async Task&lt;IdentityResult&gt; Register(RegisterInputModel userRegiterModel)
        {
        
            try
            {
                ApplicationUser registrationUser = new ApplicationUser()
                {
                    Email = userRegiterModel.Email,
                    UserName = userRegiterModel.UserName,
                    PhoneNumber = userRegiterModel.PhoneNumber
                };
               

                IdentityResult result = await _userManager.CreateAsync(registrationUser, userRegiterModel.Password);
                if (!result.Succeeded)
                {
                    IdentityErrorDescriber errorDescriber = new IdentityErrorDescriber();
                    IdentityError primaryError = result.Errors.FirstOrDefault();

                    if (primaryError.Code == nameof(errorDescriber.DuplicateEmail))
                    {
                        throw new Exception(&quot;Email already exists.&quot;);
                    }
                    else if (primaryError.Code == nameof(errorDescriber.DuplicateUserName))
                    {
                        //_logger.LogError($&quot;Username already exists: {registrationUser.UserName}&quot;);
                        throw new Exception(&quot;Username already exists.&quot;);
                    }
                    else
                    {
                        throw new Exception(primaryError.Description);
                    }
                }
                else
                {
                    return result;
                }
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex.ToString());
                throw new Exception(ex.Message);
            }

        }
</code></pre>
",https://stackoverflow.com/questions/71515164/dotnet-6-xunit-integration-testing-ensuresuccessstatuscode-gives-response-status,"['c#', 'asp.net', '.net', 'xunit.net']",353,False,0,0
How to start a clickhouse container with testcontainers?,"<p>I'd like to use testcontainers for integration testing. I need to test against a clickhouse storage.</p>
<p>The docker image is <a href=""https://hub.docker.com/r/yandex/clickhouse-server"" rel=""nofollow noreferrer"">yandex/clichouse-server</a></p>
<p>My code thus far (imported mostly from the official redis example on testcontainers website):</p>
<pre><code>    ctx := context.Background()
    req := testcontainers.ContainerRequest{
        Image: &quot;yandex/clickhouse-server&quot;,
        ExposedPorts: []string{&quot;9000/tcp&quot;},
    }
    chContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
        ContainerRequest: req,
        Started:          true,
    })
    require.NoError(t, err, &quot;unexpected error while creating clickhouse container&quot;)

    endpoint, err := chContainer.Endpoint(ctx, &quot;&quot;)
    require.NoError(t, err)
</code></pre>
<p>This throws an error <code>port not found</code> on getting the endpoint, and I'm not sure where to go from there.</p>
",https://stackoverflow.com/questions/73652833/how-to-start-a-clickhouse-container-with-testcontainers,['go'],337,True,1,2
Integration testing vs e2e testing on a finished application,"<p>What makes more sense? I am testing a finished application for a company which is already being used by its customers. The software really only displays data. Which type of testing makes most sense, end-to-end or integration testing?
EDIT: If it makes any difference, the software up to now is completely untested.</p>
",https://stackoverflow.com/questions/74965435/integration-testing-vs-e2e-testing-on-a-finished-application,"['angular', 'testing', 'integration-testing', 'integration', 'end-to-end']",85,True,0,1
Xunit integration test dotnet 6 System.Net.Http.HttpRequestException : Response status code does not indicate success: 415 (Unsupported Media Type),"<p>Hello I'm learning integration testing and I want to test a 'POST' method from my controller using xunit and WebApplicationFactory
But I'm getting this exception</p>
<p>Error Message:
System.Net.Http.HttpRequestException : Response status code does not indicate success: 415 (Unsupported Media Type).
Stack Trace:
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()</p>
<p>This is my code for the test:</p>
<pre><code>using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace integrationtest.IntegrationTests;

public class ControllerTest  : IClassFixture&lt;TestingWebAppFactory&lt;Program&gt;&gt;
{
   private readonly HttpClient _client;
   public ControllerTest(TestingWebAppFactory&lt;Program&gt; factory) 
       =&gt; _client = factory.CreateClient();

   

   [Fact]
   public async Task AddInternshipMemberTest()
   {
       var postRequest = new HttpRequestMessage(HttpMethod.Post, &quot;/api/InternshipMember/AddInternshipMember&quot;);

       var formModel = new Dictionary&lt;string, string&gt;
       {
           { &quot;var1&quot;, &quot;1&quot;},
           { &quot;var2&quot;, &quot;0&quot;},
           { &quot;var3&quot;, &quot;135&quot;},
           { &quot;var4&quot;, &quot;1&quot;},
           { &quot;var5&quot;, &quot;1&quot;},
           { &quot;var6&quot;, &quot;1&quot;},
           { &quot;var7&quot;, &quot;3&quot; }
       };
       postRequest.Content = new FormUrlEncodedContent(formModel); 
       var response = await _client.SendAsync(postRequest); 
               
       response.EnsureSuccessStatusCode(); 
               
       var responseString = await response.Content.ReadAsStringAsync(); 
               
       Assert.Contains(&quot;1&quot;, responseString); 
   }
}
</code></pre>
<p>Can anyone help why i'm getting that error?</p>
",https://stackoverflow.com/questions/71471009/xunit-integration-test-dotnet-6-system-net-http-httprequestexception-response,"['c#', 'asp.net', '.net', 'xunit', 'xunit.net']",361,False,1,0
ServiceStack ORMLite SQLite implementation fails on Mac M1,"<p>We use SQLite in-memory databases in our dotnet codebase for integration testing our repository layer with ORMLite. When I try to run a test on Mac I get this error:</p>
<pre><code>System.DllNotFoundException
Unable to load shared library 'SQLite.Interop.dll' or one of its dependencies. In order to help diagnose loading problems, consider setting the DYLD_PRINT_LIBRARIES environment variable: dlopen(libSQLite.Interop.dll, 0x0001): tried: 'libSQLite.Interop.dll' (no such file), '/usr/local/lib/libSQLite.Interop.dll' (no such file), '/usr/lib/libSQLite.Interop.dll' (no such file), '/Users/aaron/Projects/joinder/DASH/Test/ClientSiteData.Tests/bin/Debug/net6.0/libSQLite.Interop.dll' (no such file)
   at System.Data.SQLite.UnsafeNativeMethods.sqlite3_config_none(SQLiteConfigOpsEnum op)
</code></pre>
<p>Is there a way to get this working on Mac so I don't have to revert to my Windows machine every time I need to run tests?</p>
",https://stackoverflow.com/questions/72745111/servicestack-ormlite-sqlite-implementation-fails-on-mac-m1,"['c#', 'sqlite', '.net-core', 'apple-m1', 'ormlite-servicestack']",133,True,1,1
Can I apply &#39;setupFilesAfterEnv&#39; to specific file in jest config?,"<p>I'm working on appling prisma <code>unit testing</code> and <code>Integration testing</code></p>
<p>I want to apply unit testing for <code>*.service.test.ts</code> files
and intergration testing for <code>*.test.ts</code> files.</p>
<p>I followed the Prisma document, but there is something that doesn't work.</p>
<ul>
<li>singleton.ts</li>
</ul>
<pre><code>import { mockReset, mockDeep, DeepMockProxy } from &quot;jest-mock-extended&quot;;
import { PrismaClient } from &quot;@prisma/client&quot;;
import Prisma from &quot;../src/db/prisma&quot;;

jest.mock(&quot;../src/db/prisma&quot;, () =&gt; {
  return {
    __esModule: true,
    default: mockDeep&lt;PrismaClient&gt;(),
  };
});

beforeEach(() =&gt; {
  // eslint-disable-next-line no-use-before-define
  mockReset(prismaMock);
});

export const prismaMock = Prisma as unknown as DeepMockProxy&lt;PrismaClient&gt;;

</code></pre>
<ul>
<li>jest.config.ts</li>
</ul>
<p>When turing off <code>setupFilesAfterEnv</code> option, testing <code>*.test.ts</code> files are working.</p>
<p>So I Want turn off <code>setupFilesAfterEnv</code> option in Integration testing</p>
<p>Is it applicable only when unit testing?</p>
<pre><code>...

setupFilesAfterEnv: [
 &quot;./jest/singleton.ts&quot;

]
</code></pre>
",https://stackoverflow.com/questions/73119123/can-i-apply-setupfilesafterenv-to-specific-file-in-jest-config,"['node.js', 'unit-testing', 'integration-testing', 'prisma', 'ts-jest']",739,True,0,1
Create a oauth-token for integration tests,"<p>We want to create a &quot;long lasting&quot; token for integration testing purposes. We are using a keycloak for creating tokens normally. But I don't see a possibility to create tokens with no expiration, so that reoccuring integration tests on dev-stage can be done without interuption.</p>
<p>What would you suggest for such automatically repeating testing regarding oauth?</p>
",https://stackoverflow.com/questions/72879216/create-a-oauth-token-for-integration-tests,"['testing', 'oauth-2.0', 'keycloak']",440,True,0,2
Verify.XUnit does not scrube inline datetime in the action result response,"<p>I am using Verify in XUnit to test a controller response and everything is working fine except that in the response headers there is an un-scrubbed Datetime object which is failing every time. (I am testing the standard weatherforcast from .NET 6 with Verify.XUnit 17.10.1)</p>
<p>My integration testing:</p>
<pre class=""lang-cs prettyprint-override""><code>    var client = new HttpClient()
    {
        BaseAddress = new Uri(&quot;url&quot;)
    };

    var result = await client.GetAsync(&quot;WeatherForecast&quot;);
    var responseString = await result.Content.ReadAsStringAsync();
    var json = JsonConvert.DeserializeObject&lt;IEnumerable&lt;WeatherForecast&gt;&gt;(responseString);
    await Verify(new
    {
        json,
        result
    });
</code></pre>
<p>The place it is failing:</p>
<p><a href=""https://i.stack.imgur.com/gGODW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/gGODW.png"" alt=""enter image description here"" /></a></p>
<p>Any suggestions?</p>
",https://stackoverflow.com/questions/73370054/verify-xunit-does-not-scrube-inline-datetime-in-the-action-result-response,"['.net-6.0', 'xunit', 'verify']",98,False,0,0
how to define the class order in spring integration test,"<p>I have write some classes  for integration test</p>
<p>this is a parent class</p>
<pre><code>@Testcontainers
@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public abstract class ABC {
        
        @beforeAll
        // method 
}
</code></pre>
<p>in this abstract class only the pre req methods like db initialisation, and I am using this in my implementation classes</p>
<pre><code>public class A extends ABC {

   @Test
   @Order(10)
   test1(){
    }



}

public class B extends ABC {
   @Test
   @Order(10)
   test2(){
    }
}

</code></pre>
<p>these two classes Class A and Class B extends abstract class ABC.
I want to run integration testing in order class A after  class B.</p>
",https://stackoverflow.com/questions/70802488/how-to-define-the-class-order-in-spring-integration-test,"['java', 'spring', 'integration-testing']",392,False,0,1
Maven Integration Testing Framework forces dependency resolution from central repository,"<p>I'm using the <a href=""https://github.com/khmarbaise/maven-it-extension"" rel=""nofollow noreferrer"">Maven Integration Testing Framework</a> plugin to test one goal of a custom-developed plugin. As far as the tests go, everything works well. However, there is one unexpected and undesired technicality that I have noticed:</p>
<p>The local repositories created for individual test cases in <code>target/maven-it/.../test-case/.m2/repository</code> are always populated remotely - from the <a href=""https://mvnrepository.com/repos/central"" rel=""nofollow noreferrer"">Maven Central Repository</a>. If I run <code>mvn clean integration-test</code> without being connected to the Internet, the dependency resolution results in an error after a failed connection attempt. I would expect it, however, to look for the dependencies in the &quot;standard&quot; cache located in <code>USER/.m2/repository</code> first, where the dependencies were already present in my experiment.</p>
<p>It's interesting that even after adding the <code>--offline</code> option to <code>mvn clean integration-test</code>, online dependency resolution is still attempted.</p>
<p>My main question is - should this be happening? Is this the expected behavior when using the Maven Integration Testing Framework? Or do you think there might be something wrong with the way I'm using it?</p>
<p>Related dependencies from the <code>pom.xml</code> of the tested custom-developed plugin:</p>
<pre><code>        &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;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-params&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.platform&lt;/groupId&gt;
            &lt;artifactId&gt;junit-platform-suite&lt;/artifactId&gt;
            &lt;version&gt;${junit.platform.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.assertj&lt;/groupId&gt;
            &lt;artifactId&gt;assertj-core&lt;/artifactId&gt;
            &lt;version&gt;3.16.1&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.soebes.itf.jupiter.extension&lt;/groupId&gt;
            &lt;artifactId&gt;itf-jupiter-extension&lt;/artifactId&gt;
            &lt;version&gt;0.11.0&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.soebes.itf.jupiter.extension&lt;/groupId&gt;
            &lt;artifactId&gt;itf-assertj&lt;/artifactId&gt;
            &lt;version&gt;0.11.0&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
</code></pre>
<p>Related plugins:</p>
<pre><code>            &lt;plugin&gt;
                &lt;groupId&gt;com.soebes.itf.jupiter.extension&lt;/groupId&gt;
                &lt;artifactId&gt;itf-maven-plugin&lt;/artifactId&gt;
                &lt;version&gt;0.11.0&lt;/version&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;id&gt;installing&lt;/id&gt;
                        &lt;phase&gt;pre-integration-test&lt;/phase&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;install&lt;/goal&gt;
                            &lt;goal&gt;resources-its&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt;
                &lt;version&gt;3.0.0-M5&lt;/version&gt;
                &lt;configuration&gt;
                  &lt;systemProperties&gt;
                    &lt;maven.version&gt;${maven.version}&lt;/maven.version&gt;
                    &lt;maven.home&gt;${maven.home}&lt;/maven.home&gt;
                  &lt;/systemProperties&gt;
                &lt;/configuration&gt;
                &lt;executions&gt;
                  &lt;execution&gt;
                    &lt;goals&gt;
                      &lt;goal&gt;integration-test&lt;/goal&gt;
                      &lt;goal&gt;verify&lt;/goal&gt;
                    &lt;/goals&gt;
                  &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
</code></pre>
",https://stackoverflow.com/questions/70702126/maven-integration-testing-framework-forces-dependency-resolution-from-central-re,"['maven', 'integration-testing', 'maven-plugin']",148,True,1,1
In the loop vs. A-SPICE processes,"<p>Can the HIL,SIL, and MIL tests be matched with SWE4,SWE5,SWE6(static analysis, unit testing, integration testing, qualification testing)  processes? For instance can Unit Tests(ceedling, Google tests) be considered as MIL test?</p>
<p>I am trying to compare in the loop tests and regular automotive based software tests to understand better in the loop testing.</p>
",https://stackoverflow.com/questions/74221127/in-the-loop-vs-a-spice-processes,"['unit-testing', 'testing', 'model-based-testing']",25,False,0,0
karate.callSingle getting call twice for two tests,"<p>I am trying to integrate karate in my project for integration testing. I was trying to use karate.callSingle() to fetch authorization headers.</p>
<p>I have two tests</p>
<pre><code>    @Test
    void test1() {
        Results results = Runner.path(&quot;classpath:integrationTests/test1.feature&quot;).parallel(2);
        assertEquals(0, results.getFailCount(), results.getErrorMessages());

    }

    @Test
    void test2 {
        Results results = Runner.path(&quot;classpath:integrationTests/test2.feature&quot;).parallel(1);
        assertEquals(0, results.getFailCount(), results.getErrorMessages());

    }
</code></pre>
<p>Now the test1.feature has two scenarios and test2.feature has one scenario. The tests are running fine just that in the logs I see karate.callSingle is executed twice...for both tests. Is this the expected behaviour?</p>
",https://stackoverflow.com/questions/74740276/karate-callsingle-getting-call-twice-for-two-tests,"['karate', 'karate-call-single']",62,True,1,1
how to perform tap/on Pressed action on Sliver list specific item in flutter integration test,"<p>Need to perform on pressed operation using automation testing in flutter integration testing.
There is Sliver List used in my app and on that Sliver list when user tap on Sliver list item it will call on Tap method which I implemented but now need to do the same in integration test. Is there any way to perform tap on Sliver list element.</p>
<pre><code>SliverList(
childCount:10,
delegate: SliverChildBuilderDelegate((context, index) {
return ListItem(log: _logs![index],onPress: () =&gt; onPressed(_logs![index]),);
});
)
</code></pre>
",https://stackoverflow.com/questions/70801220/how-to-perform-tap-on-pressed-action-on-sliver-list-specific-item-in-flutter-int,['flutter'],419,False,0,1
Customizing Angular ng g c to create multiple spec files,"<p>I'd like to generate two spec files for each component, one to test the TS file and one for testing the HTML file (some might say unit testing and integration testing)</p>
<p>So something like this:</p>
<pre><code>components
    └──credit-card
        ├── credit-card.component.css
        ├── credit-card.component.html
        ├── credit-card.component.spec.ts
        ├── credit-card.component.unit.spec.ts
        └── credit-card.component.ts
</code></pre>
<p>Generally, <code>ng g c</code> will create a <code>spec</code> file by default, but I'm interested in modifying the command somehow to create multiple spec files by default. Is this possible?</p>
",https://stackoverflow.com/questions/74633703/customizing-angular-ng-g-c-to-create-multiple-spec-files,"['angular', 'angular-cli']",301,True,0,1
Flutter integration testing : Enter text into TextFormField by label,"<p>How do I enter text into <code>TextFormField</code> by using the label text? My issue is that I can't find the widget while doing an integration test. I was able to find the widget by adding a key but I don't want to change the source code of the app for doing integration testing.</p>
<pre><code>TextFormField(
                controller: usernameController,
                decoration: InputDecoration(border: UnderlineInputBorder(), labelText: &quot;Username&quot;),
              )
</code></pre>
<p>Tried something like this but it doesn't work:</p>
<pre><code>final usernameField = find.descendant(
  of: find.text(&quot;Username&quot;),
  matching: find.byType(EditableText),
);
</code></pre>
",https://stackoverflow.com/questions/73202977/flutter-integration-testing-enter-text-into-textformfield-by-label,"['flutter', 'flutter-test']",937,True,0,2
Code actions provider API for integration testing,"<p>I'm writing a CodeActions provider in <a href=""https://github.com/google/wireit/pull/174"" rel=""nofollow noreferrer"">https://github.com/google/wireit/pull/174</a> and using an integration testing setup similar to that documented at <a href=""https://code.visualstudio.com/api/working-with-extensions/testing-extension"" rel=""nofollow noreferrer"">https://code.visualstudio.com/api/working-with-extensions/testing-extension</a>.</p>
<p>I can't seem to find any APIs to get the code actions that my language server provides, nor to get VSCode to apply a code action so that I may assert on the effects.</p>
",https://stackoverflow.com/questions/72119902/code-actions-provider-api-for-integration-testing,"['visual-studio-code', 'vscode-extensions']",148,False,2,0
asp.net core web Api integration testing with startup having static file configuration,"<p>I was trying to implement integration testing for my api. But, it is saying     System.IO.DirectoryNotFoundException : ..WebApi.IntegrationTest\bin\Debug\net6.0\Files\ while I run the test</p>
<p>here is my startup code</p>
<pre><code> public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
     
            }
            app.UseBlazorFrameworkFiles();
            
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @&quot;Files&quot;)),
                RequestPath = new PathString(&quot;/Files&quot;)
            });
            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseCors(&quot;CorsPolicy&quot;);
             app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =&gt;
            {
                endpoints.MapControllers();
            });
            app.Initialize(Configuration);
        }
</code></pre>
<p>when I comment out UseStaticFiles it passes the test else it fails with the above. exception</p>
<p>here is my CustomWebApplicationFactory</p>
<pre><code> public class CustomWebApplicationFactory&lt;TStartup&gt; : WebApplicationFactory&lt;TStartup&gt; where TStartup : class
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =&gt;
        {
            services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
            {
                options.UseInMemoryDatabase(&quot;ApplicationDbContextInMemoryTest&quot;);
            })
            .AddControllers()
            .AddApplicationPart(typeof(Startup).Assembly);

            var sp = services.BuildServiceProvider();
            using (var scope = sp.CreateScope())
            {
                var scopedService = scope.ServiceProvider;
                var context = scopedService.GetRequiredService&lt;ApplicationDbContext&gt;();
                var logger = scopedService.GetRequiredService&lt;ILogger&lt;CustomWebApplicationFactory&lt;TStartup&gt;&gt;&gt;();

                context.Database.EnsureCreated();
                try
                {
                    Utilities.InitializeDbForTests(context);
                }
                catch (Exception ex)
                {

                    logger.LogError(ex, $&quot;An error occured seeding the database with test messages, Error: {ex.Message}&quot;);
                }
            }
        });
    }
    protected override IHost CreateHost(IHostBuilder builder)
    {
        builder.UseContentRoot(Directory.GetCurrentDirectory());
        return base.CreateHost(builder);
    }
    public HttpClient GetAnonymousClient()
    {
        return CreateClient();
    }
}
</code></pre>
<p>I tried a lot to fix it but I was not able, please help me, thank you!</p>
",https://stackoverflow.com/questions/71941540/asp-net-core-web-api-integration-testing-with-startup-having-static-file-configu,"['asp.net-core', 'asp.net-web-api', 'integration-testing', 'asp.net-core-staticfile']",286,False,1,0
How to override a service in Autofac container using WebApplicationFactory,"<p>I'm writing some integration testing using WebApplicationFactory. I use Autofac as my dependency resolver. In my test, I'm trying to override one of the registration so I can mock one of the dependency. It's pretty simple using the aspnetcore default ConfigureServices method :</p>
<pre><code>public static RestClient GetClient(Func&lt;IDependency&gt; dependencyFactory)
{
   var application = new WebApplicationFactory&lt;Program&gt;().WithWebHostBuilder(builder =&gt;
   {
       builder.ConfigureServices(s =&gt;
       {
            s.AddTransient&lt;Func&lt;IDependency&gt;&gt;(s=&gt;dependencyFactory);
       });
    });
    return GetRestClient(application.CreateClient());
}
</code></pre>
<p>But, what I'm trying to do is to do the same thing using the Autofac ContainerBuilder. Something that would look like :</p>
<pre><code>public static RestClient GetClient(Func&lt;IDependency&gt; dependencyFactory)
{
   var application = new WebApplicationFactory&lt;Program&gt;().WithWebHostBuilder(builder =&gt;
   {
       builder.ConfigureContainer&lt;ContainerBuilder&gt;(containerBuilder =&gt;
       {
            containerBuilder.Register&lt;IDependency&gt;(c=&gt;dependencyFactory()).InstancePerDependency();
       });
    });
    return GetRestClient(application.CreateClient());
}
</code></pre>
<p>Any of you know how I can do this ?</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/73157243/how-to-override-a-service-in-autofac-container-using-webapplicationfactory,"['asp.net-core', 'integration-testing', 'autofac', '.net-6.0']",588,True,7,1
Node.js/express integration test with jest/supertest suitable for automated tests,"<p>Given a <code>nodejs/express</code> web api application which works with <code>MySQL</code>, <code>MongoDB</code> and calls some external apis and services, we want to add testing with <code>jest</code> and <code>supertest</code>.</p>
<p>Now, what are the ways for integration testing, calling apis which includes all code from controller to database? in-memory databases, mocking and dedicated database for testing are options.</p>
<p>One important use case is automated tests under CI/CD tools.</p>
<p>Any help is highly appreciated.</p>
",https://stackoverflow.com/questions/74384638/node-js-express-integration-test-with-jest-supertest-suitable-for-automated-test,"['node.js', 'express', 'jestjs', 'automated-tests', 'integration-testing']",34,True,0,1
pgmock2 retrieve data after insert,"<p>I am evaluating pgmock2 for use in integration testing. The case I have is to insert data into a table and then read that same data out again in a subsequent query. Is this possible with pgmock2? Is there an example somewhere that someone can point me to? If this is not possible with pgmock2 then is there another package I should be using?</p>
",https://stackoverflow.com/questions/73060061/pgmock2-retrieve-data-after-insert,"['node.js', 'postgresql']",34,False,0,0
How to test a PyQt5 QApplication using pytest and pytest-qt?,"<p>I am trying to test my QtApplication using pytest-qt and need some assistance with the basics.</p>
<p>Give a simple mwe such as this:</p>
<pre><code># mwe.py
import sys
from PyQt5.QtWidgets import (QWidget, QToolTip,
    QPushButton, QApplication)
from PyQt5.QtGui import QFont


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()
        self.count = 0


    def initUI(self):

        QToolTip.setFont(QFont('SansSerif', 10))

        self.setToolTip('This is a &lt;b&gt;QWidget&lt;/b&gt; widget')

        btn = QPushButton('Button', self)
        btn.setToolTip('This is a &lt;b&gt;QPushButton&lt;/b&gt; widget')
        btn.resize(btn.sizeHint())
        btn.move(50, 50)
        btn.clicked.connect(self.pushedTheButton)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Tooltips')
        self.show()

    def pushedTheButton(self):
        print(&quot;Button pressed&quot;)
        self.count += 1


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()
</code></pre>
<p>How would I test that the counter has incremented when the button is pressed?</p>
<pre><code>from mwe import Example
import pytest
import pytestqt
from pytestqt.qtbot import QtBot
import sys

from PyQt5.Qt import QApplication

def test_press_button(qtbot: QtBot):
    app = QApplication(sys.argv)
    ex = Example()

    qtbot.add_widget(ex)
    sys.exit(app.exec())
    
    # how to press the button and verify that counter is incermented? 
    
</code></pre>
<p>Note, I've been able to do this outside the main loop, by just instantiating the <code>Example</code> but for my integration testing I want to have the full application open and running.</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/72882790/how-to-test-a-pyqt5-qapplication-using-pytest-and-pytest-qt,"['python', 'qt', 'testing', 'pyqt5', 'pytest-qt']",241,False,2,0
Response.body is empty in this test that uses supertest and node.js,"<p><a href=""https://i.stack.imgur.com/8eeNz.png"" rel=""nofollow noreferrer"">Using supertest to test a node.js api for unit and integration testing but the test for integration keep failing; I don't know why I keep receiving an empty object in the reponse.body while I am expecting a result of 30 from the AddNum object. the error comes from the file app.test.js line 19 </a></p>
<p>This is my code for app.test.js</p>
<pre><code>
const supertest = require('supertest');
const server = require('../../app');


describe(&quot;Calculate&quot;, () =&gt; {
    it('POST /calculate: action: sum', async () =&gt; {
       const  AddNum = {
            action: 'sum',
            num1: 20,
            num2: 10
        }

        
        const response = await supertest(server).post(&quot;/calculate&quot;).send(AddNum)
        console.log({response})
        expect(response.status).toBe(200)

        const expectResult = {result:30}
        expect(response.body).toBe(expectResult)
    })
})

</code></pre>
<p>This is my error from running the test in the command line.</p>
<pre><code>      at Object.log (test/integration/app.test.js:15:17)

  ● Calculate › POST /calculate: action: sum

    expect(received).toBe(expected) // Object.is equality

    - Expected  - 3
    + Received  + 1

    - Object {
    -   &quot;result&quot;: 30,
    - }
    + Object {}

      17 |
      18 |         const expectResult = {result:30}
    &gt; 19 |         expect(response.body).toBe(expectResult)
         |                               ^
      20 |     })
      21 | })

      at Object.toBe (test/integration/app.test.js:19:31)

A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that 
.unref() was called on them.
Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 failed, 4 skipped, 1 passed, 6 total
Snapshots:   0 total
Time:        2.556 s
Ran all test suites.

</code></pre>
",https://stackoverflow.com/questions/73632556/response-body-is-empty-in-this-test-that-uses-supertest-and-node-js,"['node.js', 'integration-testing', 'javascript-objects', 'response', 'supertest']",199,False,0,0
"Can you use Testcontainers to manage service dependencies, like a database, during local development?","<p>Testcontainers can manage dockerized service dependencies, like a database, Kafka, Elasticsearch, and so on for integration testing.</p>
<p>Can I configure my Spring Boot application to manage these service dependencies during local development?</p>
<p>For example, my <strong>Spring Boot application</strong> needs a MySQL database.
I would like to integrate it with Testcontainers to provide a Docker container with MySQL not only during the tests execution, but at application startup during local development too.</p>
",https://stackoverflow.com/questions/71196722/can-you-use-testcontainers-to-manage-service-dependencies-like-a-database-duri,"['spring-boot', 'docker', 'docker-compose', 'containers', 'testcontainers']",763,True,0,1
Integration testing with docker-compose,"<p>I am working on an application with multiple (10+) containers (microservices .NET, front-end React, 3rd party etc.) being started using docker-compose files.
How would you go about integration testing? Is there a testing framework which would allow a beforeAll() to clear containers, restart them, or clean volumes? Do you know of a well-performing setup to run multiple integration tests against a docker-compose environment?</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/72430520/integration-testing-with-docker-compose,"['docker-compose', 'continuous-integration', 'integration-testing']",205,False,0,1
How to send mocked request using chai http,"<p>I am fairly new to integration testing and I am trying to send a mock request using mocha and chai http but having no luck. I want to try and have a jwt verified by passing in a mocked token which I create, however, all of the data is being passed into the req.body.</p>
<p>Is there a way of sending the entire req instead of just passing data in the req.body through the .send()?</p>
<pre class=""lang-js prettyprint-override""><code>// TEST I AM RUNNING
it('should POST /newCertificate for an Accreditor ',async()=&gt;{
    let status,
        json,
        res;

    status = stub();
    json = spy();
    res = { json, status };
    status.returns(res);


    let title = 'title';
    let recipientEmail = 'student@email.com';
    let grade = 'grade';
    let type = 'type';
    let department = 'department';
    const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyNDFhMjhlY2Y4Y2FlOWFiYmQ4Nzg5NSIsImlhdCI6MTY0ODQ2ODYyMiwiZXhwIjoxNjQ4NzI3ODIyfQ.KU6Un3YPq79TRruTrM8y2BrvgRH8xOn882LVy6vwhU4'
    const body = JSON.stringify({ title, recipientEmail, grade, type, department })
    const req = mockRequest(token, body);


    let res2 = await chai
      .request(app)
      .post('/newCertificateRoutes/newCertificate')
      .set('content-type', 'application/x-www-form-urlencoded')
      .send(req) // I AM TRYING TO SEND THE ENTIRE req but it only adds req to req.body

    expect(res2.status).toHaveBeenCalledWith(201);

});
</code></pre>

<pre class=""lang-js prettyprint-override""><code>// FUNCTION I AM CALLING
module.exports.newCertificate_post = async (req, res) =&gt; {

        let { title, recipientEmail, grade, type, department }  = req.body;
        const token = req.cookies.jwt;
        let accreditorId = null;
        let departmentId = null;

        console.log(&quot;token: &quot;, token);
        console.log(&quot;req.body: &quot;, req.body);


        // check if department or accreditor/admin is issueing degree
        jwt.verify(token, 'ultralongsecretkeywhichnooneisabletoguessaccreditor', (err, decodedToken) =&gt; {
            if (err) {
                jwt.verify(token, 'ultralongsecretkeywhichnooneisabletoguessdepartment', (err, decodedToken) =&gt; {
                    if (err) {
                        console.log(err.message);
                    } else {
                        departmentId = decodedToken.id
                    }
                });
            } else {
                accreditorId = decodedToken.id;
            }
        });

        console.log(&quot;departmentId: &quot;, departmentId);
        console.log(&quot;accreditorId: &quot;, accreditorId);
    
    res.status(201).json({ });
 };
</code></pre>

",https://stackoverflow.com/questions/71648970/how-to-send-mocked-request-using-chai-http,"['javascript', 'node.js', 'testing', 'mocha.js', 'chai']",325,False,1,0
PreparedStatement RETURN_GENERATED_KEYS,"<p>Assuming I have a MERGE statement that either updates or inserts on a given criteria; what would be the behaviour of OJDBC10:19.6.0.0 on JDK11 if RETURN_GENERATED_KEYS was specified for an executeUpdate?</p>
<p>In H2 in-memory Oracle compatible tests the key is returned, but in integration testing the key is not present. The result of the PreparedStatement has the expected number of rows updated, but the ResultSet does not contain the values.</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/73965547/preparedstatement-return-generated-keys,"['java', 'oracle', 'h2', 'ojdbc']",69,False,0,0
Springboot database URL change during integration testing,"<p>I am doing integration testing, and have 2 databases to test my project against. Rather than creating 2 profiles, is there a quick and easy way where I create 2 integration test classes, and one to test against the database originally written on my main profile, and another where I add some sort of annotation that changes the database url programatically, but otherwise keeps everything else the same, and run my tests through there?</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/74396107/springboot-database-url-change-during-integration-testing,"['spring', 'spring-boot', 'profile', 'spring-profiles', 'spring-properties']",154,True,0,2
Add custom headers to Next.js responses based on environment,"<p>I'm trying to add the the <a href=""https://developers.google.com/search/docs/advanced/robots/robots_meta_tag#xrobotstag"" rel=""nofollow noreferrer"">X-Robots-Tag header</a> to all Next.js HTTP responses based on <em>something</em> in the environment the server is deployed to -- whether that is an environment variable (my preference) or anything else.</p>
<p>My Next.js application is deployed to two environments: an integration testing environment that uses the production Next.js build (<code>NODE_ENV=&quot;production&quot;</code>) but is connected to non-prod services, and the actual production environment that serves user traffic. I want to add the header only to the integration testing environment.</p>
<p>I've tried adding the header conditionally based on <code>process.env.INTEGRATION</code><em><code>TEST</code></em><code>ENV</code> in <a href=""https://nextjs.org/docs/api-reference/next.config.js/headers"" rel=""nofollow noreferrer""><code>headers()</code> in next.config.js</a>, but any env var like <code>process.env.XYZ</code> seems to be evaluated at build time, not at runtime. For example, this doesn't work, even though the <code>INTEGRATION_TEST_ENV</code> environment variable is set to the string &quot;true&quot; on the server:</p>
<pre><code>headers() {
      if (process.env.INTEGRATION_TEST_ENV === &quot;true&quot;) {
        console.log(&quot;This code will never be run. The condition never evaluates to true, despite the runtime env var actually being set to 'true'.&quot;)
        return [
          {
            source: &quot;/:path*&quot;,
            headers: [
              {
                key: &quot;X-Robots-Tag&quot;,
                value: &quot;none&quot;,
              },
            ],
          },
        ]
      }
    },
</code></pre>
<p>I can't use next.config.js's phases either, since both my integration test and &quot;real production&quot; are running the production build and production server.</p>
<p>A <a href=""https://nextjs.org/docs/advanced-features/custom-server"" rel=""nofollow noreferrer"">custom server</a> might solve the problem, but it seems like overkill, especially with the loss of automatic static optimization.</p>
<p>Is there any way to add a header based on a runtime environment variable?</p>
",https://stackoverflow.com/questions/71722818/add-custom-headers-to-next-js-responses-based-on-environment,['next.js'],2090,True,1,1
Integration testing with XCtest,"<p>I'm trying to write some Unit and Integration testing using XCtest.
I have a part that I'm not sure if it is a unit test or Integration test :
I need to test uploading one document using an upload service .
My question : Since my function is going to interact with a different service &quot;upload service&quot; so I'm thinking that it is an Integration test more than a unit test.
Could anyone please confirm ?</p>
",https://stackoverflow.com/questions/73606106/integration-testing-with-xctest,"['integration-testing', 'xctest']",29,False,0,0
Hibernate 7.0.2: javax.validation.NoProviderFoundException,"<p>I'm using spring-boot-starter-web:jar:2.6.2 in my project, this jar uses hibernate-validator:6.2.0.Final. Recently we decided to move to Hibernate 7.0.2.Final, so I added the following maven config:</p>
<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
    &lt;version&gt;${rest.starter.version}&lt;/version&gt;
    &lt;exclusions&gt;
        &lt;exclusion&gt;
            &lt;groupId&gt;org.hibernate.validator&lt;/groupId&gt;
            &lt;artifactId&gt;hibernate-validator&lt;/artifactId&gt;
        &lt;/exclusion&gt;
    &lt;/exclusions&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.hibernate.validator&lt;/groupId&gt;
    &lt;artifactId&gt;hibernate-validator&lt;/artifactId&gt;
    &lt;version&gt;7.0.2.Final&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<p>But now I get the following error during integration testing or run:</p>
<blockquote>
<p>javax.validation.NoProviderFoundException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.</p>
</blockquote>
<p>Why does it happen and how to fix it?</p>
",https://stackoverflow.com/questions/71077641/hibernate-7-0-2-javax-validation-noproviderfoundexception,"['java', 'spring', 'hibernate', 'maven']",1757,True,2,1
Unit testing a method that calls other methods Jest,"<p>I was thinkig a lot on WHAT to test in a method that works like an &quot;orchestrator&quot; and it's only job is to calls functions. So I have this BattleInteractor class</p>
<pre><code>class BattleInteractor {
    constructor(opts) {
        this.battleRepository = opts.battleRepository
        this.battleEntity = opts.battleEntity
        this.battleWinner = opts.battleWinner
        this.typeFactoryService = opts.typeFactory
    }
    
    async execute(pokemonOne, pokemonTwo) {

        const battleResult = this.battle(pokemonOne, pokemonTwo)
        return battleResult
    }

    battle(pokemonOne, pokemonTwo) {
        const strategy = this.typeFactoryService.getStrategy(pokemonOne, pokemonTwo)
        const pokemonsSetted = strategy.setStats(pokemonOne, pokemonTwo)
        const battleResult = this.battleEntity.battleLogic(pokemonsSetted)
        return this.battleWinner.battleWinner(battleResult)
    }

}

module.exports = BattleInteractor
</code></pre>
<p>And the test file with all methods mocked:</p>
<pre><code>const BattleInteractor = require('../../../../src/application/useCases/battle/battleInteractor')
describe('BattleInteractor test', () =&gt; {

    const pokemonOneMock = 'mock'
    const pokemonTwoMock = 'mock'
    const battleWinnerMock = 'mock'

    class TypeMock {
        setStats() {
            return 'mockStats'
        }
    }

    const battleInteractor = new BattleInteractor({
        battleRepository: {
            savedDatabase: () =&gt; true
        },
        typeFactory: {
            getStrategy: () =&gt; {
                return new TypeMock()
            },
        },
        battleEntity: {
            battleLogic: () =&gt; {
                return &quot;battleLogicMock&quot;
            }
        },
        battleWinner: {
            battleWinner: () =&gt; {
                return battleWinnerMock
            }
        },
    })


    test.only('Should return properties formatted', async () =&gt; {
        const res = await battleInteractor.execute(pokemonOneMock, pokemonTwoMock)
        expect(res.message).toBe(&quot;carnivine and naganadel have tied&quot;)
    })


})
</code></pre>
<p>All works fine, so I have some questions:
What should I test in a method like this?
Is this a unit testing or a integration testing?
How necessary is it to test a class/method like this?</p>
",https://stackoverflow.com/questions/72066525/unit-testing-a-method-that-calls-other-methods-jest,"['javascript', 'node.js', 'unit-testing', 'jestjs', 'integration-testing']",493,False,1,0
"Flutter integration test not working, uri not found","<p>Edit: tl;dr If you're getting &quot;Target of URI doesn't exist&quot; errors when adding a new package, try closing the Android Studio project and re-opening it.</p>
<p>I'm just getting started with integration testing on my Flutter app and for some reason it can't find the integration_testing uri.</p>
<p><a href=""https://i.stack.imgur.com/QfrJy.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/QfrJy.png"" alt=""error"" /></a></p>
<p>I've followed all the steps <a href=""https://docs.flutter.dev/cookbook/testing/integration/introduction"" rel=""nofollow noreferrer"">here</a> including:</p>
<ol>
<li>Updating my pubspec.yaml</li>
</ol>
<pre><code>dev_dependencies:
  integration_test:
    sdk: flutter
  flutter_test:
    sdk: flutter
</code></pre>
<ol start=""2"">
<li><p>Creating the <code>integration_test/app_test.dart</code> directory and file:
<a href=""https://i.stack.imgur.com/asczp.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/asczp.png"" alt=""enter image description here"" /></a></p>
</li>
<li><p>Run <code>pub get</code>, <code>flutter clean</code>.</p>
</li>
<li><p>On latest flutter version and no issues with doctor:</p>
</li>
</ol>
<pre><code>Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.10.3, on macOS 11.3.1 20E241 darwin-arm, locale
    en-CA)
[✓] Android toolchain - develop for Android devices (Android SDK version
    32.0.0-rc1)
[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.1)
[✓] IntelliJ IDEA Community Edition (version 2021.3)
[✓] Connected device (2 available)
[✓] HTTP Host Availability

• No issues found!

</code></pre>
<p>Here's the complete <code>pubspec.yaml</code></p>
<pre><code>name: squabbit
description: A new Flutter application.

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.8.0+80

environment:
  sdk: &quot;&gt;=2.7.0 &lt;3.0.0&quot;

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^1.1.0
  firebase_auth: ^1.1.3
  firebase_storage: ^8.0.5
  cloud_firestore: ^1.0.7
  firebase_crashlytics: ^2.0.2
  rxdart: 0.26.0
  intl: ^0.17.0
  #  file_picker: ^1.1.1
  google_sign_in: ^5.2.3
  image_picker: 0.7.4
  cached_network_image: ^3.0.0
  flutter_google_places: ^0.3.0
  google_maps_webservice: ^0.0.19
  carousel_pro: ^1.0.0
  flutter_launcher_icons: ^0.9.0
  package_info: ^2.0.0
  mime: ^0.9.7
  google_fonts: 2.1.0
  enum_to_string: 1.0.14
  shared_preferences: ^2.0.5
  algolia: 1.0.1
  flutter_email_sender: ^5.0.0
  device_info_plus: ^1.0.1
  material_design_icons_flutter: 4.0.5955
  visibility_detector: ^0.2.2
  fluttertoast: ^8.0.7
  in_app_review: ^2.0.2
  cloud_functions: ^3.0.0
  firebase_analytics: ^8.2.0

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  in_app_purchase: ^0.5.2
  firebase_messaging: ^11.2.6
  firebase_remote_config: ^2.0.2

dev_dependencies:
  integration_test:
    sdk: flutter
  flutter_test:
    sdk: flutter

flutter_icons:
  android: false
  ios: true
  image_path: &quot;assets/icon/icon.png&quot;


# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:
  assets:
    - assets/images/

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

</code></pre>
",https://stackoverflow.com/questions/71498072/flutter-integration-test-not-working-uri-not-found,"['flutter', 'integration-testing', 'flutter-integration-test']",1531,True,1,2
Springboot 2.7 : Property &#39;sqlSessionFactory&#39; or &#39;sqlSessionTemplate&#39; are required in @WebMvcTest for spring boot with mybatis,"<p>Below is my PaymentController Unittest</p>
<pre><code>@WebMvcTest(PaymentController.class)
public class PaymentControllerTest {
    @MockBean
    PaymentService paymentService;

    @Autowired
    MockMvc mockMvc;

    @Test
    public void testFindAllPaymentDtoAndExpect200() throws Exception {
         mockMvc.perform(MockMvcRequestBuilders
                        .get(&quot;/payment/list&quot;))
                        .andExpect(status().isOk());
    }
    
</code></pre>
<p>I'm seeing the below stacktrace when I run the above unit test and am wondering why the @WebMvcTest trying to initialize the <code>sqlSessionFactory</code> for unit test? Can someone please help me fix this error?
I have refered the similar issue <a href=""https://github.com/mybatis/spring-boot-starter/issues/227"" rel=""nofollow noreferrer"">https://github.com/mybatis/spring-boot-starter/issues/227</a> but it was for integration testing in my case it is a unit testing.</p>
<pre><code>    Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.postProcessFields(MockitoTestExecutionListener.java:110)
    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.injectFields(MockitoTestExecutionListener.java:94)
    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.prepareTestInstance(MockitoTestExecutionListener.java:61)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:248)
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$8(ClassBasedTestDescriptor.java:363)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:368)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$9(ClassBasedTestDescriptor.java:363)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179)
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
    at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310)
    at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735)
    at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734)
    at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:362)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:283)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:282)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:272)
    at java.base/java.util.Optional.orElseGet(Optional.java:364)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:271)
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:102)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:101)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:66)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$2(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:90)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    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.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193)
    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)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoApiController': Unsatisfied dependency expressed through field 'demoService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoServiceImpl' defined in file [C:\Dev\gitlab\billing-app\marketplace\build\classes\java\main\us\billing\service\impl\DemoServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'demoDataReadMapper' defined in file [C:\Dev\gitlab\billing-app\marketplace\build\classes\java\main\us\billing\mapper\DemoDataReadMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
    at app//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:659)
    at app//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639)
    at app//org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119)
    at app//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1431)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
    at app//org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
    at app//org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955)
    at app//org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
    at app//org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
    at app//org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
    at app//org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
    at app//org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
    at app//org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:132)
    at app//org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at app//org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    ... 88 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoServiceImpl' defined in file [C:\Dev\gitlab\billing-app\marketplace\build\classes\java\main\us\billing\service\impl\DemoServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'demoDataReadMapper' defined in file [C:\Dev\gitlab\billing-app\marketplace\build\classes\java\main\us\billing\mapper\DemoDataReadMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
    at app//org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
    at app//org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
    at app//org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
    at app//org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
    at app//org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1391)
    at app//org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1311)
    at app//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:656)
    ... 107 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'demoDataReadMapper' defined in file [C:\Dev\gitlab\billing-app\marketplace\build\classes\java\main\us\billing\mapper\DemoDataReadMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
    at app//org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
    at app//org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
    at app//org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1391)
    at app//org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1311)
    at app//org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
    at app//org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
    ... 120 more
Caused by: java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
    at org.springframework.util.Assert.notNull(Assert.java:201)
    at org.mybatis.spring.support.SqlSessionDaoSupport.checkDaoConfig(SqlSessionDaoSupport.java:122)
    at org.mybatis.spring.mapper.MapperFactoryBean.checkDaoConfig(MapperFactoryBean.java:73)
    at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800)
    ... 131 more
</code></pre>
<p>Below is <code>DemoApiController</code> code which is not linked with the <code>PaymentController</code> that am trying to unit test</p>
<pre><code>@RestController
public class DemoApiController implements DemoApi {
    @Autowired
    private DemoService demoService;

    @Override
    public String getDemoData(String id) {          
        return &quot;demo data size &quot; +demoService.demoFetchFromDatabase().size();
    }
}

public interface DemoService {
    List&lt;DemoData&gt; demoFetchFromDatabase();
}

@Service
@RequiredArgsConstructor
public class DemoServiceImpl implements DemoService {

    private final DemoDataReadMapper demoDataReadMapper;  

    @Override
    public List&lt;DemoData&gt; demoFetchFromDatabase() {
        return demoDataReadMapper.listDemoData(Arrays.asList(&quot;1&quot;, &quot;2&quot;));
    }
}

@Mapper
@Repository
@DBRouter(DatasourceType.Slave)
public interface DemoDataReadMapper {
    List&lt;DemoData&gt; listDemoData(@Param(&quot;items&quot;) Collection&lt;String&gt; idList);
}
</code></pre>
",https://stackoverflow.com/questions/74707199/springboot-2-7-property-sqlsessionfactory-or-sqlsessiontemplate-are-requir,"['java', 'spring', 'spring-boot', 'unit-testing', 'spring-mvc-test']",1155,False,3,1
How do I separate between integration testing and unit testing using Hapi in Node.js?,"<p>How do I separate between integration testing and unit testing using Hapi in Node.js?</p>
<p>I am trying to reduce the testing time in our automations for every time we update a unit within our API.</p>
<p>I was wondering can I just create two new folders test/unit and test/int to separate the scripts and what would the update to the package.json require?</p>
<p>I have the following in the package.json which runs the .labrc.js
package.json</p>
<pre><code>    &quot;test&quot;: &quot;npm run version-stamp &amp;&amp; lab --bail -t 80 -r html -o coverage.html -r console -o stdout -r junit -o TestResult.xml -r lcov -o coverage.dat&quot;,
    &quot;simple-test&quot;: &quot;npm run version-stamp &amp;&amp; lab&quot;,
    &quot;test-int&quot;: &quot;not sure what to put here&quot;,
</code></pre>
<p>labrc.js</p>
<pre><code>module.exports = {
    verbose: true,
    timeout: 7500,
    lint: true,
    paths: [
        &quot;test/init/aws&quot;,
        &quot;test/unit/plugins&quot;,
        &quot;test/unit/utils&quot;,
        &quot;test/unit/routes&quot;
    ],
</code></pre>
",https://stackoverflow.com/questions/74690668/how-do-i-separate-between-integration-testing-and-unit-testing-using-hapi-in-nod,"['node.js', 'unit-testing', 'jestjs', 'nunit', 'hapi.js']",52,False,0,1
"Designing Integration Test Suite for Google Cloud Workflows, Dataflow &amp; Pub/Sub","<p>Need some advice on technologies and design choices for integration testing GCP Workflows which is triggered by Pub/Sub and starts the Dataflow job.</p>
<p>For running the tests locally, I was thinking of using Pub/Sub emulator but for workflows I would need to either trigger a test workflow execution or setup a workflow for testing purposes?</p>
<p>Any ideas on how to test such an environment or technologies that can be used to execute and assert test results will be appreciated.</p>
",https://stackoverflow.com/questions/72249440/designing-integration-test-suite-for-google-cloud-workflows-dataflow-pub-sub,"['google-cloud-platform', 'integration-testing', 'google-cloud-pubsub', 'google-workflows']",302,True,1,1
"Error: unable to authenticate user when running kibana, elasticsearch and APM from docker","<p>I'm following <a href=""https://www.elastic.co/guide/en/kibana/current/kibana-debugging.html#_running_kibana_with_the_apm_agent_locally"" rel=""nofollow noreferrer"">this guide</a> to run APM with kibana and elasticsearch:</p>
<p>and when I run this command: <code>./scripts/compose.py start master --no-kibana</code></p>
<p>this is the output I get:</p>
<pre><code>Kibana will be launched to configure APM integration and stopped after that.
Starting/Building stack services..

Pulling elasticsearch ... done
Pulling kibana        ... done
Pulling apm-server    ... done
Pulling wait-service  ... done
Starting localtesting_8.4.1_elasticsearch ... done
Starting localtesting_8.4.1_kibana        ... done

ERROR: for wait-service  Container &quot;3897cf4e31e4&quot; is unhealthy.

ERROR: for apm-server  Container &quot;3897cf4e31e4&quot; is unhealthy.
ERROR: Encountered errors while bringing up the project.
Traceback (most recent call last):
  File &quot;/home/omar/Downloads/apm-integration-testing/./scripts/compose.py&quot;, line 31, in &lt;module&gt;
    main()
  File &quot;/home/omar/Downloads/apm-integration-testing/./scripts/compose.py&quot;, line 17, in main
    setup()
  File &quot;/home/omar/Downloads/apm-integration-testing/scripts/modules/cli.py&quot;, line 213, in __call__
    self.args.func()
  File &quot;/home/omar/Downloads/apm-integration-testing/scripts/modules/cli.py&quot;, line 590, in start_handler
    self.build_start_handler(&quot;start&quot;)
  File &quot;/home/omar/Downloads/apm-integration-testing/scripts/modules/cli.py&quot;, line 782, in build_start_handler
    self.run_docker_compose_process(docker_compose_cmd + up_params)
  File &quot;/home/omar/Downloads/apm-integration-testing/scripts/modules/cli.py&quot;, line 476, in run_docker_compose_process
    subprocess.check_call(docker_compose_cmd)
  File &quot;/usr/lib/python3.10/subprocess.py&quot;, line 369, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['docker-compose', '-f', '/home/omar/Downloads/apm-integration-testing/docker-compose.yml', 'up', '-d']' returned non-zero exit status 1.
</code></pre>
<p>and when I run <code>docker ps</code> I get this:</p>
<pre><code>CONTAINER ID   IMAGE                                                          COMMAND                  CREATED      STATUS                     PORTS                                NAMES
3897cf4e31e4   docker.elastic.co/kibana/kibana:8.4.1-SNAPSHOT                 &quot;/bin/tini -- /usr/l…&quot;   2 days ago   Up 7 minutes (unhealthy)   127.0.0.1:5601-&gt;5601/tcp             localtesting_8.4.1_kibana
4eef98f32f5d   docker.elastic.co/elasticsearch/elasticsearch:8.4.1-SNAPSHOT   &quot;/bin/tini -- /usr/l…&quot;   2 days ago   Up 8 minutes (healthy)     127.0.0.1:9200-&gt;9200/tcp, 9300/tcp   localtesting_8.4.1_elasticsearch
</code></pre>
<p>So I try running kibana locally with <code>yarn start</code> in the kibana folder, but I encounter this error:</p>
<pre><code>[ERROR][elasticsearch-service] Unable to retrieve version information from Elasticsearch nodes. security_exception: [security_exception] Reason: unable to authenticate user [kibana_system] for REST request [/_nodes?filter_path=nodes.*.version%2Cnodes.*.http.publish_address%2Cnodes.*.ip]
</code></pre>
<p>I tried adding the <code>kibana_system</code> user to kibana.yml like this:</p>
<pre><code>elasticsearch.username: 'kibana_system'
</code></pre>
<p>but with no luck, If someone encountered a similar issue or got apm-integration-testing to work locally with kibana, I'd be grateful for the help</p>
",https://stackoverflow.com/questions/73756528/error-unable-to-authenticate-user-when-running-kibana-elasticsearch-and-apm-fr,"['docker', 'elasticsearch', 'kibana', 'apm', 'elastic-apm']",314,False,0,0
Desktop window size in flutter integration testing,"<p>Now that the Desktop embedding in flutter is almost stable it is interesting to perform the integration testing directly on the OS you are using during the development (instead of initialize every time an emulator and wait until is ready). It should also be interesting in the CI pipeline. Unfortunatly I can't find a way to set the window size dimension when I perform the test. This is needed for adaptive apps.</p>
<p>I tried with:</p>
<pre class=""lang-dart prettyprint-override""><code>tester.binding.window.physicalSizeTestValue = const Size(300, 300);
</code></pre>
<p>but it didn't worked for me</p>
",https://stackoverflow.com/questions/71814768/desktop-window-size-in-flutter-integration-testing,"['flutter', 'testing', 'integration-testing']",239,True,0,2
Integration test not working with Spring Boot and Test Containers,"<p>I implemented a project with Spring Boot + MySQL + Docker + Fly way. I created a test class for the integration testing using test containers. Below mentioned the implemented test class.</p>
<pre><code>@Testcontainers
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class UserControllerIntegrationTest {

    @Autowired
    private UserController userController;

    @Autowired
    UriComponentsBuilder builder;

    @Container
    public static MySQLContainer container = new MySQLContainer(&quot;mysql:latest&quot;)
            .withDatabaseName(&quot;example_db&quot;)
            .withUsername(&quot;Test&quot;)
            .withPassword(&quot;Test&quot;);

    @Container
    public static GenericContainer&lt;?&gt; redis =
            new GenericContainer&lt;&gt;(DockerImageName.parse(&quot;redis:6.2-alpine&quot;)).withExposedPorts(6379);

    @BeforeAll
    public static void setUp(){
        container.withReuse(true);
        container.withInitScript(&quot;src/main/test/resources/schema.sql&quot;);
        container.start();
        redis.start();
    }

    @DynamicPropertySource
    public static void overrideProperties(DynamicPropertyRegistry registry){
        registry.add(&quot;spring.datasource.url&quot;, container::getJdbcUrl);
        registry.add(&quot;spring.datasource.username&quot;, container::getUsername);
        registry.add(&quot;spring.datasource.password&quot;, container::getPassword);
        registry.add(&quot;spring.datasource.driver-class-name&quot;, container::getDriverClassName);
    }

    @Test
    public void testCreateUser(){
        CreateUserRequestDto request = new CreateUserRequestDto();
        request.setName(&quot;Test User&quot;);
        request.setAge(45);
        UserResponseDto response = userController.create(request);
        assertNotNull(response);
    }

}
</code></pre>
<p>When I build the project, every time it search the host db(app_db) which is created in docker container.
Below mentioned the application.yml and docker-compose.yml files I used.</p>
<p><strong>docker-compose.yml</strong></p>
<pre><code> version: &quot;3.0&quot;
 services:
  api_service:
    build: .
    restart: always
    ports:
      - 8090:8090
    depends_on:
      - mysql_db
    links:
      - mysql_db:app_db
  mysql_db:
    image: &quot;mysql:8.0&quot;
    restart: always
    ports:
      - 3306:3306
    environment:
      MYSQL_DATABASE: test_db
      MYSQL_USER: user
      MYSQL_PASSWORD: password
      MYSQL_ROOT_PASSWORD: password
</code></pre>
<p><strong>application.yml</strong></p>
<pre><code>app:
  name: test-service

server:
  port: 8090

spring:
  datasource:
    url: jdbc:mysql://app_db:3306/test_db
    username: user
    password: password
    initialization-mode: always
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL8Dialect
    hibernate:
      ddl-auto: create
</code></pre>
<blockquote>
<p>Caused by: java.net.UnknownHostException: No such host is known (app_db)</p>
</blockquote>
<p>Any help or workarounds are appreciated for solve this issue.</p>
",https://stackoverflow.com/questions/74572141/integration-test-not-working-with-spring-boot-and-test-containers,"['mysql', 'spring-boot', 'docker', 'integration-testing']",321,False,0,0
getting an error The following constructor parameters did not have matching fixture data: PostgreSqlResource resource,"<p>I am using xunit to do integration testing, and below is my test class.</p>
<pre><code>public class CodesAndGuidelinesTest : IClassFixture&lt;SchemaCache&gt;
{
    public readonly SchemaCache schemaCache;
    public CodesAndGuidelinesTest(PostgreSqlResource resource) 
    {
        schemaCache = new SchemaCache(resource);
    }

    [Fact]
    public async Task Create_Name_Contains_Expression()
    {
        IRequestExecutor requestExecutor = await schemaCache.CodesAndGuidelinesExecutor;
        .......
    }
}
</code></pre>
<p>Here is the schema cache class</p>
<pre><code>public class SchemaCache : QueryTestBase
{
    Task&lt;IRequestExecutor&gt; _codesAndGuidelinesExecutor;
    public SchemaCache(PostgreSqlResource resource) : base(resource)
    {
        _codesAndGuidelinesExecutor = CreateDb(CodesAndGuidelinesMockFixture.codeStandardGuidelines);
    }

    public Task&lt;IRequestExecutor&gt; CodesAndGuidelinesExecutor
    {
        get { return _codesAndGuidelinesExecutor; }
    }
}
</code></pre>
<p>Here <code>CodesAndGuidelinesMockFixture.codeStandardGuidelines</code> is just a mock object, and When I run the test cases, I am getting the below error.</p>
<blockquote>
<p>Class fixture type 'API.Tests.SchemaCache` had one or more unresolved
constructor arguments: PostgreSqlResource resource,
CodeStandardGuideline[] codesAndGuidelines    The following
constructor parameters did not have matching fixture data:
PostgreSqlResource resource</p>
</blockquote>
<p>I am not sure where I am doing wrong with the above code. Could anyone point me in the right direction?</p>
<p>Thanks!!!</p>
<p>Update :
QueryTestBase class</p>
<pre><code>public class QueryTestBase
{
    private readonly PostgreSqlResource _resource;
    public QueryTestBase(PostgreSqlResource resource)
    {
        _resource = resource;
    }

    protected async Task&lt;Func&lt;IResolverContext, IQueryable&lt;T&gt;&gt;&gt; BuildResolverAsync&lt;T&gt;(T[] arrayOfEntities) where T : class
    {
        var databaseName = Guid.NewGuid().ToString(&quot;N&quot;);
        var options = new DbContextOptionsBuilder&lt;APIDbContext&gt;()
            .UseNpgsql(_resource.ConnectionString)
            .Options;
        .......
        .......         
        return _ =&gt; set.AsQueryable();
    }

    protected async Task&lt;IRequestExecutor&gt; CreateDb&lt;T&gt;(T[] Entities) where T : class
    {
        Func&lt;IResolverContext, IQueryable&lt;T&gt;&gt; resolver = await BuildResolverAsync(Entities);

        return .......
    }
}
</code></pre>
",https://stackoverflow.com/questions/72635043/getting-an-error-the-following-constructor-parameters-did-not-have-matching-fixt,"['c#', 'moq', 'xunit', 'xunit.net', 'xunit2']",862,True,4,1
How to setup Asp.net Core TestServer with Azure Function v4 for Integration Tests,"<p>Trying to setup TestServer form Asp.Net Core manually because WebApplicationFactory is not available for Azure functions. This is for Integration tests in memory.</p>
<p>I have created my own Startup for Integration testing  where I use Sqllite in memory to test services and repositories.</p>
<p>Which works fine, but I want to be able to use TestServer from Asp.Net Core into Azure Functions, tried to Setup using, but throws an exception if I use ConfigureWebHost and ConfigureServices:</p>
<p>System.ObjectDisposedException : Cannot access a disposed object.
Object name: 'IServiceProvider'.</p>
<pre><code>ConfigureWebHost((webBuilder) =&gt;
{
    webBuilder.UseTestServer();
})
</code></pre>
<pre><code>    public BaseIntegrationTest()
    {
        TestHost = CreateHostBuilder().Build();
        Task.Run(() =&gt; TestHost.RunAsync());
    }

    public IHost TestHost { get; }

    public static IHostBuilder CreateHostBuilder(string[] args = null) =&gt;
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((services) =&gt;
            {
                services.AddHttpContextAccessor();

                services.AddDomain();

                services.AddDbContext&lt;HubDbContext&gt;(options
                    =&gt; options.UseSqlite(&quot;Filename=:memory:&quot;,
                        (options) =&gt;
                        {
                        }));

                services.AddRepositories();
            });
</code></pre>
",https://stackoverflow.com/questions/73661689/how-to-setup-asp-net-core-testserver-with-azure-function-v4-for-integration-test,"['c#', 'asp.net-core', 'azure-functions', 'integration-testing']",566,False,1,0
Effector: &quot;.use argument should be a function&quot; on attach,"<p>effector throws error &quot;.use argument should be a function&quot; at getCurrent (node_modules/effector/effector/region.ts:27:5) on attach method while testing.</p>
<p>I'm trying integration testing with mocking of some initial state.</p>
<pre><code>//babel config
module.exports = (api) =&gt; {
  if (api.env('test')) {
    config.plugins.push([
      'module-resolver',
      {
        root: ['.'],
        alias: {
          effector-react: 'effector-react/scope',
        },
      },
    ]);
  }
  return config;
};

//store.ts
export const getUsersFx = attach({
  effect: getUsersOriginalFx,
  source: [$clientId],
  mapParams: (_, [clientId]) =&gt; ({
    clientId
  }),
});

//component.tsx
import { render } from '@testing-library/react';
import { Provider } from 'effector-react/scope'

describe('TestableComponent', () =&gt; {
  test('should increment counter after click', () =&gt; {
    const scope = fork()

    const rendered = render(
      &lt;Provider value={scope}&gt;
        &lt;TestableComponent /&gt;
      &lt;/Provider&gt;
    );
  })
})
</code></pre>
<p>I think the reason is that Effector mocks Effect and under the hood uses .use for effect callback mock. But then it change it to null or undefined and Effector throws error that fn in .use(fn) must be function</p>
<p>Effector mocks getUsersFx =&gt; getUsersFx.use(mockFn &lt;- it's undefined i think).</p>
<p>Effector version: 22</p>
",https://stackoverflow.com/questions/70862023/effector-use-argument-should-be-a-function-on-attach,['effector'],141,True,1,1
MockMvc with SpringBootTest is throwing exception HttpMediaTypeNotSupportedException when testing the controller,"<p>I am testing request validation in Spring RestController with the help of integration testing and MockMvc.</p>
<p><strong>ControllerTest.java</strong></p>
<pre><code>@ExtendWith(MockitoExtension.class)
@SpringBootTest(classes = Controller.class)
@AutoConfigureMockMvc(addFilters = false)
class ControllerTest {

    private ObjectMapper objectMapper;

    @MockBean
    private Service service;

    @Autowired
    private MockMvc mockMvc;

    @BeforeEach
    void setUp() {
        objectMapper = new ObjectMapper();
    }

    @Test
    void createOrAdd_shouldReturnErrorResponseOnInvalidInput() throws Exception {
        Request request = Request.builder()
                .name(&quot;name&lt;script&gt;&quot;)
                .primaryEmail(&quot;test@mail.com&quot;)
                .build();

        mockMvc.perform(MockMvcRequestBuilders.post(&quot;/api/create&quot;)
                        .accept(MediaType.APPLICATION_JSON)
                        .contentType(MediaType.APPLICATION_JSON_VALUE)
                        .content(objectMapper.writeValueAsString(request))
                .characterEncoding(&quot;utf-8&quot;))
                .andExpect(MockMvcResultMatchers.status().isBadRequest());
    }
}
</code></pre>
<p><strong>Controller.java :</strong></p>
<pre><code>@Slf4j
@RestController
public class Controller {

    private final Service service;

    public Controller(Service service) {
        this.service = service;
    }

    @PostMapping(value = &quot;/api/create&quot;, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity&lt;GenericResponse&lt;Response&gt;&gt; createOrAdd(@RequestBody @Valid Request request, Errors errors) {
        GenericResponse&lt;Response&gt; genericResponse = new GenericResponse&lt;&gt;();
        try {
            if (errors.hasErrors()) {
                throw new RequestParamsException(errors.getAllErrors());
            }
            Response response = service.createOrAdd(request);
            genericResponse.setData(response);
            return ResponseEntity.ok().body(genericResponse);
        } catch (RequestParamsException ex) {
            genericResponse.setErrors(ex.getErrors());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(genericResponse);
        }
    }
</code></pre>
<p><strong>Error</strong> :</p>
<pre><code>WARN 17304 --- [           main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=utf-8' not supported]

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /api/create
       Parameters = {}
          Headers = [Content-Type:&quot;application/json;charset=utf-8&quot;, Accept:&quot;application/json&quot;, Content-Length:&quot;162&quot;]
             Body = {&quot;name&quot;:&quot;name&lt;script&gt;alert(1)&lt;/script&gt;&quot;,&quot;primary_email_address&quot;:&quot;test@mail.com&quot;}
    Session Attrs = {}

Handler:
             Type = com.org.controller.Controller
           Method = com.org.controller.Controller#createOrAdd(Request, Errors)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.HttpMediaTypeNotSupportedException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 415
    Error message = null
          Headers = [Accept:&quot;application/octet-stream, text/plain, application/xml, text/xml, application/x-www-form-urlencoded, application/*+xml, multipart/form-data, multipart/mixed, */*&quot;]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status expected:&lt;400&gt; but was:&lt;415&gt;
Expected :400
Actual   :415
</code></pre>
<p>I have used the correct <code>Content-Type</code> and <code>Accept</code> Headers while making a call in <code>Test.java</code> using <code>mockMvc</code>, but still it's giving HttpMediaTypeNotSupportedException. Tried many combinations in <code>Accept</code> and <code>Content-Type</code> but still not working.</p>
<p>I have read many SO questions related to this exception, but couldn't find what's the issue here.
Still not able to figure out why it's saying HttpMediaTypeNotSupportedException.</p>
<p><strong>Update</strong> : After removing <code>addFilters = false</code> as suggested, not able to find the handler itself.</p>
<pre><code>    MockHttpServletRequest:
          HTTP Method = POST
          Request URI = /api/create
           Parameters = {}
              Headers = [Content-Type:&quot;application/json;charset=utf-8&quot;, Accept:&quot;application/json&quot;, Content-Length:&quot;162&quot;]
                 Body = {&quot;name&quot;:&quot;name&lt;script&gt;alert(1)&lt;/script&gt;&quot;,&quot;primary_email_address&quot;:&quot;test@mail.com&quot;}
    Session Attrs = {org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN=org.springframework.security.web.csrf.DefaultCsrfToken@7a687d8d}   

     
Handler:
             Type = null

Async:
    Async started = false
     Async result = null
    
    Resolved Exception:
             Type = null
    
    ModelAndView:
            View name = null
                 View = null
                Model = null
    
    FlashMap:
           Attributes = null
    
MockHttpServletResponse:
           Status = 403
    Error message = Forbidden
          Headers = [X-Content-Type-Options:&quot;nosniff&quot;, X-XSS-Protection:&quot;1; mode=block&quot;, Cache-Control:&quot;no-cache, no-store, max-age=0, must-revalidate&quot;, Pragma:&quot;no-cache&quot;, Expires:&quot;0&quot;, X-Frame-Options:&quot;DENY&quot;]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

    
java.lang.AssertionError: Status expected:&lt;400&gt; but was:&lt;403&gt;
Expected :400
Actual   :403
</code></pre>
<p><strong>Request</strong> :</p>
<pre><code>@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CreateAgencyRequest {

    @NotNull(message = &quot;name can't be null&quot;)
    @JsonProperty(value = &quot;name&quot;)
    @Pattern(regexp = REGEX_CONST, message = &quot;name is not valid&quot;)
    private String name;

    @NotNull(message = &quot;primary_email_address can't be null&quot;)
    @JsonProperty(value = &quot;primary_email_address&quot;)
    private String primaryEmail;

}
</code></pre>
",https://stackoverflow.com/questions/72874685/mockmvc-with-springboottest-is-throwing-exception-httpmediatypenotsupportedexcep,"['spring', 'spring-boot', 'integration-testing', 'spring-boot-test', 'mockmvc']",957,True,0,3
How to COPY files from outside of the Earthfile&#39;s directory?,"<p>Suppose I have a monorepo. Apps (<code>app1</code>, <code>app2</code>) use a Gradle as a build system and share some build-logic with <code>includeBuild(&quot;../shared-build-logic&quot;)</code> which is outside of the root of each app.</p>
<pre><code>├── shared-build-logic
│   └── src/...
└── app1
    ├── Earthfile
    ├── build.gradle
    ├── src/...
└── app2
    ├── Earthfile
    ├── build.gradle
    ├── src/...
</code></pre>
<p>Is it possible for <code>Earthfile</code> to access the files from outside of its root folder or Earthly has the same restrictions as <code>Dockerfile</code>?</p>
<p>I get the following error on attempt to <code>COPY ../shared-build-logic ./</code>:</p>
<pre><code>============================ ❌ FAILURE [2. Build 🔧] ============================

Repeating the output of the command that caused the failure
            +compile *failed* | --&gt; COPY ../shared-build-logic ./
            +compile *failed* | [no output]
            +compile *failed* | ERROR Earthfile line 22:4
            +compile *failed* |       The command
            +compile *failed* |           COPY ../shared-build-logic ./
            +compile *failed* |       failed: &quot;/shared-build-logic&quot;: not found
</code></pre>
<p>I would also like to perform integration testing with the <code>docker-compose.yaml</code> file located one level above the Eartfile root, but facing the similar problem:</p>
<pre><code>integration-tests:
    FROM earthly/dind:alpine
    COPY ../docker-compose.yaml ./ # &lt;------- does not work
    WITH DOCKER --compose docker-compose.yaml --load build-setup=+compile --allow-privileged
        RUN docker run -e SPRING_DATA_MONGODB_URI=mongodb://mongodb:27017/test-db --network=default_dev-local build-setup ./gradlew test
    END
</code></pre>
<p>Is my the only solution to the problem to move <code>Earthfile</code> itself one level upper?</p>
",https://stackoverflow.com/questions/74866036/how-to-copy-files-from-outside-of-the-earthfiles-directory,['earthly'],167,True,2,1
Liquibase causes &quot;could not prepare statement; SQL&quot; only with H2,"<p>I integrated Liquibase in my Spring Boot application. Using it with MariaDB works fine.</p>
<p>For unit &amp; integration testing I use a H2 in-memory database. While running tests it causes following exception:</p>
<pre><code>org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [select user0_.id as id1_19_0_, user0_.created_at as created_2_19_0_, user0_.updated_at as updated_3_19_0_, user0_.version as version4_19_0_, user0_.activated as activate5_19_0_, user0_.birthday as birthday6_19_0_, user0_.email as email7_19_0_, user0_.firstname as firstnam8_19_0_, user0_.force_password_change as force_pa9_19_0_, user0_.password_hash as passwor10_19_0_, user0_.role as role11_19_0_, user0_.surname as surname12_19_0_ from users user0_ where user0_.id=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:259) ~[spring-orm-5.3.19.jar:5.3.19]
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233) ~[spring-orm-5.3.19.jar:5.3.19]
</code></pre>
<p>My prod config (working):</p>
<pre class=""lang-yaml prettyprint-override""><code>spring:
  main:
    allow-bean-definition-overriding: true
  datasource:
    url: jdbc:mariadb://localhost:3307/testdb
    username: user
    password: psw

  jpa:
    generate-ddl: false
    database-platform: org.hibernate.dialect.MariaDB103Dialect

  sql:
    init:
      mode: never

  liquibase:
    enabled: true
    change-log: classpath:db/db.changelog-master.yaml

</code></pre>
<p>My test config (not working):</p>
<pre class=""lang-yaml prettyprint-override""><code>spring:
  main:
    allow-bean-definition-overriding: true

  datasource:
    url: jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;NON_KEYWORDS=user
    username: sa
    driver-class-name: org.h2.Driver
    password: password

  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    generate-ddl: false

  sql:
    init:
      mode: never

  liquibase:
    change-log: classpath:db/db.changelog-master.yaml
    enabled: true

  test:
    database:
      replace: none
</code></pre>
<p>What I tried:</p>
<ul>
<li>Multiple url configs including the <code>NON_KEYWORDS</code> option from H2 to exclude problems with user as it is maybe interpreted as a keyword.</li>
</ul>
<p>As it is working with MariaDB I think it is a problem related to H2.</p>
<p>Thankful for any help, documentation, link whatever :)</p>
",https://stackoverflow.com/questions/71996714/liquibase-causes-could-not-prepare-statement-sql-only-with-h2,"['sql', 'spring-boot', 'jpa', 'h2', 'liquibase']",553,True,0,1
Alternative to Enzyme for unit testing in React,"<p>Since Enzyme is dead for React 18 and everyone seems to be talking about React Testing Library, for a more integration-testing approach. However, in my case I need more of a unit-testing solution to test functions within my React component:</p>
<pre><code>export default function Chat({ userName, roomName }: ChatProps) {
    const [userInput, setUserInput] = useState(&quot;&quot;);
    const [messageList, setMessageList] = useState&lt;SocketMessageNS.NewMessageIn[]&gt;([]);

    const [sendSocketMessage, isConnected] = useSocketIo(userName, roomName, handleOnNewMessage);

    function handleOnNewMessage(msg: SocketMessageNS.NewMessageIn) {
        // ...
    }

    function handleOnSendMessage() {
        // ...
    }

    return (
        &lt;div className=&quot;Chat&quot;&gt;
            &lt;ChatHeader isConnected={isConnected} roomName={roomName} /&gt;
            &lt;ChatConversation data={messageList} userName={userName} /&gt;
            &lt;ChatInput value={userInput} onChange={setUserInput} onSubmit={handleOnSendMessage} /&gt;
        &lt;/div&gt;
    );
}
</code></pre>
<p>I want to be able to test my functions on their own, simply by calling them like you would do with Enzyme:       <code>wrapper.instance().handleOnSendMessage();</code></p>
<p>It doesn't seem to be possible with React Testing Library.
What do you do when you need to test your functions with React components with spies and such?</p>
",https://stackoverflow.com/questions/74281739/alternative-to-enzyme-for-unit-testing-in-react,"['reactjs', 'jestjs', 'react-testing-library']",49,False,-1,1
"How should we write test for repository , logic and controller layer in laravel?","<p>I am trying to write test for repository, logic and controller layer. Repository class injected inside logic and logic class injected to controller. I wrote the test for repository and mock repository in logic class to write test for logic. But for controller i wrote integration test like this:</p>
<pre><code>public function test_create_role()
{
    $data = Role::factory()-&gt;make()-&gt;toArray();

    $this-&gt;postJson(route('roles.store'), $data)
        -&gt;assertCreated();
}
</code></pre>
<p>Do I need to check if new data has been added to data base like this:</p>
<pre><code>public function test_create_role()
{
    $data = Role::factory()-&gt;make()-&gt;toArray();

    $this-&gt;postJson(route('roles.store'), $data)
        -&gt;assertCreated();

    $this-&gt;assertDatabaseHas('roles', $data);
}
</code></pre>
<p>Or is the repository test enough?
Do we need to test the repository layer and logic layer separately, or is integration testing enough?</p>
",https://stackoverflow.com/questions/72396001/how-should-we-write-test-for-repository-logic-and-controller-layer-in-laravel,"['laravel', 'unit-testing', 'testing', 'phpunit']",112,False,0,1
Error Could not find a part of the path when build the testing .net core application,"<p>I have a testing (unit testing and integration testing) app in .net core 5,,
Another explanation that I can say is that in my solution I have 3 Project , 1 for App and 2 other for testing
when I build my project I get this error</p>
<p>when I build my project I get this error</p>
<blockquote>
<p>Error     Could not find a part of the path 'C:\testProject\obj\Debug\net6.0\testProject.GeneratedMSBuildEditorConfig.editorconfig'.  testProject C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\Roslyn\Microsoft.Managed.Core.targets  190</p>
</blockquote>
<p>Why I get this error?
How can I solve this error?
Thank a bunch</p>
",https://stackoverflow.com/questions/74666115/error-could-not-find-a-part-of-the-path-when-build-the-testing-net-core-applica,"['c#', 'build']",2910,True,5,1
Unable to test c# rest controllers via in memory host integration tests,"<p>I am new to .net and c# and I am learning how to do integration testing on rest controllers in local.
I went through the below link for understanding and created a sample project.
<a href=""https://www.strathweb.com/2012/06/asp-net-web-api-integration-testing-with-in-memory-hosting/"" rel=""nofollow noreferrer"">https://www.strathweb.com/2012/06/asp-net-web-api-integration-testing-with-in-memory-hosting/</a></p>
<p>When I start the server and hit controller route it works fine. However, when I run the tests it doesn't work. Looks like http client is thinking there is an actual server which is hosting the service and it throws an error saying unable to connect. But I am trying to do via in memory host server. So this error doesn't make sense to me as there is no server started here. Below is the error:</p>
<pre><code>System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: No connection could be made because the target machine actively refused it. [::ffff:127.0.0.1]:80
</code></pre>
<p>Below is rest controller code:</p>
<pre><code>    namespace restapiproject.Controllers
{
    public class TestController : Controller
    {
        [HttpGet]
        public String Get()
        {
            return &quot;hello controller&quot;;
        }
    }
}
</code></pre>
<p>Within Startup.cs the below code is where route mapping is done</p>
<pre><code>// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c =&gt; c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;restapiproject v1&quot;));
            }
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =&gt;
            {
                endpoints.MapControllers();
                endpoints.MapControllerRoute(
                    name: &quot;default&quot;,
                    pattern: &quot;{controller=Home}/{action=Index}&quot;);
            });
        }
</code></pre>
<p>Here is the Integration test code:</p>
<pre><code>[TestClass]
    public class IntegrationTestController
    {
        [TestMethod]
        public void TestController()
        {
            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(name: &quot;Test&quot;, routeTemplate: &quot;Test&quot;, 
                defaults:
                        new
                        {
                            controller = &quot;Test&quot;,
                            action = &quot;get&quot;
                        });
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            HttpServer _httpServer = new HttpServer(config);
            _httpServer.InnerHandler = new HttpClientHandler();
            HttpClient client = new HttpClient(_httpServer);
            client.BaseAddress = new Uri(&quot;http://localhost/&quot;);
            String url = &quot;http://localhost/test/get&quot;;
            var request = new HttpRequestMessage
            {
                RequestUri = new Uri(url),
                Method = HttpMethod.Get
            };
            var response = client.Send(request);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
}
</code></pre>
<p>What I think here is when the server is created somehow it is unable to load this controllers within test project. I came across a code snippet where configure the webapi should fix but I am unable to refer this below code as I am getting compilation errors.</p>
<pre><code>WebApiApiConfig.Configure(config); // config of your Web API
</code></pre>
<p>Can someone please help me on how do I refer this webapiconfig and also how I make sure to load the controllers in the test project or if this error is something else.</p>
",https://stackoverflow.com/questions/72357747/unable-to-test-c-rest-controllers-via-in-memory-host-integration-tests,"['c#', 'rest', 'asp.net-web-api', 'asp.net-core-mvc']",408,False,0,1
WebApplicationFactory always return 404 (not found) for controllers calls in .net core 6,"<p>In .net core 6, startup.cs has been removed, the integration testing I used before doesn't work anymore as is. I need to do an update.</p>
<p>In my API (program.cs), I added:</p>
<pre><code>[assembly: InternalsVisibleTo(&quot;constructionCompanyAPI.IntegrationTests&quot;)]
</code></pre>
<p>and here is the Integration.Tests csproj:</p>
<p><a href=""https://i.stack.imgur.com/qkeB7.png"" rel=""nofollow noreferrer"">csprojImage</a></p>
<p>I created a ConstructionCompanyControllersTests.cs like:</p>
<pre><code>public class ConstructionCompanyControllerTests
{
    private HttpClient _client;

    public ConstructionCompanyControllerTests()
    {
        _client = new WebApplicationFactory&lt;Program&gt;()
            .WithWebHostBuilder(builder =&gt;
            {
                builder.ConfigureServices(services =&gt;
                {
                    var dbContextOptions = services
                    .SingleOrDefault(service =&gt; service.ServiceType == typeof(DbContextOptions&lt;ConstructionCompanyDbContext&gt;));

                    services.Remove(dbContextOptions);

                    services.AddDbContext&lt;ConstructionCompanyDbContext&gt;(options =&gt; options.UseInMemoryDatabase(&quot;ConstructionCompanyDb&quot;));
                });
            })
            .CreateClient();
    }
    [Theory]
    [InlineData(&quot;?pageNumber=1&amp;pageSize=10&quot;)]
    [InlineData(&quot;?pageNumber=1&amp;pageSize=5&quot;)]
    public async Task GetAll_WithQueryParameters_ReturnsOkResult(string queryParams)
    {
        // act

        var response = await _client.GetAsync(&quot;/api/constructionCompany&quot; + queryParams);

        // assert

        response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK);
    }
</code></pre>
<p>When I launch the API, every thing works correctly, I'm to see my controller in Swagger and call the get with a code 200 returns.</p>
<p>So each time the test fails here:</p>
<pre><code>var response = await _client.GetAsync(&quot;/api/constructionCompany&quot; + queryParams);
</code></pre>
<p>The response always get a 404 error (not found).</p>
<pre><code>Expected response.StatusCode to be HttpStatusCode.OK {value: 200}, but found HttpStatusCode.NotFound {value: 404}.
</code></pre>
<p>What should I do to make it works correctly?</p>
<p>Thanks</p>
<p>Edit:
The Entire program.cs file:</p>
<p><a href=""https://pastebin.com/8qtdzv4F"" rel=""nofollow noreferrer"">program.cs</a></p>
",https://stackoverflow.com/questions/73318209/webapplicationfactory-always-return-404-not-found-for-controllers-calls-in-ne,"['c#', '.net', 'testing', 'xunit']",800,True,2,1
Generating multiple jars for spring boot with gradle,"<p>My project is spring boot with gradle.  My goal is to have spring boot generate 2 different boot jars.  The first jar is the typical jar created today which would be used in production systems.  The second jar would be used by other systems for integration testing.  The second jar would have a different set of configuration and dependencies. Has anyone else done this?  I did not see any simple configuration for the <code>bootJar</code> task nor was i successful trying to create my own task based on <code>bootJar</code>.</p>
<p><em>UPDATE: Below is the solution which worked based upon Francisco Mateo's answer.</em></p>
<pre><code>configurations {
    integrationImplementation.extendsFrom implementation
    integrationRuntimeOnly.extendsFrom runtimeOnly
    //...
}


dependencies {
    // ...

    integrationRuntimeOnly 'com.h2database:h2'

    // ...
}

sourceSets {
    integration {
        compileClasspath += sourceSets.main.output
        runtimeClasspath += sourceSets.main.output
    }
}
tasks.register(&quot;integrationBootJar&quot;, BootJar) {
    description = &quot;Assembles an executable JAR archive to be used for integration tests of other projects containing the main classes, their dependencies, and any other integrationImplementation or integrationRuntimeOnly dependencies.&quot;
    group = 'build' 
    classpath = sourceSets.main.runtimeClasspath.plus(sourceSets[&quot;integration&quot;].runtimeClasspath)
    mainClass.set(&quot;${jarMainClass}&quot;) // TODO can pull from bootJarMainClassName or bootRunMainClassName like bootJar?
    archiveClassifier.set(&quot;integration&quot;)
    shouldRunAfter bootJar
}
assemble.dependsOn integrationBootJar
</code></pre>
",https://stackoverflow.com/questions/71387297/generating-multiple-jars-for-spring-boot-with-gradle,"['spring-boot', 'gradle', 'jar']",1505,True,2,2
Google Sign In Integration Testing Flutter,"<p>I have implemented Google Sign In using Firebase, but somehow while performing the Integration Testing, I am not able to click the different email address options when the default dialog box opens to sign in. Is there any way I can click on the email given in the dialog box and navigate to the next screen.
The test for finding the login button passess successfully, but the testing app closes once the test has passed not clicking any of the given email addressess on the dialog box.
Attaching screen shots of start screen and email dialog box for better understanding.
<a href=""https://i.stack.imgur.com/wnYte.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/wnYte.png"" alt=""enter image description here"" /></a>
<a href=""https://i.stack.imgur.com/tabav.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/tabav.png"" alt=""enter image description here"" /></a>
<a href=""https://i.stack.imgur.com/r5wLd.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/r5wLd.png"" alt=""enter image description here"" /></a></p>
<p>Code</p>
<pre><code>void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();
  group('end-to-end test', () {
    var log = find.byType(LoginButton);

    testWidgets('Login Button Test', (tester) async {
      app.main();
      await tester.pumpAndSettle();
      await tester.tap(log);
      await tester.pumpAndSettle();
    });
  });
}
</code></pre>
",https://stackoverflow.com/questions/74782015/google-sign-in-integration-testing-flutter,"['flutter', 'flutter-test']",93,False,1,0
Express listen is not working and port is taken from env automatically,"<p>After writing all the endpoints I decided to add PORTS and JWT_key to .ENV by using dotenv package all work perfectly fine until I decided to do Integration testing now express.listen is not working and it automatically takes the port from .ENV file and I don't how</p>
<p>this is app.js</p>
<pre><code>require(&quot;express-async-errors&quot;);
const Express = require(&quot;express&quot;);
const app= Express();
const winston = require(&quot;winston&quot;);
require(&quot;./start/logger&quot;)();
require(&quot;./start/routes&quot;)(express);
require(&quot;./start/db&quot;)();
require(&quot;./start/config&quot;)();
require(&quot;dotenv&quot;).config();

const port = process.env.PORT || 5000;
const server = app.listen(port, () =&gt;
  console.log(`listening on port ${port}`)
);

module.exports = server;
</code></pre>
<p>gets nothing on the console</p>
<p>this is .env file</p>
<pre><code>PORT=9000
jwtPrivateKey=&quot;myPrivateKey&quot;
</code></pre>
<p>as soon as I remove the port from .env file the server stop responding</p>
<p>this is my test file</p>
<pre><code>const request = require(&quot;supertest&quot;);

let server;

describe(&quot;/api/genres&quot;, () =&gt; {
  beforeEach(() =&gt; {
    server = require(&quot;../../app&quot;);
  });
  afterEach(() =&gt; {
    server.close();
  });

  describe(&quot;GET /&quot;, () =&gt; {
    it(&quot;should return all genres&quot;, async () =&gt; {
      jest.setTimeout(2000);
      const res = await request(server).get(&quot;/api/genres&quot;);
      expect(res.status).toBe(200);
    });
  });
});
</code></pre>
<p>please guide me through this I did not make a git repo for this otherwise I would have reset it</p>
",https://stackoverflow.com/questions/72392129/express-listen-is-not-working-and-port-is-taken-from-env-automatically,"['javascript', 'node.js', 'express', 'jestjs']",444,True,1,1
How to mock Grpc Client inside GRPC server implementation for integration tests running with Docker,"<p>In order to do E2E integration testing, I am using docker container to spin up the API service.</p>
<pre><code>  datalake_api:
    build:
      context: ../../../
      dockerfile: go.Dockerfile
</code></pre>
<p>Inside API service <code>main.go</code> file, I am initialising another client (lets say C) from another package and passing it to the API server.</p>
<pre><code>client := protos.NewS2ControlPlaneApiServiceClient(conn)

s := service.NewDatalakeApiServiceImpl(client, store)
grpcServer := server.NewGrpcServer(
    server.WithReflection(),
    server.WithUnaryServerInterceptors(
        middleware.DataDogMetrics(dd),
        middleware.ErrorsOnlyGrpcZapLogger(zapLogger),
        middleware.RequestBodyLogger(middleware.ErrorsOnlyDecider()),
    ),
    server.WithRegisteredServices(s.Register),
)
</code></pre>
<p>Currently the API server in docker container is looking for the client at <code>localhost:38644</code>, but its not available.</p>
<p>I dont want to create separate container(s) for C, because it has its dependencies and I will have to create for all then, so I want to mock it in integration tests. Any idea on how can we mock this client?</p>
",https://stackoverflow.com/questions/74282837/how-to-mock-grpc-client-inside-grpc-server-implementation-for-integration-tests,"['docker', 'go', 'mocking', 'integration-testing', 'gomock']",203,False,1,0
How to save entities along with their related entities in spring boot integration testing?,"<p>I have an integration test on a endpoint of creating a user with its related entities. It turns out that the related entities were not persisted with the user entity.</p>
<p>However, it is working fine when running the normal spring boot application. Is it possible to achieve this during testing?</p>
<p>This is the log when running the integration test of the endpoint</p>
<p><a href=""https://i.stack.imgur.com/7bi14.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/7bi14.png"" alt=""This is the log when running the integration test of the endpoint"" /></a></p>
<p>And this is the log when calling from Postman to the normal application</p>
<p><a href=""https://i.stack.imgur.com/Q7DEg.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Q7DEg.png"" alt=""this is the log when calling from Postman to the normal application"" /></a></p>
<p>as you can notice the roles are not inserted to the <code>rel_mi_user__mi_user_role</code> table during integration testing.</p>
<p>The setup source code for the integration test is shown below</p>
<pre><code>@Autowired
private PasswordEncoder passwordEncoder;

@Autowired
private MockMvc mockMvc;

@Autowired
private MiMiUserRepository miMiUserRepository;

private static Logger log = LoggerFactory.getLogger(MiMiUserResourceIT.class);

@Test
@Transactional
void testRegisterBackOfficeUser() throws Exception {
    MiMiUserRegistrationDTO userRegistrationDTO = new MiMiUserRegistrationDTO();
    userRegistrationDTO.setPassword(&quot;test12345&quot;);
    userRegistrationDTO.setEmail(&quot;john@gmail.com&quot;);
    userRegistrationDTO.setContactNo(&quot;0188991122&quot;);
    userRegistrationDTO.setUserRoles(List.of(&quot;BACKOFFICE&quot;));
    MiMiUserProfileRegistrationDTO profile = new MiMiUserProfileRegistrationDTO();
    profile.setSalutation(&quot;Mr&quot;);
    profile.setFirstName(&quot;John&quot;);
    profile.setLastName(&quot;Lee&quot;);
    userRegistrationDTO.setProfile(profile);

    mockMvc
        .perform(
            post(&quot;/v1/p/user/register/back-office&quot;)
                .contentType(MediaType.APPLICATION_JSON)
                .content(TestUtil.convertObjectToJsonBytes(userRegistrationDTO))
        )
        .andExpect(status().isCreated());
    MiUser u = miMiUserRepository.findOneWithMiUserRolesByEmailIgnoreCase(userRegistrationDTO.getEmail()).get();
    assertThat(u.getUserStatus()).isEqualTo(UserStatus.NEW);
}
</code></pre>
",https://stackoverflow.com/questions/72216243/how-to-save-entities-along-with-their-related-entities-in-spring-boot-integratio,"['java', 'spring-boot', 'spring-data-jpa', 'integration-testing']",250,False,0,1
Autotest project architecture with a large number of roles,"<p>What are the best practices for organizing an Autotest project (see project below) when you need to test multiple roles, each with their own permissions? And so that testing the entire assembly takes less time. At the moment, authorization under a specific role and opening a browser is performed before each class. Perhaps in this case it is better to use Selenoid, Selenium Grid, or these tools are not used for parallel testing by roles?</p>
<p>Project:</p>
<ul>
<li>Selenium + maven + testng + java</li>
<li>Integration testing</li>
<li>800 autotests</li>
<li>10 roles with their own permissions</li>
<li>Parallel running of tests</li>
</ul>
<p><strong>public class BaseTest:</strong></p>
<pre><code>    protected WebDriver driver;

    @Parameters({&quot;login&quot;})
    @BeforeClass (alwaysRun = true)
    public void setUpMain(final String login) throws IOException{
        driverPath = &quot;src/test/resources/chromedriver.exe&quot;;
        System.setProperty(&quot;webdriver.chrome.driver&quot;, driverPath);
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10L, SECONDS);
        driver.get(System.getProperty(&quot;studio_url&quot;));
        auth(login);
    }
</code></pre>
<p><strong>StudioTests.xml:</strong></p>
<pre><code>&lt;!DOCTYPE suite SYSTEM &quot;http://testng.org/testng-1.0.dtd&quot; &gt; 
&lt;suite name=&quot;Studio Tests&quot; verbose=&quot;1&quot; parallel=&quot;tests&quot; thread-count=&quot;10&quot;&gt;
    &lt;parameter name=&quot;browser&quot; value=&quot;chrome&quot;/&gt;

    &lt;test name=&quot;role_1&quot;&gt;
        &lt;parameter name=&quot;login&quot; value=&quot;login_1&quot;/&gt;
        &lt;classes&gt;
            &lt;class name=&quot;TestClass_1&quot;/&gt;
            &lt;class name=&quot;TestClass_2&quot;/&gt;
        &lt;/classes&gt;
    &lt;/test&gt;
...
...
    &lt;test name=&quot;role_10&quot;&gt;
        &lt;parameter name=&quot;login&quot; value=&quot;login_10&quot;/&gt;
        &lt;classes&gt;
            &lt;class name=&quot;TestClass_19&quot;/&gt;
            &lt;class name=&quot;TestClass_20&quot;/&gt;
        &lt;/classes&gt;
    &lt;/test&gt; 
</code></pre>
",https://stackoverflow.com/questions/72882170/autotest-project-architecture-with-a-large-number-of-roles,"['java', 'selenium', 'selenium-webdriver', 'selenium-grid', 'selenoid']",35,False,0,0
.Net Framework 4.6.1 MVC integration testing,"<p>I am having a hard time trying to find sources of how can I run Integration Tests on my old Net Framework 4.6.1 MVC application. I tried a lot of guides I found, but none of them works for one reason or another.</p>
<p>My application is way to big to upgrade it to Net 6, which would make this testing much easier. I tried running OWIN TestServer, but it always results in 404 errors.</p>
<p>So I would like to know, how to approach integration testing on a old mvc? Am I following the right path searching for a solution with OWIN TestServer? Anything else I could try? Thought of Selenium too, but couldnt get it to start a fake server just to run the tests automatically, I needs a command to initialize my app on IIS, and we need the tests to run automatically through azure CI pipeline.</p>
<p>My app is very old so I tried removing Global.asax and using only the owin pipeline through Startup.cs, but it showed an error message &quot;No HTTP resource was found that matches the request uri&quot;, tried many fixes for Route configuration and such, no success. Tried running OWIN TestServer with both global.asax and startup.cs on the solution but did not work, tried Selenium too but it does not start a fake server automatically, preferably in memory just like the most recent versions of TestServer for net core+.</p>
<p>Tried also following this: <a href=""https://www.strathweb.com/2013/12/owin-memory-integration-testing/"" rel=""nofollow noreferrer"">https://www.strathweb.com/2013/12/owin-memory-integration-testing/</a></p>
",https://stackoverflow.com/questions/74522848/net-framework-4-6-1-mvc-integration-testing,"['c#', 'selenium', 'integration-testing', 'owin', 'testserver']",266,True,0,1
How to test system back button tap in Flutter integration test,"<p>I want to test system back button press in my flutter integration test.</p>
<p>Child screen is presented as model view and there is a close button 'X' to dismiss the screen.
I can already detect the 'X' button tap and test the go back scenario.
2nd test scenario, I want to simulate the system back button tap. I have tried below script, but seems not working</p>
<pre><code>await Process.run(
  'adb', 
  &lt;String&gt;['shell', 'input', 'keyevent', 'KEYCODE_BACK'], 
  runInShell: true,
);
</code></pre>
<p>I also tried some other ways mentioned here <a href=""https://stackoverflow.com/questions/59044829/flutter-integration-testing-how-to-go-back-to-previous-screen-when-no-back-butt"">Flutter Integration Testing- How to go back to previous screen when no back button available on screen</a></p>
<p>Nothing is working for me. If anyone has done this, please share the solution.
My flutter version <code>Flutter 2.10.3</code></p>
",https://stackoverflow.com/questions/71507125/how-to-test-system-back-button-tap-in-flutter-integration-test,"['flutter', 'dart', 'flutter-test']",1105,False,2,1
Unable to Stop Testcontainers Container in .NET Using MSTest,"<p>I'm using the dotnet <code>Testcontainers</code> library to spin up a SQL Server database in Docker for integration testing. I'm using the MSTest framework.</p>
<p>My idea is to run a <code>TestInitialize</code> where the container will start, populate the database and run assertions in the test method, and then run a <code>TestCleanup</code> at the end which will stop the container and dispose of it.</p>
<p>However, the container starts up in Docker and the test hangs (I guess it never ends up running for some reason). Also I'm not 100% sure how to populate the database (I couldn't find any commands for initialising and SQL scripts).</p>
<p>Here is the code:</p>
<pre><code>[TestClass]
public class WithFixtureData
{
    private static readonly TestcontainersContainer _dbContainer =
        new TestcontainersBuilder&lt;TestcontainersContainer&gt;()
        .WithImage(&quot;mcr.microsoft.com/mssql/server&quot;)
        .WithEnvironment(&quot;Database&quot;, &quot;Master&quot;)
        .WithEnvironment(&quot;User Id&quot;, &quot;SA&quot;)
        .WithEnvironment(&quot;Password&quot;, &quot;YourSTRONG!Passw0rd&quot;)
        .WithCleanUp(true)
        .Build();

    [TestInitialize]
    public async Task StartContainer()
    {
        await _dbContainer.StartAsync();
        ///container starts
    }

    [TestMethod]
    public async Task ShouldBringCorrectFixturesBack()
    {
        ///populate db and run assertions. This code never seems to run
    }

    [TestCleanup]
    public async Task DisposeContainer()
    {
        await _dbContainer.StopAsync();
        ///this part of the code never seems to be executed either
    }
}
</code></pre>
",https://stackoverflow.com/questions/74323116/unable-to-stop-testcontainers-container-in-net-using-mstest,"['c#', '.net', 'sql-server', 'mstest', 'testcontainers']",574,True,2,1
Calling an executable from a Spring Application,"<p>I have a Spring application that will need to occasionally produce database backup files. This can be accomplished by calling a MySQL executable called mysqldump. Aside from having to ensure that this executable is available to the application during integration testing and is available in the Docker image the spring app gets built into, are there any obvious reasons why this is a bad design? And if so how would you work around it?</p>
<p>Edit: Just clarifying, I already have implemented this behavior, I’m just curious if anyone sees this as a bad design. That is, having your spring code rely on some external executable.</p>
",https://stackoverflow.com/questions/71489210/calling-an-executable-from-a-spring-application,"['java', 'mysql', 'spring', 'design-patterns']",43,True,1,1
Flutter Widget Testing and Integration Testing,"<p>I have a small to mid sized application having several individual components (eg:- primary button) and several screens (eg:- login screen) where screens are a composition of these individual components and other flutter built in widgets.</p>
<p>Should I be writing widget tests for individual components to check edge cases like handling long texts and overflow issues on smaller or larger devices or write widget tests for entire screens? Here I'll only be testing the cosmetic behaviour of the application screens or widgets?</p>
<p>As for integration testing, I'm assuming it would test the entire functionality of the app, i.e. the screens using blocs (PS: I'm using flutter bloc and redux in conjunction)</p>
",https://stackoverflow.com/questions/73559110/flutter-widget-testing-and-integration-testing,"['flutter', 'testing', 'integration-testing', 'widget-test-flutter']",56,True,0,1
Access different google-service.json in androidTest,"<p>I am trying to perform <strong>integration testing</strong>. For this I have created two <strong>Firebase projects</strong> - one for <strong>production</strong>, another one for <strong>testing</strong>. Now I have this <strong>structure</strong>:</p>
<pre><code>app/
    google-services.json
    src/androidTest/java/google-services.json
    src/debug[main]/java/google-services.json/
    src/main/java/.../
    test[unitTest]/java/.../
</code></pre>
<p>And my specified <strong>build types</strong>:</p>
<pre><code>buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }

    debug {
        debuggable = true
    }
}
</code></pre>
<p>When I run my <strong>test</strong>, which is in <strong>androidTest</strong> directory:</p>
<pre><code>@Test
fun userSensorsAreVisible() {
    // write specific data in Firebase Realtime Database

    val navController = TestNavHostController(ApplicationProvider.getApplicationContext())
    UiThreadStatement.runOnUiThread { navController.setGraph(R.navigation.nav_graph) }

    launchFragmentInHiltContainer&lt;SensorsFragment&gt;(navHostController = navController)

    // assert that data received from DB is shown in SensorsFragment

    Thread.sleep(10000)
}
</code></pre>
<p>The app continues to use <strong>google-services.json</strong>, which is provided in my <strong>src/main</strong> folder (<strong>production</strong>), even though in the below links it's stated that <code>By default, all tests run against the debug build type.</code></p>
<p>I did follow <a href=""https://developer.android.com/studio/build/build-variants"" rel=""nofollow noreferrer"">https://developer.android.com/studio/build/build-variants</a> and <a href=""https://firebase.google.com/docs/projects/multiprojects"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/projects/multiprojects</a>.</p>
<p>How to make my test classes in the <strong>androidTest</strong> use a different <strong>google-services.json</strong> file, which is in <strong>src/androidTest/java/google-services.json</strong>? Thank you.</p>
",https://stackoverflow.com/questions/73919986/access-different-google-service-json-in-androidtest,"['android', 'firebase', 'firebase-realtime-database', 'android-testing', 'android-build-type']",65,False,0,0
How to add AntiForgeryToken Or __RequestVerificationToken in integration tests?,"<p>I am writing a test script in <strong>C#</strong> using <strong>NUnit framework</strong> where i send a <strong>httprequestmeassage</strong> to a <em>uri</em> to <strong>GET</strong> the <strong>__RequestVerificationToken</strong> in response. I wanted to know, how can i add that <strong>__RequestVerificationToken</strong> in the <strong>json</strong> and send it with a <strong>POST</strong> request. <strong>Do i need to deserialize the response and then add the __RequestVerificationToken or can i directly do it from the response object of HttpResponseMessage type?</strong> <em>I am fairly new to C# and integration testing. i would really appreciate it if the answers would be simplified to the core.</em> <strong>Thank You So Much!</strong>
This is what i have come up with up until now:</p>
<pre><code>[Test]
public void DoLogin()
        {
            string uri = &quot;/account/login&quot;;
            AuthenticationRequest authenticationRequest = new AuthenticationRequest
            {
                Email = email,
                Password = password,
                ServiceType= ServiceType
            };

            HttpClient httpClient = new HttpClient { BaseAddress = new Uri(Consts.APIBaseURL) };
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));
            Task&lt;HttpResponseMessage&gt; responseResult = httpClient.GetAsync(uri);
            HttpResponseMessage httpResponseMessage = responseResult.Result;
            Console.WriteLine(httpResponseMessage.ToString());


            string jsonString = JsonConvert.SerializeObject(
                authenticationRequest,
                Formatting.Indented,
                new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });

            HttpRequestMessage httpRequest = new HttpRequestMessage
            {
                RequestUri = new Uri(uri, UriKind.Relative),
                Method = HttpMethod.Post,
                Content = new StringContent(jsonString, Encoding.UTF8, &quot;application/json&quot;)
            };

            //response message
            Task &lt; HttpResponseMessage &gt; response = httpClient.SendAsync(httpRequest);
            HttpResponseMessage httpResponseMessage = response.Result;
            Console.WriteLine(httpResponseMessage);

            //response content data
            HttpContent httpContent = httpResponseMessage.Content;
            Task &lt;string&gt; contentData = httpContent.ReadAsStringAsync();
            string data = contentData.Result;
            Console.WriteLine(&quot;Content Data: \n&quot; + data);

        }
</code></pre>
",https://stackoverflow.com/questions/73858808/how-to-add-antiforgerytoken-or-requestverificationtoken-in-integration-tests,"['c#', 'nunit', 'integration-testing', 'httpclient', 'antiforgerytoken']",98,False,0,0
How to observe the event that a VM has booted?,"<p>I have a bare <code>qemu</code> or <code>kvm</code> virtual machine and would like to observe or wait for the event that the virtual machine has booted in a reliable way.</p>
<p>This is a generic question that may not have a generic answer. If it helps you may assume a subset of the following:</p>
<ul>
<li>The VM is running Debian GNU/Linux.</li>
<li>The actual question is whether the contained ssh server is reachable. It is exported via user networking and a <code>hostfwd</code>.</li>
</ul>
<p>Remarks:</p>
<ul>
<li>reliable means that it is suitable for continous integration testing. It should fail in less than 0.1% of cases.</li>
<li>Running <code>ssh -o ConnectionAttempts=30</code> sometimes produces a failure even though ssh would work afterwards.</li>
</ul>
",https://stackoverflow.com/questions/74938693/how-to-observe-the-event-that-a-vm-has-booted,"['qemu', 'kvm']",22,False,0,0
Replace OAuth2 client provder properties in Spring Boot for testing,"<p>Our Spring Boot application acts as an OAuth2 client and, by default, contacts the identity provider's (here: Keycloak) endpoint for its &quot;OAuth Well-Known Configuration Information&quot; configured by this Spring property:</p>
<p><code>spring.security.oauth2.client.provider.keycloak.issuer-uri</code></p>
<p>The problem is, that any <code>@SpringBootTest</code> then also attempts to connect to such a server which fails immediately. So, for integration testing, I'd like to replace the above <code>issuer-uri</code> with the propeties <code>jwk-set-uri</code>, <code>authorization-uri</code> and <code>token-uri</code> which don't prevent the application from starting.</p>
<p>So, I created the following <code>application.yml</code> which does its job but I think it's not very obvious for other team members what happens here.</p>
<pre class=""lang-yaml prettyprint-override""><code>spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            provider: keycloak
            client-id: ${app.authentication.client-id}
            client-secret: ${app.authentication.client-secret}
            authorization-grant-type: authorization_code
            redirect-uri: &quot;{baseUrl}/login/oauth2/code/keycloak&quot;
            scope: openid
        provider:
          keycloak:
            user-name-attribute: preferred_username

---
spring:
  config:
    activate:
      on-profile: default
  security:
    oauth2:
      client:
        provider:
          keycloak:
            issuer-uri: ${app.authentication.server-url}

---
spring:
  config:
    activate:
      on-profile: integration-test
  security:
    oauth2:
      client:
        provider:
          keycloak:
            jwk-set-uri: ${app.authentication.server-url}
            authorizationUri: ${app.authentication.server-url}
            tokenUri: ${app.authentication.server-url}
</code></pre>
<p>Is there soem other apporach how to diable the <code>issuer-uri</code> and replace it by the three above properties when testing?</p>
",https://stackoverflow.com/questions/72280016/replace-oauth2-client-provder-properties-in-spring-boot-for-testing,"['spring', 'spring-boot', 'spring-security']",437,False,0,0
Should I mock APIs in end-to-end testing?,"<p>When you are doing e2e tests for your application, you want to test the whole application, not some portions of it like unit tests or integration testing.</p>
<p>But in some situations, people do mock APIs.<br>
For example, when you have a massive microservice as your back-end, which makes your e2e tests very slow, or beside your own API, you rely on other third-party APIs, which makes your e2e tests fail occasionally.<br>
So you only want to make sure that your front-end application works well, what should you do?</p>
<p>In my company, we have a massive system with a really heavy database which makes e2e testing very ineffective. Is it right to mock APIs in such a scenario?</p>
",https://stackoverflow.com/questions/71969081/should-i-mock-apis-in-end-to-end-testing,"['testing', 'automated-tests', 'end-to-end']",4261,True,7,1
Framework for E2E tests akka-http,"<p>Asking this question because I am trying to figure out the framework which is most widely used for integration testing akka-http. How to automate those tests in Jenkins? Probably a rookie question but ideas are appreciated. Thanks</p>
<p>EDIT from comments:
What have you tried so far? So far I tried implementing 1. Jest 2. Using Testkit, IntegrationPatience Where are you stuck? Both the approaches doesn't look like standard to me and since I have app deployed in multiple locations, I am trying to understand if there is any framework out there which I can use to setup. The app is deployed to multiple data centers which may have different environment variables.</p>
",https://stackoverflow.com/questions/70684331/framework-for-e2e-tests-akka-http,"['akka', 'integration-testing', 'akka-http']",87,True,1,1
not-null property references error when Adding @Column(nullable = false),"<p>I have a springboot project with two tables/entities having one-to-many relationship below</p>
<pre><code>@Getter
@Setter
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {&quot;invoiceItemId&quot;}))
public class InvoiceItem {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long invoiceItemId;
    @Column(nullable =  false)
    private int sn;
    @ManyToOne
    @JoinColumn(name = &quot;invoiceId&quot;, insertable = false, updatable = false, foreignKey = @ForeignKey(name=&quot;FK_invoice_item&quot;))
    private Invoice invoice;
    @ManyToOne
    @JoinColumn(name = &quot;productId&quot;, foreignKey = @ForeignKey(name=&quot;FK_product&quot;))
    private Product product;
    @Column(nullable = false)
    private Double quantity;
//  @Column(nullable = false)
    private Double price;
//  @Column(nullable =  false)
    private Double totalAmount; //add validation later

}
</code></pre>
<pre><code>@Getter
@Setter
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {&quot;invoiceId&quot;}))
public class Invoice {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long invoiceId; //set format
    @Column(nullable = false, unique = true)
    private String invoiceNo;
    @Column(nullable = false)
    private String customerName;
    private String customerAddress;
    @Column(nullable = false)
    private String contactNo; //set format
    @ManyToOne
    @JoinColumn(name= &quot;userId&quot;, nullable = false, foreignKey = @ForeignKey(name = &quot;FK_invoice_sales&quot;))
    private User salesPerson;
    @Column(nullable = false, unique = true)
    private String poNumber;
    @Temporal(TemporalType.TIMESTAMP)
    @Column(nullable = false)
    private Date purchaseDate;
    @Column(nullable = false)
    private String paymentType;
    private String paymentTerm;
    @Column(nullable = false)
    private String tinNumber;
    @Temporal(TemporalType.DATE)
    @Column(nullable = false)
    private Date dueDate;
    @OneToMany(cascade = CascadeType.PERSIST)
    @JoinColumn(name= &quot;invoiceId&quot;, nullable = false)
    private List&lt;InvoiceItem&gt; invoiceItems;
    private Double totalAmount;
    
    
}
</code></pre>
<p>I am using <code>spring-data-jpa</code> for this project to handle the database transaction. Initially, I marked the fields in <code>InvoiceItem</code> like <code>quantity</code> as non-nullable. When running my Unit Test, I don't face any issues at all. I have tested my unit test using H2 and MySQL and test passed on both. However, when I am doing integration testing, I always get below error:</p>
<pre><code>not-null property references a null or transient value : com.edar.sales.be.entity.InvoiceItem.quantity
</code></pre>
<p>This error is thrown for all the fields in the <code>InvoiceItem</code> with <code>@Column(nullable = false)</code> annotation. What weirded me out is that I only encounter this issue when calling the API endpoint. Also, when I removed the <code>@Column(nullable = false)</code> I don't face this error</p>
",https://stackoverflow.com/questions/74080305/not-null-property-references-error-when-adding-columnnullable-false,"['java', 'spring-boot', 'spring-data-jpa']",13,False,0,0
.NET 6 TestServer cannot resolve Controller,"<p>I have a .NET 6 minimal API, and I'm using <code>WebApplicationFactory&lt;T&gt;</code> for integration testing. Usually, I have something roughly like this in my tests:</p>
<pre><code>using TestServer server = new WebApplicationFactory&lt;Program&gt;().Server;
using HttpClient client = server.CreateClient();
// ... do stuff with the client
</code></pre>
<p>However, I would like to also test my controller directly (primarily so that I can use the debugger within the controller itself during the tests), after getting an instance of it with all the DI goodness baked in from the factory, but it throws an exception when I try to resolve my controller, like this:</p>
<pre><code>using TestServer server = new WebApplicationFactory&lt;Program&gt;().Server;

// throws InvalidOperationException : No service for type 'MyController' has been registered.
var controller = server.Services.GetRequiredService&lt;MyController&gt;();
</code></pre>
<p>Why is this happening, and is there a way to fix it?</p>
<h2>EDIT:</h2>
<p>Of course, I have a line in <code>Program.cs</code> like this:</p>
<pre><code>builder.Services.AddControllers();
</code></pre>
<p>...and my API starts up correctly and the controller in question works in this case.</p>
",https://stackoverflow.com/questions/72560692/net-6-testserver-cannot-resolve-controller,"['.net', 'testing', '.net-6.0']",234,True,0,1
Passing claims into HandleAuthenticateAsync for integration testing,"<p>While following Microsoft's ASP.NET Core guide for integration testing authentication, I have the following test built for Authentication:</p>
<pre><code>[Fact]
public async Task Get_SecurePageIsReturnedForAnAuthenticatedUser()
{
    // Arrange
    var client = _factory.WithWebHostBuilder(builder =&gt;
        {
            builder.ConfigureTestServices(services =&gt;
            {
                services.AddAuthentication(&quot;Test&quot;)
                    .AddScheme&lt;AuthenticationSchemeOptions, TestAuthHandler&gt;(
                        &quot;Test&quot;, options =&gt; {});
            });
        })
        .CreateClient(new WebApplicationFactoryClientOptions
        {
            AllowAutoRedirect = false,
        });

    client.DefaultRequestHeaders.Authorization = 
        new AuthenticationHeaderValue(&quot;Test&quot;);

    //Act
    var response = await client.GetAsync(&quot;/SecurePage&quot;);

    // Assert
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
</code></pre>
<p>What I want to do, is use the [Theory] option instead of [Fact] to test multiple Authentications so it will look like this:</p>
<pre><code>[Theory]
[InlineData(&quot;TestAuth1&quot;,&quot;12345&quot;)]
[InlineData(&quot;TestAuth2&quot;,&quot;23456&quot;)]
[InlineData(&quot;TestAuth3&quot;,&quot;34567&quot;)]
public async Task Get_SecurePageIsReturnedForAnAuthenticatedUser(string claim, string claimsIdentity)
{
   var claim = new Claim(claim, claimsIdentity);

.
.
.
</code></pre>
<p>However I'm not sure how to pass claim to TestAuthHandler through AddScheme&lt;AuthenticationSchemeOptions, TestAuthHandler&gt;</p>
<p>Here is the given TestAuthHandler</p>
<pre><code>public class TestAuthHandler : AuthenticationHandler&lt;AuthenticationSchemeOptions&gt;
{
    public TestAuthHandler(IOptionsMonitor&lt;AuthenticationSchemeOptions&gt; options, 
        ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
        : base(options, logger, encoder, clock)
    {
    }

    protected override Task&lt;AuthenticateResult&gt; HandleAuthenticateAsync()
    {
        var claims = new[] { new Claim(ClaimTypes.Name, &quot;Test user&quot;) };
        var identity = new ClaimsIdentity(claims, &quot;Test&quot;);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, &quot;Test&quot;);

        var result = AuthenticateResult.Success(ticket);

        return Task.FromResult(result);
    }
}
</code></pre>
<p>I would like to replace the claims variable in HandleAuthenticaAsync() with the claim passed into Get_SecurePageIsReturnedForAnAuthenticatedUser(Claim claim)</p>
<p>As a note they do have to be tested individually since my current authentication will pass as long as one correct authentication exists in the HandleAuthenticateAsync claims variable.</p>
<p>Thank you for any help provided.</p>
",https://stackoverflow.com/questions/73830338/passing-claims-into-handleauthenticateasync-for-integration-testing,"['c#', 'asp.net-core', 'integration-testing']",198,False,0,1
"In a dotnet 5 web api project, how do I get the instance of a singleton service in a test method?","<p>I'm integration testing my asp.net 5 web apis. In my test methods I want to get a reference to the instance a of faked service so I can customise the service's behaviour for my tests.</p>
<p>In the app, the service is scoped as singleton.</p>
<pre><code>//in ConfigureServices in Startup.cs    
services.AddSingleton&lt;IYbNewProjectsService, YbNewProjectsService&gt;();
</code></pre>
<p>In my test project, I set up my client and server in my TestFixture class, and save a reference to the ServiceProvider, returned to me by the services.BuildServiceProvider() call...</p>
<pre><code>private void SetupClient()
{
    Client = Factory.WithWebHostBuilder(builder =&gt;
    {
        builder.ConfigureTestServices(services =&gt;
        {
            services.Remove&lt;IYbNewProjectsService&gt;();
            services.AddSingleton&lt;IYbNewProjectsService, FakeYbNewProjetsService&gt;();
        });

        builder.ConfigureServices(services =&gt;
        {
            ServiceProvider = services.BuildServiceProvider();
        });
    })
    .CreateClient(new WebApplicationFactoryClientOptions
    {
        AllowAutoRedirect = false
    });
}
</code></pre>
<p>I know it's working, because in my tests, when I do...</p>
<pre><code>// ServiceProvider is inherited from TestFixture, so it's the same as above.
var fakeYbService = (FakeYbNewProjectsService)ServiceProvider.GetService(typeof(IYbNewProjectsService));
fakeYbService.InjectedResponse = @&quot;[{{&quot;&quot;idProjet&quot;&quot;:1883557,&quot;&quot;dateDApplication&quot;&quot;:...
var response = await Client.GetAsync(&quot;/api/yb-new-projects&quot;);
</code></pre>
<p>...I get my faked service. Trouble is, when I call <code>Client.GetAsync()</code>, the TestServer is using a clean instance of the same faked service, without my <code>InjectedResponse</code>. This is meant to be a singleton, so why are there two of them?</p>
",https://stackoverflow.com/questions/71109644/in-a-dotnet-5-web-api-project-how-do-i-get-the-instance-of-a-singleton-service,"['c#', 'asp.net-core', 'asp.net-web-api']",492,True,2,1
Using WebApplicationFactory to do E2E testing with .Net 6 (minimal api),"<p>Im trying to get E2E/UI testing (selenium, playwright) to work with my unit testing framework.</p>
<p>The basic idea it to use MSTest and the WebApplicationFactory to spin up a &quot;real server&quot; from within my unit tests. The reason for doing this would be to simply avoid having to deploy/release my application for testing (I guess this could be done by using containers etc, sadly.. Im not allowed to use containers). Im also thinking that doing it this wasy would be a &quot;neat&quot; way of mocking any code that calls external services, and be able to create multiple tests with different scenarios for those external calls.</p>
<p>I have searched the web for a way of doing this, but all I can find are posts about how to do this in previous .Net versions (2.1-5), but since .Net 6 the &quot;startup ceremonial&quot; code has changed and the standard way is now to use the minimal API.</p>
<p>Here is a blog post from Scott.H where he is basically doing exactly what Im planing to do, but with .Net 2.1: <a href=""https://www.hanselman.com/blog/real-browser-integration-testing-with-selenium-standalone-chrome-and-aspnet-core-21"" rel=""nofollow noreferrer"">https://www.hanselman.com/blog/real-browser-integration-testing-with-selenium-standalone-chrome-and-aspnet-core-21</a></p>
<p>What I have done so far is creating a custom class that inherits from WebApplicationFactory.</p>
<p>basically:</p>
<pre><code>class MyAppFactory : WebApplicationFactory&lt;Program&gt; {

}
</code></pre>
<p>And I can use that perfectly fine for integration testing. However.. the server thats initialized when using that class does not accept http-calls, so I cant reach that using a web browser, and neither can selenium.</p>
<p>I tried to follow Scotts blog post. But for some reason the:</p>
<pre><code>protected override TestServer CreateServer(IWebHostBuilder builder)
</code></pre>
<p>Is never called.. (not sure if that has with minimal APIs and .Net 6 to do).</p>
<p>Has anyone managed to use the WebApplicationFactory and .Net 6 Minimal API to spin up an &quot;actual server&quot; in memory that accepts http-calls?</p>
",https://stackoverflow.com/questions/71541576/using-webapplicationfactory-to-do-e2e-testing-with-net-6-minimal-api,"['testing', '.net-6.0']",1645,True,2,2
Unit and Integration testing of custom Kong plugin using busted,"<p>I have been trying to explore unit and integration testing frameworks for custom kong plugins. I'm very new to Lua and I started exploring busted and I was <strong>not</strong> able to successfully run tests on the plugin.</p>
<p>Here are the steps I followed -</p>
<ol>
<li>I ran a Docker container of kong version 2.5.0</li>
<li>Inside the kong docker container I cloned <a href=""https://github.com/Kong/kong"" rel=""nofollow noreferrer"">https://github.com/Kong/kong</a> repo</li>
<li>when I try to run some tests from the above repository's spec folder i get error as <code>./kong/tools/utils.lua:37: attempt to index global 'ngx' (a nil value)</code></li>
</ol>
<p>I'm following <a href=""https://docs.konghq.com/gateway/latest/plugin-development/tests/"" rel=""nofollow noreferrer"">this</a> documentation, to understand writing and running unit and integrtion tests in kong, but I'm having hard time setting up the environment.</p>
<p>Any help in setting up a docker container to run unit and integration tests in kong using busted is appreciated.</p>
",https://stackoverflow.com/questions/74068456/unit-and-integration-testing-of-custom-kong-plugin-using-busted,"['lua', 'kong', 'kong-plugin', 'lua-busted']",325,False,1,0
How to grant photos permission for flutter integration test in iOS simlulator?,"<p>Please help to identify the problem about permission to access photo library in iOS simulator (iOS 15.0) with flutter test (integration_test).</p>
<p>I'm trying to use flutter integration testing with a mobile app required permission to access photo. ex change user profile picture.</p>
<p>try to use command line as below to grant the permission</p>
<p><code>xcrun simctl privacy booted grant photos  &lt;app bundle id&gt;</code></p>
<p>But when return to access photos in the app,it always asks permission to access photos library. (xcrun for grant all access is not working)</p>
<p>Anyway, when using revoke</p>
<p><code>xcrun simctl privacy booted revoke photos  &lt;app bundle id&gt;</code></p>
<p>For this time, the app displays no permission to access photos library correctly. (xcrun is working as expected)</p>
<p>How to grant permission to access photo library,no permission asking when runing flutter test script?</p>
<p>Thank you very much.</p>
",https://stackoverflow.com/questions/73384666/how-to-grant-photos-permission-for-flutter-integration-test-in-ios-simlulator,"['flutter', 'ios-simulator', 'flutter-test', 'user-permissions']",626,False,0,1
How to use custom spring library for integration testing,"<p>I have a spring library which I use for spring boot applications. This library is an API client that can make HTTP requests on known API endpoints. This library has several packages and configuration classes that read the configuration values from the application.yaml file of the spring-boot application where this library is used at. i.e. API URL, API login credentials ...etc</p>
<p>I want to use this library for some integration testing. My integration test is not a spring-boot application therefore, I want to provide the configuration from a separate .property file or .yaml file. How do I achieve that? I want to run it as a junit5 test.</p>
<pre><code>//@SpringBootTest
@TestPropertySource(locations = &quot;classpath:api-config.yaml&quot;)
@EnableConfigurationProperties
@ExtendWith(SpringExtension.class)
public class APITest {

// this property is from the above library
@Autowired
private ApiClient apiClient;

@Test
  void testSomeAPIResponse() {
    String key = &quot;some-key&quot;;
    SomethingDTO somethingDTO = apiClient.getSomethingBykey(key);
    assertNotNull(somethingDTO);
  }
}
</code></pre>
<p>in the above code, api-config.yaml is the file where I have configuration values for APIClient.</p>
",https://stackoverflow.com/questions/73103924/how-to-use-custom-spring-library-for-integration-testing,"['java', 'spring', 'spring-test']",118,False,0,0
How do I test a Spring Integration Transformer?,"<p>I am new to Spring Integration (been using Spring before). I have made a transformer like this:</p>
<pre><code>@Transformer(inputChannel = &quot;signering&quot;, outputChannel = &quot;validering&quot;)
</code></pre>
<p>and now I want to test it. So I have done like this in my test:</p>
<pre><code>@Autowired
MessageChannel signering;

@Autowired
PollableChannel validering;
</code></pre>
<p>When I invoke the transformer in my test it seems to work</p>
<pre><code>signering.send(msg.build());
</code></pre>
<p>but I am unable to intercept the outgoing message (which is what I want). Instead it seems to go to the real bean validering and onwards. I have added a .receive call after the send call, but it gets nothing. And the Internet is not really helpful right now. What examples I find for Spring Integration testing seems to be using XML context, and they are pretty old at that. What is the current way of doing this kind of testing?</p>
",https://stackoverflow.com/questions/73478051/how-do-i-test-a-spring-integration-transformer,"['java', 'spring', 'spring-boot', 'spring-integration']",81,False,0,1
Cannot create index for MongoDB replica set: ReplicaSetNoPrimary,"<p>I am writing integration testing for my Go program. When I try to initiate my MongoDB (with Docker) running in replica set, it raise error:</p>
<pre class=""lang-js prettyprint-override""><code>server selection error: server selection timeout, current topology:

{
    Type: ReplicaSetNoPrimary,
    Servers: [
        {
            Addr: b3ec1125321a:27017,
            Type: Unknown,
            Last error: connection() error occurred during connection handshake: dial tcp: lookup b3ec1125321a on 10.225.109.87:53: no such host
        },
    ]
}
</code></pre>
<p>So I try to create a minimal runnable code as below with comment:</p>
<pre class=""lang-golang prettyprint-override""><code>package main

import (
    &quot;bytes&quot;
    &quot;context&quot;
    &quot;errors&quot;
    &quot;fmt&quot;
    &quot;net&quot;
    &quot;os/exec&quot;
    &quot;time&quot;

    &quot;go.mongodb.org/mongo-driver/bson&quot;
    &quot;go.mongodb.org/mongo-driver/mongo&quot;
    &quot;go.mongodb.org/mongo-driver/mongo/options&quot;
)

// getDockerPath returns the path for docker.
func getDockerPath() (string, error) {
    return exec.LookPath(&quot;docker&quot;)
}

// getPort returns a useable port. (should use it as soon as you can)
func getPort() (int, error) {
    l, err := net.Listen(&quot;tcp&quot;, &quot;:0&quot;)
    if err != nil {
        return 0, fmt.Errorf(&quot;listen to port 0: %w&quot;, err)
    }
    defer l.Close()
    return l.Addr().(*net.TCPAddr).Port, nil
}

// runMongo will run a MongoDB container in docker.
func runMongo(ctx context.Context) error {
    dockerPath, err := getDockerPath()
    if err != nil {
        return fmt.Errorf(&quot;get docker path: %w&quot;, err)
    }
    mongoPort, err := getPort()
    if err != nil {
        return fmt.Errorf(&quot;get mongo port: %w&quot;, err)
    }
    mongoURL := fmt.Sprintf(&quot;mongodb://127.0.0.1:%d&quot;, mongoPort)
    fmt.Printf(&quot;Starting a mongoDB listening on %s\n\n&quot;, mongoURL)

    // Run MongoDB - build command and run.
    args := []string{
        &quot;run&quot;, &quot;-d&quot;, &quot;-p&quot;, fmt.Sprintf(&quot;%d:27017&quot;, mongoPort),
        &quot;mongo&quot;,
        &quot;mongod&quot;, &quot;--replSet=rs0&quot;,
    }
    startCmd := exec.CommandContext(ctx, dockerPath, args...)
    stdout := &amp;bytes.Buffer{}
    startCmd.Stdout = stdout
    if err := startCmd.Run(); err != nil {
        return fmt.Errorf(&quot;run MongoDB container by docker: %w&quot;, err)
    }

    // Get the Docker container name.
    containerName, err := stdout.ReadString('\n')
    for err != nil {
        containerName, err = stdout.ReadString('\n')
    }
    containerName = containerName[:6]

    // **********************************************************************
    // NOTICE: When I remove the code below to initiate the MongoDB's Replica
    // Set. And remove the argument `--replSet rs0`, it works.
    // **********************************************************************
    //
    // Initiate Mongo's Replica Set.
    args = []string{
        &quot;exec&quot;, containerName,
        &quot;mongo&quot;, &quot;--eval&quot;, &quot;rs.initiate();&quot;,
    }
    err = errors.New(&quot;in loop&quot;)
    for err != nil {
        &lt;-time.After(1 * time.Second)
        initCmd := exec.CommandContext(ctx, dockerPath, args...)
        fmt.Println(initCmd)
        err = initCmd.Run()
        if err != nil {
            fmt.Println(err)
        }
    }

    // Init MongoDB before use it.
    client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoURL))
    if err != nil {
        return fmt.Errorf(&quot;cannot connect to MongoDB: %w&quot;, err)
    }
    indexName := &quot;Namespace's name's unique index&quot;
    True := true
    index, err := client.Database(&quot;tmp&quot;).Collection(&quot;namespace&quot;).Indexes().CreateOne(ctx, mongo.IndexModel{
        Keys: bson.D{{Key: &quot;name&quot;, Value: 1}},
        Options: &amp;options.IndexOptions{
            Name:   &amp;indexName,
            Unique: &amp;True,
        },
    })
    if err != nil {
        return fmt.Errorf(&quot;create index for namespace: %w&quot;, err)
    }
    fmt.Println(index)

    return nil
}

func main() {
    err := runMongo(context.Background())
    if err != nil {
        fmt.Printf(&quot;Fail to run MongoDB: %v\n&quot;, err)
    }
}
</code></pre>
<p>When I try to run, it throw an error:</p>
<pre><code>$ go run .
Starting a mongoDB listening on mongodb://127.0.0.1:29597

/usr/bin/docker exec b3ec11 mongo --eval rs.initiate();
Fail to run MongoDB: create index for namespace: server selection error: server selection timeout, current topology: { Type: ReplicaSetNoPrimary, Servers: [{ Addr: b3ec1125321a:27017, Type: Unknown, Last error: connection() error occurred during connection handshake: dial tcp: lookup b3ec1125321a on 10.225.109.87:53: no such host }, ] }
</code></pre>
<p>I try to search on Google. But still cannot find a solution.</p>
<hr />
<p><strong>UPDATE</strong>: I can use mongosh to do it without any error:</p>
<pre class=""lang-bash prettyprint-override""><code>$ mongosh mongodb://127.0.0.1:29597
&gt; use tmp
&gt; ns = db.getCollection(&quot;namespace&quot;)
&gt; ns.createIndex({name: 1}, {unique: true, name: &quot;Namespace's name's unique index&quot;})
</code></pre>
<p>And this really worry me a lot - I cannot get why I can use <code>mongosh</code> but not the go-driver of MongoDB.</p>
<p>It tells me that now it is <code>ReplicaSetNoPrimary</code>. But I try to use <code>mongosh</code> to connect it and run <code>rs.isMaster()</code> - it tells me that the only running MongoDB node <strong>IS</strong> the master node.</p>
",https://stackoverflow.com/questions/73511255/cannot-create-index-for-mongodb-replica-set-replicasetnoprimary,"['mongodb', 'docker']",108,True,0,1
Difference between &quot;Kafka for junit&quot; &amp; &quot;spring-kafka-test&quot;,"<p>We are using spring boot application for Kafka.</p>
<p>We want to do unit testing &amp; integration testing for Kafka producer(kafkatemplate) &amp; consumer (EventListner) application.</p>
<p>We explored couple of library for Kafka testing.
#1 Test container/ Kafka container - no access to docker images so we skipped this</p>
<p>#2 MockProducer &amp; MockConsumer not worked with kafkatemplate &amp; Kafkalietner. -- not found good working example for reference. Worked with core KafkaProducer &amp; Kafka consumer interface.</p>
<p>#3 spring-kafka-test - EmbededKafka working as expected:)</p>
<p>#4 Kafka for junit</p>
<p>Anyone used Kafka for junit for Kafka testing?</p>
<p>What are the advantages of Kafka for junit over spring-kafka-test library ?</p>
<p>When to use Kafka for junit library vs spring-kafka-test ?</p>
<p>Advantages &amp; Disadvantage of Kafka for junit ?</p>
<p>Thanks for advance.</p>
",https://stackoverflow.com/questions/73725825/difference-between-kafka-for-junit-spring-kafka-test,"['spring-boot', 'apache-kafka', 'integration-testing', 'junit4', 'spring-kafka-test']",160,False,0,0
How do I parameterize property values for spring boot test,"<p>I am working on an aggregation framework using spring boot, which can be used to aggregate multiple kinds of I/O operations' results. Additionally, it has support for both non-blocking (reactive) &amp; blocking aggregation layer, which is controlled by a property, which is in-turn used for conditional beans. For integration testing, I have been using this setup:</p>
<pre class=""lang-java prettyprint-override""><code>abstract class HttpUpstreamTests {
    // Setup &amp; test logic
}

@SpringBootTest(properties = {
        &quot;aggregation.reactive.enabled=false&quot;,
})
class BlockingAggregationIT extends HttpUpstreamTests {}

@SpringBootTest(properties = {
        &quot;aggregation.reactive.enabled=true&quot;,
})
class NonBlockingAggregationIT extends HttpUpstreamTests {}
</code></pre>
<p>Now I have to add a couple more base classes:</p>
<pre class=""lang-java prettyprint-override""><code>abstract class MongodbUpstreamTests {
    // Setup &amp; test logic
}
abstract class SqlUpstreamTests {
    // Setup &amp; test logic
}
</code></pre>
<p>But of course, I can't make the IT classes extend from multiple abstract classes. One way would be to make all the upstrteam tests parameterized tests, but I can't seem to find a way to use that approach with different values of the property in <code>@SpringBootTest(properties=&quot;aggregation.reactive.enabled=false&quot;)</code>. Is there a way to use different properties as a parameter for parameterized tests?</p>
",https://stackoverflow.com/questions/71480610/how-do-i-parameterize-property-values-for-spring-boot-test,"['java', 'spring-boot', 'testing', 'spring-boot-test', 'parameterized-tests']",454,False,4,0
How to wrap code that uses transcations in a transaction and then rollback?,"<p>I'm setting up my integration testing rig. I'm using the <code>beforeEach</code> and <code>afterEach</code> hooks to wrap every single test in a transaction that rollsback so that the tests don't affect each other. A simplified example might be this:</p>
<pre class=""lang-js prettyprint-override""><code>const { repository } = require(&quot;library&quot;)

describe(&quot;Suite&quot;, function () {
  beforeEach(async function () {
    await knex.raw(&quot;BEGIN&quot;);
  });

  afterEach(async function () {
    await knex.raw(&quot;ROLLBACK&quot;);
  });

  it(&quot;A test&quot;, async function () {
    const user = await repository.createUser()
    user.id.should.equal(1)
  });
});

</code></pre>
<p>This worked fine because I configured knex to use a single DB connection for tests. Hence calling <code>knex.raw(&quot;BEGIN&quot;);</code> created a <em>global</em> transaction.</p>
<p>Now however, the library's repository which I can't control started using transactions internally. I.e. <code>createUser()</code> begins and then <em>commits</em> the created user. This broke my tests as now my <code>afterEach</code> hook doesn't rollback the changes because they were already committed.</p>
<p>Is there a way in Postgres to rollback a transaction that have (already committed) nested transactions?</p>
<p>Or maybe a way to use knex to prevent the repository from starting transactions in the first place? It uses <code>knex.transaction()</code> to create them.</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/74387244/how-to-wrap-code-that-uses-transcations-in-a-transaction-and-then-rollback,"['javascript', 'postgresql', 'knex.js', 'strapi']",542,True,2,2
"Getting column &quot;B&quot; not found, while running the SQL query to create the table in the h2 db in the Springboot application","<p>I am working on a spring-boot application. Where I have to run a set of SQL queries (&quot;written for the MySQL DB&quot;) to create the tables when the application starts. These queries are working fine while connecting the spring-boot application with MySQL DB.</p>
<p>But I wanted to create these tables in the h2-in memory Db (for integration testing), So I configure the application to connect with h2 DB, But while running the SQL queries I am getting the error</p>
<blockquote>
<p>Column &quot;B&quot; not found</p>
</blockquote>
<p>in each query.</p>
<p>Please help me, why I am getting column &quot;B&quot; not found in each query.</p>
<p>Here are my error logs</p>
<pre><code>.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.5.RELEASE)

2022-06-28 06:19:45.179  INFO 18824 --- [           main] com.tools.seed.SeedMain           : Starting SeedMain v1.0.0.ez on -Latitude-3410 with PID 18824 (/home/Documents/SourceCode/server/code/seed-data/target/seed-data-1.0.0.ez.jar started by  abcd in /home/Documents/SourceCode/server/code/seed-data)
2022-06-28 06:19:45.184 DEBUG 18824 --- [           main] com.tools.seed.SeedMain           : Running with Spring Boot v1.3.5.RELEASE, Spring v4.2.6.RELEASE
2022-06-28 06:19:45.184  INFO 18824 --- [           main] com.tools.seed.SeedMain           : The following profiles are active: 
-----&gt; INITIALIZING CONFIGURATION: Tue Jun 28 06:19:53 IST 2022 &lt;-----
-----&gt; Active Profiles: : &lt;-----
2022-06-28 06:19:55.673 DEBUG 18824 --- [           main] c.e.tools.seed.loader.LoaderRegistry     : registered [2147483647] com.tools.seed.loader.DeviceFirmwareVersionLoader
2022-06-28 06:19:55.713  INFO 18824 --- [           main] c.e.p.hibernate.config.HibernateConfig   : Using Hz as Hibernate Cache
2022-06-28 06:21:09.483  INFO 18824 --- [           main] c.e.p.hibernate.config.HibernateConfig   : releaseConnectionAfterTransaction : false
2022-06-28 06:21:12.964 ERROR 18824 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000388: Unsuccessful: create table app_version (id bigint not null auto_increment, created_by varchar(20) not null, created_time datetime not null, lock_id int(11) default 0 not null, modified_by varchar(20) not null, modified_time datetime not null, application_id varchar(50) not null, descriptor longtext, device_type varchar(16), file_size bigint, notes varchar(1024), org_code varchar(25) not null, pinned bit(1) default b'1', rollout_id varchar(25), severity int(2) default 1, status varchar(14) not null, version_code bigint not null, version_name varchar(14) not null, primary key (id)) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE latin1_general_cs 
2022-06-28 06:21:12.966 ERROR 18824 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : Column &quot;B&quot; not found; SQL statement:
create table app_version (id bigint not null auto_increment, created_by varchar(20) not null, created_time datetime not null, lock_id int(11) default 0 not null, modified_by varchar(20) not null, modified_time datetime not null, application_id varchar(50) not null, descriptor longtext, device_type varchar(16), file_size bigint, notes varchar(1024), org_code varchar(25) not null, pinned bit(1) default b'1', rollout_id varchar(25), severity int(2) default 1, status varchar(14) not null, version_code bigint not null, version_name varchar(14) not null, primary key (id)) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE latin1_general_cs  [42122-212]
2022-06-28 06:21:12.978 ERROR 18824 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000388: Unsuccessful: create table bharatqr_provider_config (id bigint not null auto_increment, created_by varchar(20) not null, created_time datetime not null, lock_id int(11) default 0 not null, modified_by varchar(20) not null, modified_time datetime not null, auto_check_status_enabled bit(1) default b'0' not null, auto_check_status_initiation_time integer, auto_check_status_interval_time integer, auto_check_status_type varchar(30), qr_type varchar(15) not null, terminal_type varchar(10) not null, expired_transaction_status varchar(20), generate_batch_number bit(1) default b'0' not null, partial_refund_enabled bit(1) default b'0' not null, processing_hop varchar(15), provider_base_url varchar(255) not null, provider_key varchar(255), provider_name varchar(255) not null, provider_password varchar(255), provider_username varchar(255), status varchar(20), timezone varchar(255), upi_check_status_enabled bit(1) default b'0' not null, primary key (id)) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE latin1_general_cs 
2022-06-28 06:21:12.978 ERROR 18824 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : Column &quot;B&quot; not found; SQL statement:
create table bharatqr_provider_config (id bigint not null auto_increment, created_by varchar(20) not null, created_time datetime not null, lock_id int(11) default 0 not null, modified_by varchar(20) not null, modified_time datetime not null, auto_check_status_enabled bit(1) default b'0' not null, auto_check_status_initiation_time integer, auto_check_status_interval_time integer, auto_check_status_type varchar(30), qr_type varchar(15) not null, terminal_type varchar(10) not null, expired_transaction_status varchar(20), generate_batch_number bit(1) default b'0' not null, partial_refund_enabled bit(1) default b'0' not null, processing_hop varchar(15), provider_base_url varchar(255) not null, provider_key varchar(255), provider_name varchar(255) not null, provider_password varchar(255), provider_username varchar(255), status varchar(20), timezone varchar(255), upi_check_status_enabled bit(1) default b'0' not null, primary key (id)) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE latin1_general_cs  [42122-212]
2022-06-28 06:21:12.980 ERROR 18824 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000388: Unsuccessful: create table bin_info (bin varchar(6) not null, created_by varchar(20) not null, created_time datetime not null, lock_id int(11) default 0 not null, modified_by varchar(20) not null, modified_time datetime not null, bank varchar(50), bank_code varchar(25), cash_enabled bit(1) default b'1', classification varchar(10), country2_iso varchar(3), country3_iso varchar(4), country_iso varchar(2), emi_enabled bit(1) default b'1', info varchar(100), iso_country varchar(16), loyalty_enabled bit(1) default b'0', mdr_card_category varchar(100), origin varchar(16), payment_card_brand varchar(25), payment_card_type varchar(10), phone varchar(16), verified_bin bit(1) default b'0', www varchar(255), primary key (bin)) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE latin1_general_cs 
2022-06-28 06:21:12.980 ERROR 18824 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : Column &quot;B&quot; not found; SQL statement:
create table bin_info (bin varchar(6) not null, created_by varchar(20) not null, created_time datetime not null, lock_id int(11) default 0 not null, modified_by varchar(20) not null, modified_time datetime not null, bank varchar(50), bank_code varchar(25), cash_enabled bit(1) default b'1', classification varchar(10), country2_iso varchar(3), country3_iso varchar(4), country_iso varchar(2), emi_enabled bit(1) default b'1', info varchar(100), iso_country varchar(16), loyalty_enabled bit(1) default b'0', mdr_card_category varchar(100), origin varchar(16), payment_card_brand varchar(25), payment_card_type varchar(10), phone varchar(16), verified_bin bit(1) default b'0', www varchar(255), primary key (bin)) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE latin1_general_cs  [42122-212]
2022-06-28 06:21:12.996 ERROR 18824 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000388: Unsuccessful: create table communication_mapping (id bigint not null auto_increment, created_by varchar(20) not null, created_time datetime not null, lock_id int(11) default 0 not null, modified_by varchar(20) not null, modified_time datetime not null, block_repetition bit(1) default b'1', communication_template_id bigint not null, communication_trigger varchar(5) not null, communication_type varchar(12) not null, config_level varchar(4) not null, csv_input json not null, csv_report json, end_date datetime not null, end_date_modified datetime, input_touch_points integer not null, mapping_name varchar(50) not null, recipient_level varchar(5), start_date datetime not null, status varchar(25), target_users_count bigint, total_target_count bigint, no_of_touch_points bigint, no_of_touch_points_modified bigint, primary key (id)) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE latin1_general_cs 
2022-06-28 06:21:12.996 ERROR 18824 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : Column &quot;B&quot; not found; SQL statement:
create table communication_mapping (id bigint not null auto_increment, created_by varchar(20) not null, created_time datetime not null, lock_id int(11) default 0 not null, modified_by varchar(20) not null, modified_time datetime not null, block_repetition bit(1) default b'1', communication_template_id bigint not null, communication_trigger varchar(5) not null, communication_type varchar(12) not null, config_level varchar(4) not null, csv_input json not null, csv_report json, end_date datetime not null, end_date_modified datetime, input_touch_points integer not null, mapping_name varchar(50) not null, recipient_level varchar(5), start_date datetime not null, status varchar(25), target_users_count bigint, total_target_count bigint, no_of_touch_points bigint, no_of_touch_points_modified bigint, primary key (id)) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE latin1_general_cs  [42122-212]

</code></pre>
<p>My db configuration in the application.properties file</p>
<pre><code>database.driver=org.h2.Driver
database.url=jdbc:h2:mem:testdb12;MODE=MySQL;IGNORECASE=TRUE
database.user=root
database.password=root123
spring.h2.console.enabled=true
database.encEnabled=false
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
</code></pre>
<p><strong>Note:</strong> all the SQL queries are verified so I can't make any changes to the queries.</p>
",https://stackoverflow.com/questions/72779825/getting-column-b-not-found-while-running-the-sql-query-to-create-the-table-in,"['spring-boot', 'h2', 'h2db']",231,True,0,1
