title,body,link,tags,view_count,is_answered,score,answer_count
Integration testing DRF,"<p>I'm using Django with DRF as just an API--it doesn't serve any FE assets of any kind. I know the Django testing suite is built on the Python native <code>unittest</code> library and plan on using it for unit testing.</p>
<ul>
<li>When it comes to integration testing, is it sufficient or should something like Behave be used?</li>
<li>If <code>unittest</code> is sufficient, should it be used in conjunction with some kind of faker?</li>
</ul>
",https://stackoverflow.com/questions/66676964/integration-testing-drf,"['django', 'testing', 'django-rest-framework', 'integration-testing']",835,True,2,1
Spring Batch Integration testing,"<br>
We have several spring batch projects and we want to implement integration tests for them.
<p>One of the projects reads from DB and writes to another DB.<br>
The other project reads from DB and writes to a file.<br>
The other reads from File and writes to DB.</p>
<p>How can we apply the end-to-end integration test to these projects?<br>
How can we run this test in the pipeline?</p>
<p>Thank you.</p>
",https://stackoverflow.com/questions/66708173/spring-batch-integration-testing,"['java', 'spring', 'spring-batch', 'integration-testing']",1870,True,0,1
Spring boot integration testing issue,"<p>I am working on a project, i have completed but issue is in project i have to write integration testing code.</p>
<blockquote>
<p>This is the controller</p>
</blockquote>
<pre><code> @PostMapping(&quot;/newgame&quot;)
    public ResponseEntity&lt;Players&gt; beginNewGame(@RequestBody Players players) {

        Players savedPersion = playerService.beginNewGame(players);

        return savedPersion!=null ?  ResponseEntity.ok(savedPersion):
                (ResponseEntity&lt;Players&gt;) ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
}
</code></pre>
<blockquote>
<p>And this is service.</p>
</blockquote>
<pre><code>@Override
    public Players beginNewGame(Players players) {

            //new game state
            GameState gameState =new GameState();
            gameState.setWinner(&quot;null&quot;);


        GameState save = gameStateRepositery.save(gameState);

        //new score
        Score score = new Score();
        score.setGameId(save.getId());

        Score savedScore = scoreRepositery.save(score);
        players.setScoreId(savedScore.getId());
        players.setGameId(save.getId());

        Players savedPlayers=null;
            savedPlayers= playersRepositery.save(players);

        System.out.println(savedScore.getGameId()+&quot;ksdjfkjskn&quot;);

       return savedPlayers;
    }
</code></pre>
<blockquote>
<p>And if i hit the endpoints with proper required parameters, the is
working fine, and return me.</p>
</blockquote>
<pre><code>{
    &quot;gameId&quot;: 57,
    &quot;id&quot;: 1,
    &quot;playerOne&quot;: &quot;vinitSaini&quot;,
    &quot;playerTwo&quot;: &quot;anonymousKal&quot;,
    &quot;scoreId&quot;: 58
}
</code></pre>
<blockquote>
<p>This is the testing code, how i can check  what the response is
returning.</p>
</blockquote>
<pre><code>@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
public class PlayersIntTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private PlayersRepositery playersRepositery;


    @Test
    void newGame() throws Exception {
        
        //mockMvc.perform(post(&quot;/api/{forumId}/register&quot;, 42L)
        mockMvc.perform(post(&quot;/api/newgame&quot;)
                .contentType(&quot;application/json&quot;)
                .content(objectMapper.writeValueAsString(players)))
                .andExpect(status().isOk());




    }
</code></pre>
<p><strong>So please help me to write integration testing.</strong></p>
",https://stackoverflow.com/questions/67252093/spring-boot-integration-testing-issue,"['java', 'spring', 'spring-boot', 'spring-mvc', 'testing']",126,False,1,2
Spring integration testing of logout,"<p>I have a Spring Controller that contains a logout endpoint</p>
<pre><code>@PostMapping(&quot;/logout&quot;)
public ResponseEntity&lt;Void&gt; logout() {
    var request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    try {
        request.logout();
        return new ResponseEntity&lt;&gt;(HttpStatus.OK);
    } catch (ServletException e) {
        log.error(&quot;Unable to logout&quot;);
        return new ResponseEntity&lt;&gt;(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
</code></pre>
<p>How can I test this using mockmvc ?</p>
<p>What I have so far is this piece of code, but I don't know how to test that the request.logout() was called (what are its effects?).</p>
<pre><code>mvc.perform(MockMvcRequestBuilders.post(&quot;/logout&quot;).principal(principal)).expect(??)
</code></pre>
",https://stackoverflow.com/questions/66877066/spring-integration-testing-of-logout,"['java', 'spring', 'spring-mvc', 'spring-security']",228,False,0,1
Integration testing with Azure ADB2C,"<p>We have a Web application that is protected by Azure ADB2C. Users must be logged in to access the application. When the user logs into the application we use the API connectors feature to go and fetch more user details using the email the user logged in with. These extra details are added to the token as custom attributes and are consumed by the web app inside the OnTokenValidated event.</p>
<p>When our code is deployed to either the Test/Staging or Production endpoints our integration tests are run against that endpoint. I can't spoof the authentication as the tests are talking to live endpoints. I need to authenticate the tests as if they are a real user.</p>
<p>I have looked around and have tried the ROPC flow that is suggested on similar posts. The trouble is with this solution is that it does not call the API connectors to get the extra user details that the 'normal' login flow would.</p>
<p>ROPC Solution:
<a href=""https://stackoverflow.com/questions/62281717/integration-test-with-azure-ad-login?rq=1"">Integration Test with Azure AD login</a></p>
<p>How can I make my integration tests authenticate with Azure ADB2C the same way a real user would so that the API connectors are called?</p>
<p>Any help/advice is greatly appreciated.</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/69347980/integration-testing-with-azure-adb2c,"['asp.net-core', 'web-applications', 'integration-testing', 'azure-ad-b2c']",256,False,0,1
Integration Testing multipart/form-data c#,"<p>I have trouble trying to create an integration test for my post call that accepts a viewmodel that has amongst other values, an IFormFile, which makes this call from an application/json to a multipart/form-data</p>
<p>My IntegrationSetup class</p>
<pre><code>protected static IFormFile GetFormFile()
        {
            byte[] bytes = Encoding.UTF8.GetBytes(&quot;test;test;&quot;);

            var file = new FormFile(
                baseStream: new MemoryStream(bytes),
                baseStreamOffset: 0,
                length: bytes.Length,
                name: &quot;Data&quot;,
                fileName: &quot;dummy.csv&quot;
            )
            {
                Headers = new HeaderDictionary(),
                ContentType = &quot;text/csv&quot;
            };

            return file;
        } 
</code></pre>
<p>My Test Method</p>
<pre><code>public async Task CreateAsync_ShouldReturnId()
        {
            //Arrange
            using var content = new MultipartFormDataContent();
            var stringContent = new StringContent(
                JsonConvert.SerializeObject(new CreateArticleViewmodel
                {
                    Title = &quot;viewModel.Title&quot;,
                    SmallParagraph = &quot;viewModel.SmallParagraph&quot;,
                    Url = &quot;viewModel.Url&quot;,
                    Image = GetFormFile()
                }),
                Encoding.UTF8,
                &quot;application/json&quot;);
            stringContent.Headers.Add(&quot;Content-Disposition&quot;, &quot;form-data; name=\&quot;json\&quot;&quot;);
            content.Add(stringContent, &quot;json&quot;);

            //Act
            var response = await httpClient.PostAsync($&quot;{Url}&quot;, content);
            //Assert
            response.StatusCode.ShouldBe(HttpStatusCode.OK);
            int id = int.Parse(await response.Content.ReadAsStringAsync());
            id.ShouldBeGreaterThan(0);
        }
</code></pre>
<p>My Controller Method</p>
<pre><code>[HttpPost]
        public async Task&lt;IActionResult&gt; CreateArticleAsync([FromForm] CreateArticleViewmodel viewModel)
        {

            var id = await _service.CreateAsync(viewModel).ConfigureAwait(false);
            if (id &gt; 0)
                return Ok(id);
            return BadRequest();
        }
</code></pre>
<p>It throws a BadRequest without getting inside the method.</p>
",https://stackoverflow.com/questions/68211390/integration-testing-multipart-form-data-c,"['c#', 'asp.net-core', 'integration-testing', 'asp.net-core-webapi', 'web-api-testing']",2095,True,2,1
Integration Testing with Spring Cloud Kubernetes,"<p>We are in the process of evaluating Spring Cloud Kubernetes. Our projects are using <code>Spring Cloud 2020.0.3</code> and <code>Spring Boot 2.4.9</code>. We have been deploying our microservices up to this point to Docker Swarm, and as a result we have been using Spring Cloud Eureka, Spring Cloud Config, and Spring Cloud Gateway. Now we're making modifications to our microservices to remove any references to these components.</p>
<p>After adding the following dependency to our microservices, as long as I have a local Minikube cluster running, my Maven build, which includes many integration tests, runs just fine.</p>
<pre><code>&lt;dependency&gt;
  &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
  &lt;artifactId&gt;spring-cloud-starter-kubernetes-client-all&lt;/artifactId&gt;
&lt;/dependency&gt;
</code></pre>
<p>However, if I destroy my Minikube cluster, the Spring Boot integration tests fail with the following exception:</p>
<pre><code>14:46:00.569 [main] ERROR o.s.boot.SpringApplication - Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'kubernetesInformerDiscoveryClient' defined in class path resource [org/springframework/cloud/kubernetes/client/discovery/KubernetesDiscoveryClientAutoConfiguration$KubernetesInformerDiscoveryConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Timeout waiting for informers cache to be ready, is the kubernetes service up?
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:771)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:763)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:438)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:339)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:123)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassBasedTestDescriptor.java:350)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:355)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$7(ClassBasedTestDescriptor.java:350)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1654)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:312)
    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:658)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:349)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$4(ClassBasedTestDescriptor.java:270)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:269)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$2(ClassBasedTestDescriptor.java:259)
    at java.base/java.util.Optional.orElseGet(Optional.java:369)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$3(ClassBasedTestDescriptor.java:258)
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:101)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:100)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:65)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:111)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:111)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:79)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invokeAllTests(JUnitPlatformProvider.java:150)
    at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invoke(JUnitPlatformProvider.java:124)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418)
Caused by: java.lang.IllegalStateException: Timeout waiting for informers cache to be ready, is the kubernetes service up?
    at org.springframework.cloud.kubernetes.client.discovery.KubernetesInformerDiscoveryClient.afterPropertiesSet(KubernetesInformerDiscoveryClient.java:221)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1845)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1782)
    ... 83 common frames omitted
</code></pre>
<p>I've been referencing the Spring Cloud Kubernetes <a href=""https://docs.spring.io/spring-cloud-kubernetes/docs/current/reference/html/"" rel=""nofollow noreferrer"">documentation</a>, but I don't see any mention of Spring Cloud Kubernetes test support. Can anyone point me in the right direction regarding what I need to do to enable my integration tests to work without requiring that a Kubernetes cluster is up and running on my build machine?</p>
",https://stackoverflow.com/questions/68535830/integration-testing-with-spring-cloud-kubernetes,['spring-cloud-kubernetes'],468,False,1,0
authorize camera test in integration testing,"<p>I am writing integration tests for Flutter App. The app let's users to take video. When writing test, how can I allow camera permission for my app inside the script for integration testing when the permission dialog appears?</p>
",https://stackoverflow.com/questions/67704165/authorize-camera-test-in-integration-testing,"['flutter', 'integration-testing']",1329,True,1,1
Integration testing of a Beam Pipeline,"<p>We have a Beam pipeline that is written using the Python SDK. The pipeline is reading from an ordered Pub/Sub topic, doing some small transformations and then inserting into ElasticSearch.</p>
<p>We want to write some integration tests that will cover the entire flow, reading from Pub/Sub and using the ES client, to make some assertions over what was inserted as a result. Since the job is streaming, it's a bit tricky to test it inside tests. Here is an example of how I do it now:</p>
<pre class=""lang-py prettyprint-override""><code>@pytest.fixture
def test_options():
    setup_options = SetupOptions()
    standard_options = setup_options.view_as(StandardOptions)
    standard_options.streaming = True
    standard_options.runner = &quot;DirectRunner&quot;
    return standard_options



def test_reading_from_pubsub_to_elastic(test_options, customer_es_client, pubsub_publisher, user_events):
    expected_ids = [&quot;1_3&quot;, &quot;1_9&quot;, &quot;1_4&quot;, &quot;1_6&quot;, &quot;1_10&quot;, &quot;1_8&quot;, &quot;1_5&quot;, &quot;1_7&quot;, &quot;1_2&quot;, &quot;1_1&quot;]

    p = HelpderClassToInitPipeline(pipeline=TestPipeline(blocking=False, options=test_options))
    pipe = p.create_pipeline(project=PROJECT, local_config=LocalConfig(run_local=False))
    pipe_result = pipe.run()

    futures = []
    for e in user_events:
        futures.append(
            pubsub_publisher.publish(
                topic=f&quot;topic_&quot;,
                data=json.dumps(e).encode(),
            )
        )
    for f in futures:
        f.result()

    time.sleep(10)  # wait for the pipeline to consume events

    result = customer_es_client.search(index=&quot;customer&quot;, body={&quot;_source&quot;: [&quot;_id&quot;], &quot;query&quot;: {&quot;match_all&quot;: {}}})

    ids = [d[&quot;_id&quot;] for d in result[&quot;hits&quot;][&quot;hits&quot;]]

    assert ids.sort() == expected_ids.sort()
    pipe_result.cancel()
</code></pre>
<p>We are using <code>pytest</code> as a test runner, and we run the inside the CI. Basically we provision Pub/Sub topics in CI, then run the tests, and then we clean up everything.</p>
<p>You can see that <code>time.sleep</code> call that is needed for the pipeline to consume and store so that we could query ES. Not sure if this is the best practice.</p>
<p>Any advices how can I improve this?</p>
",https://stackoverflow.com/questions/67622521/integration-testing-of-a-beam-pipeline,['apache-beam'],141,False,0,0
Configuring Axon in Spring for integration testing,"<p>Still new to java and axon, having troubles to setup integration test suite using spring and axon.</p>
<p>Basically, I have some process, which:</p>
<ul>
<li>starts with command1</li>
<li>goes to command handler on aggregate and event1 is dispatched</li>
<li>event1 is processed by some policy (event listener) and command2 is generated</li>
<li>command2 is processed by command handler service (thus has no aggregate id) because I need to process something with third party</li>
<li>event2 is dispatched and processed by another event listener, so command3 is dispatched</li>
<li>command3 is processed by aggregate and event3 is dispatched</li>
</ul>
<p>I use <a href=""https://docs.axoniq.io/reference-guide/v/4.4/axon-framework/testing/commands-events"" rel=""nofollow noreferrer"">axon tests</a> for unit testing aggregates and it works great.</p>
<p>But I would like to add &quot;integration&quot; tests to:</p>
<ol>
<li>check the whole flow, like: when command1 dispatched then event1, event2, event3 is recorded (actually don't care about fields, just to have confidence the whole thing is glued as expected)</li>
<li>check the service command handler work as expected in manner &quot;when command2 dispatched, then event2 is recorded&quot;</li>
</ol>
<p>I was partly succesful with 1) by doing:</p>
<pre class=""lang-java prettyprint-override""><code>package com.example.integration;

import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.eventsourcing.eventstore.EmbeddedEventStore;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Arrays;
import java.util.UUID;

@RunWith(SpringRunner.class)
@SpringBootTest
@Import(IntegrationTestConfig.class)
public class ExampleIntegrationTest
{

    @Autowired
    private CommandGateway commandGateway;

    @Autowired
    private EmbeddedEventStore eventStore;

    @Test
    public void itShouldStoreCorrectEvents() {
        var aggregateId = UUID.randomUUID().toString();
        var exampleCommand = new ExampleCommand(aggregateId);

        whenCommandIsDispatched(exampleCommand);

        thenExpectedEventsRecorded(
                Arrays.asList(
                        Event1.class,
                        Event3.class
                ),
                aggregateId
        );
    }

    private void whenCommandIsDispatched(Command command)
    {
        commandGateway.sendAndWait(command);
    }

    private void thenExpectedEventsDispatched(java.util.List&lt;Class&lt;?&gt;&gt; expectedEventTypes, String id)
    {
        var events = eventStore.readEvents(id);
        while (events.hasNext()) {
            Assert.assertEquals(
                    expectedEventTypes.get(Math.toIntExact(events.getLastSequenceNumber())),
                    events.next().getPayloadType()
            );
        }
    }
}

</code></pre>
<p>And having IntegrationConfigTest:</p>
<pre class=""lang-java prettyprint-override""><code>package com.example.library.test;

import org.axonframework.eventhandling.EventBus;
import org.axonframework.eventsourcing.eventstore.EmbeddedEventStore;
import org.axonframework.eventsourcing.eventstore.EventStorageEngine;
import org.axonframework.eventsourcing.eventstore.inmemory.InMemoryEventStorageEngine;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

@TestConfiguration
public class IntegrationTestConfig {

    @Bean
    @Primary
    public static EventBus createSpyEventBus() {
        return new EmbeddedEventStore.Builder().storageEngine(new InMemoryEventStorageEngine()).build();
    }
}
</code></pre>
<p>Which is nice and test passes, but I didn't find a way how to test events dispatched from the service command handler (Event2 in my example) - id of aggregate is needed here: <code>eventStore.readEvents(id)</code>. EDIT: But I dont want to put aggregate id in, since event was not recorded on any aggregate - it was dispatched right into event gateway in service/singleton command handler.</p>
<p>Any ideas how can I get all dispatched events so I can also assert Event2 was dispatched?</p>
<p>Or am I missing something here? :)</p>
",https://stackoverflow.com/questions/69004824/configuring-axon-in-spring-for-integration-testing,"['spring', 'spring-test', 'axon']",638,True,3,2
How to compose Docker with Integration Testing,"<p>I downloaded Docker and then run Integration Tests in my Intelij Idea written on Java.
And each integration test had the same problem :</p>
<pre><code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.api.FlywayException: Validate failed: 
Detected applied migration not resolved locally: 1.1
Detected applied migration not resolved locally: 1.2
Detected applied migration not resolved locally: 1.3
Detected applied migration not resolved locally: 1.4
Detected applied migration not resolved locally: 1.5
Detected applied migration not resolved locally: 2.1
Detected applied migration not resolved locally: 3.1
Detected applied migration not resolved locally: 3.2
Detected applied migration not resolved locally: 9.1
Detected applied migration not resolved locally: 10.1
Detected applied migration not resolved locally: 10.2
Detected applied migration not resolved locally: 11.1
Detected applied migration not resolved locally: 11.2
Detected applied migration not resolved locally: 11.3
Detected applied migration not resolved locally: 11.4
Detected applied migration not resolved locally: 11.5
</code></pre>
<p>How can it be fix?</p>
",https://stackoverflow.com/questions/68767594/how-to-compose-docker-with-integration-testing,"['java', 'docker', 'integration-testing', 'flyway']",96,False,1,0
Nodejs Integration testing fire and forget testing,"<p>I have a function controller which does some DB updates and inserts.</p>
<p>Example</p>
<pre><code>export const patchRecords = async (req: Request, res: Response) =&gt; {
    // Do some inserts.
    // Do some work.
       res.sendStatus(200);
    //fire and forget
    await additionalUpdate();
}
</code></pre>
<p>While testing this function I am getting some issues. The error is obvious but I am unable to fix this.</p>
<p>The error is that, the jest environment is already torn down once the sendStatus expect passes.</p>
<p>example test:</p>
<pre><code>  it.only('should insert order for store and product.', async () =&gt; {

        const { status } = await jsonApiRequest(
            'POST',
            `${baseUrl}/updateproducts/${storeNumber}/${productId}`,
            {
                accessToken,
            }
        );
      expect(status).toBe(201)
    });
</code></pre>
<p>The test passes, but I get below error:</p>
<pre><code>ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Failed sql and bindings 
</code></pre>
<p>This happens because of the <code>fire and forget</code> function which is called after <code>sendStatus</code></p>
<pre><code> await additionalUpdate(); // is heavy function takes some time to complete
</code></pre>
<p>I tried adding a delay in the test, but it will not work, because the we cannot predict time taken by <code>additionalUpdate</code> to complete.</p>
<pre><code>        delay(()=&gt; {
            expect(status).toBe(201)
        }, 1000);
</code></pre>
<p>I tried mocking the <code>additionalUpdate</code> function but that too does not work as it's integration test.</p>
<p>How can I fix this?</p>
",https://stackoverflow.com/questions/70216341/nodejs-integration-testing-fire-and-forget-testing,"['node.js', 'jestjs', 'integration-testing']",142,False,1,0
Integration Testing with Devise + Omniauth + Rspec + Capybara,"<p>I am trying to write some integration tests using Rspec (feature) alongside Devise and Omniauth. The OAuth provider I am using is <code>azure_activedirectory</code>.</p>
<p>I have followed the tutorial <a href=""https://github.com/omniauth/omniauth/wiki/Integration-Testing"" rel=""nofollow noreferrer"">here at the Omniauth wiki</a></p>
<p>I don't think I am doing it right. When I launch an integration test, the link for the login (localhost:3000/omniauth/azure_activedirectory) behaves like it would in dev or production, with the link directing the client to the omniauth portal page.</p>
<p>Of course given this is a test, I can't store credentials here.</p>
<p>It appears from the code in the wiki link that it should instead feed a login using a mock_auth.</p>
<p>Here is my current spec code:</p>
<pre><code>require 'rails_helper'

Capybara.app_host = &quot;http://lvh.me&quot;
OmniAuth.config.test_mode = true
OmniAuth.config.add_mock(:azure_activedirectory, {:uid =&gt; '12345'})

RSpec.feature &quot;AuthenticatesUser&quot;, type: :feature do

  before do 
    Rails.application.env_config[&quot;devise.mapping&quot;] = Devise.mappings[:user]
    Rails.application.env_config[&quot;omniauth.auth&quot;] = OmniAuth.config.mock_auth[:azure_activedirectory]
  end

  scenario &quot;User can login&quot;, js: true do
    WebMock.allow_net_connect! 
    visit '/'
    click_link 'login'
    binding.pry
    WebMock.disable_net_connect!(allow_localhost: true) # Re enable with local host
  end
end
</code></pre>
<p>So what am I doing wrong? I feel that I am using the example code in a very incorrect way or not understanding the process.</p>
<p>Or is the next step just setting up a testing oauth instance and configuring it that way to use live credentials from Azure.</p>
<p>Thanks for the help in advance.</p>
<p><strong>UPDATE</strong></p>
<p>This has to do with Capybara and the JS driver starting or running on a different server.</p>
<p>If in the interactive ruby console in the Selenium browser <code>OmniAuth.config.test_mode == false</code>. If I set it using the console in the web browser, everything 'works'.</p>
",https://stackoverflow.com/questions/67335380/integration-testing-with-devise-omniauth-rspec-capybara,"['ruby-on-rails', 'devise', 'azure-active-directory', 'capybara', 'omniauth']",581,False,1,1
Integration Testing Minimal API .NET 6 - nUnit,"<p>With .NET 5 I used the following in my nUnit <code>[SetUp]</code> for each test.  This created a host and a client with which I could call my API with full integrations as defined in the <code>Startup</code>:</p>
<pre><code>Microsoft.AspNetCore.TestHost.TestServer _testServer;

HttpClient _testClient;

[SetUp]
public async Task SetUp()
{
    // Load up test configuration
    IConfiguration config = new ConfigurationBuilder()
        .SetBasePath(&quot;mypath&quot;)
        .AddJsonFile(&quot;integrationsettings.json&quot;)
        .Build();

    // Create the host (using startup)
    WebHostBuilder builder = new WebHostBuilder()
        // Use startup from WebApp Server project
        .UserStartup&lt;MyWebApp.Startup&gt;()
        // Configure logging from integrationsettings.json
        .ConfigureLogging((hostingContext, logging) =&gt;
            logging.AddConfiguration(config.GetSection(&quot;Logging&quot;))
        // Set core app configuration to use integrationsettings.json
        .ConfigureAppConfiguration(cfg =&gt; cfg.AddConfiguration(config))
        // Add any additional services not loaded by startup
        .ConfigureServices(services =&gt; // add additional services not laoded in Startup);

    // Create the Server
    _testServer = new TestServer(builder);

    // Create the Client
    _testClient = _testServer.CreateClient();
}
</code></pre>
<p>I could then use <code>testClient HttpClient</code> to work directly with my API.</p>
<p>Life was sweet.</p>
<p>I know I could still use the old model with .NET 6 (Program.cs + Startup.cs), but if I'm going to go with the flow, now that we have minimal API with just the Program.cs, how do I replicate the above?</p>
<p>From what I can gather, it looks like WebApplicationFactory is the key, but have not found anything that gets me over the line.</p>
<p>Is it as simple as adding the assembly that contains WebApplication and just build the app in test SetUp in the same way as I do in Program.cs on the server?</p>
<p>Is there a way to encapsulate the build logic (much like the old Startup.cs) so I do not need to duplicate the configuration used on the server in my tests?</p>
",https://stackoverflow.com/questions/70306122/integration-testing-minimal-api-net-6-nunit,"['asp.net-core', 'nunit', 'integration-testing', 'asp.net-core-webapi', '.net-6.0']",1111,False,1,0
Mock IRequestClient&lt;&gt; during Integration Testing using MassTransit,"<p>I'm trying to do integration testing against a MediatR Command whose handler depends on an IRequestClient injected into its constructor.</p>
<pre><code>    public class SayHelloCommand : IRequest&lt;string&gt;
    {
    }

    public class SayHelloCommandHandler : IRequestHandler&lt;SayHelloCommand, string&gt;
    {
        private readonly IRequestClient&lt;IGetProfileMessageResult&gt; _profileClient;

        public SayHelloCommandHandler(IRequestClient&lt;IGetProfileMessageResult&gt; profileClient)
        {
            _profileClient = profileClient;
        }
        public async Task&lt;string&gt; Handle(SayHelloCommand request, CancellationToken cancellationToken)
        {
            var profile = (await _profileClient.GetResponse&lt;IGetProfileMessageResult&gt;(new {ProfileId = 1})).Message;

            return $&quot;Hello {profile.FirstName}&quot;;
        }
    }
</code></pre>
<p>I've setup my test suite to use the InMemoryMassTransit but whenever I run my test it times out when it reaches the call using the IRequestClient&lt;&gt;. I've also tried to moq the IRequestClient to return a default response like this -</p>
<pre><code>
        [Test]
        public async Task ShouldSayHello()
        {
          
          
            var mockRequestClient = new Mock&lt;IRequestClient&lt;IGetProfileMessageResult&gt;&gt;();
            mockRequestClient.Setup(x =&gt; x.GetResponse&lt;IGetProfileMessageResult&gt;(It.IsAny&lt;Object&gt;(), default, default)
            .Result.Message).Returns(new GetProfileMessageResult
            {
                FirstName = &quot;John&quot;
            });

            serviceCollection.Add(new ServiceDescriptor(typeof(IRequestClient&lt;IGetProfileMessageResult&gt;), mockRequestClient.Object));

            var result = await SendAsync(command);

            result.Status.Should().BeFalse();
            result.Message.Should().Contain(&quot;John&quot;);
        }
            

</code></pre>
<p>but this still times out.</p>
<p>Is there a way I can set up the InMemoryMassTransit to return a default response when the requestclient is called?</p>
",https://stackoverflow.com/questions/70389744/mock-irequestclient-during-integration-testing-using-masstransit,"['.net-core', 'nunit', 'moq', 'masstransit']",632,False,0,1
Stage environment for Serverless Framework integration testing,"<p>Serverless Framework has its own integration testing of endpoints, as defined <a href=""https://www.serverless.com/framework/docs/guides/testing/"" rel=""nofollow noreferrer"">here</a>. The documentation does not mention any staging or parameters that can be used for complex authentication or other setup work that may need to be done to verify an endpoint is correctly setup.</p>
<p>Is it possible to use Serverless Framework's integration testing tool with staged information? If so, how? If not, what is the intended purpose of this integration testing framework - simply to verify that an endpoint returns unauthorized errors?</p>
",https://stackoverflow.com/questions/66790160/stage-environment-for-serverless-framework-integration-testing,"['serverless-framework', 'serverless']",48,False,-1,1
Integration testing Okta app with PKCE flow,"<p>We have an application using Okta as our IDP. We have enabled the PKCE flow in the application since that is the recommended flow for our SPA</p>
<p>We would like to be able to create an integration test to automatically invoke some of our APIs and have the appropriate groups in the claims in the token we get. However, we can't enable both the PKCE and client_credentials grant types. We get an error about invalid grant types when we add them both via API.</p>
<p>The error we get is:</p>
<pre><code>        {
            &quot;errorSummary&quot;: &quot;token_endpoint_auth_method: 'token_endpoint_auth_method' is invalid. Valid values: [client_secret_basic, client_secret_post, client_secret_jwt, private_key_jwt].&quot;
        },
        {
            &quot;errorSummary&quot;: &quot;grant_types: 'grant_types' is invalid. Valid values: [implicit].&quot;
        }
</code></pre>
<p>What is the right way to get a token for testing an application via headless script that is using the PKCE flow?</p>
",https://stackoverflow.com/questions/69442374/integration-testing-okta-app-with-pkce-flow,"['javascript', 'oauth-2.0', 'okta', 'pkce']",447,True,0,1
Rails Integration testing with rspec and fixture_file_upload,"<p>I recently ran into an issue with an integration test using rspec.</p>
<pre class=""lang-rb prettyprint-override""><code>RSpec.describe &quot;Images&quot;, type: :request do
  before(:each) do
    @user = User.create(username: &quot;sam&quot;, password: &quot;password&quot;)
    @tag = @user.tags.create(name: &quot;outdoors&quot;)

    post login_path, params: { username: &quot;sam&quot;, password: &quot;password&quot; }
    expect(session[:user_id]).to eql @user.id

    @file = fixture_file_upload(&quot;/dingo.jpeg&quot;, &quot;image/jpeg&quot;)
  end

  it &quot;can show images&quot; do
    @image = @user.images.create(caption: &quot;hello&quot;, image_file: @image)
    get user_image_path(@user, @image)
    expect(response).to be_success
  end
end
</code></pre>
<p>The before each creates a valid user, tag and logs the user in. Then it loads an image file.
The test it's self creates a new image for the @user and assigns it a value for caption and the loaded file for its :image_file.</p>
<p>The Image model uses has_one_attached :image_file to associate an uploaded image with an image record</p>
<pre class=""lang-rb prettyprint-override""><code>class Image &lt; ApplicationRecord
  belongs_to :user
  has_and_belongs_to_many :tags
  has_one_attached :image_file
end
</code></pre>
<p>the controller and action as follows:</p>
<pre class=""lang-rb prettyprint-override""><code>class ImageController &lt; ApplicationController
  before_action :unauthorized_redirect
  
  def show
    @user = current_user
    @image = Image.find(params[:id])
    @tags = @user.tags.all
    authorize @image, :show?
  end

  private

  def image_params
    params.require(:image).permit(:caption, :image_file, tag_ids: [])
  end
end
</code></pre>
<p>When I run the test I get an error:</p>
<pre><code>Failures:

  1) Images can show images
     Failure/Error: &lt;%= image_tag @image.image_file, class: &quot;img-fluid show-image&quot; %&gt;
     
     ActionView::Template::Error:
       Can't resolve image into URL: undefined method `persisted?' for nil:NilClass
     # ./app/views/image/show.html.erb:7:in `_app_views_image_show_html_erb__3727703739275822003_20580'
     # &lt;internal:kernel&gt;:90:in `tap'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/actiontext-6.1.4.1/lib/action_text/rendering.rb:20:in `with_renderer'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/actiontext-6.1.4.1/lib/action_text/engine.rb:59:in `block (4 levels) in &lt;class:Engine&gt;'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/rack-2.2.3/lib/rack/tempfile_reaper.rb:15:in `call'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/rack-2.2.3/lib/rack/etag.rb:27:in `call'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/rack-2.2.3/lib/rack/conditional_get.rb:27:in `call'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/rack-2.2.3/lib/rack/head.rb:12:in `call'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/rack-2.2.3/lib/rack/session/abstract/id.rb:266:in `context'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/rack-2.2.3/lib/rack/session/abstract/id.rb:260:in `call'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/railties-6.1.4.1/lib/rails/rack/logger.rb:37:in `call_app'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/railties-6.1.4.1/lib/rails/rack/logger.rb:26:in `block in call'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/railties-6.1.4.1/lib/rails/rack/logger.rb:26:in `call'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/rack-2.2.3/lib/rack/method_override.rb:24:in `call'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/rack-2.2.3/lib/rack/runtime.rb:22:in `call'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/rack-2.2.3/lib/rack/sendfile.rb:110:in `call'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/railties-6.1.4.1/lib/rails/engine.rb:539:in `call'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/rack-test-1.1.0/lib/rack/mock_session.rb:29:in `request'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/rack-test-1.1.0/lib/rack/test.rb:266:in `process_request'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/rack-test-1.1.0/lib/rack/test.rb:119:in `request'
     # /home/sam/.rvm/gems/ruby-3.0.0/gems/rails-controller-testing-1.0.5/lib/rails/controller/testing/integration.rb:16:in `block (2 levels) in &lt;module:Integration&gt;'
     # ./spec/requests/images_spec.rb:38:in `block (2 levels) in &lt;main&gt;'
     # ------------------
     # --- Caused by: ---
     # NoMethodError:
     #   undefined method `persisted?' for nil:NilClass
     #   ./app/views/image/show.html.erb:7:in `_app_views_image_show_html_erb__3727703739275822003_20580'

Finished in 0.79372 seconds (files took 0.46552 seconds to load)
30 examples, 1 failure

Failed examples:

rspec ./spec/requests/images_spec.rb:36 # Images can show images
</code></pre>
<p>I have debugged this issue with breakpoints everywhere and I just don't understand why it's not working in test when it works in production. I hope I've provided enough information this bug has been driving me crazy for the past two days.
Thank you!</p>
<p>Versions:
rails: 6.1.4.1
rspec: 5.0.2</p>
",https://stackoverflow.com/questions/69272905/rails-integration-testing-with-rspec-and-fixture-file-upload,"['ruby-on-rails', 'ruby', 'rspec', 'rspec-rails', 'rails-activestorage']",381,False,0,1
Google cloud function integration testing pass param?,"<p>I have created a cloud function to print greetings like &quot;Hello David!&quot;. my function below:</p>
<pre class=""lang-java prettyprint-override""><code>public void service(HttpRequest request, HttpResponse response)
        throws IOException {
        String name = request.getFirstQueryParameter(&quot;name&quot;).orElse(&quot;world&quot;);
        try {
            JsonElement requestParsed = gson.fromJson(request.getReader(), JsonElement.class);
            JsonObject requestJson = null;

            if (requestParsed != null &amp;&amp; requestParsed.isJsonObject()) {
                requestJson = requestParsed.getAsJsonObject();
            }

            if (requestJson != null &amp;&amp; requestJson.has(&quot;name&quot;)) {
                name = requestJson.get(&quot;name&quot;).getAsString();
            }
        } catch (JsonParseException e) {
            logger.severe(&quot;Error parsing JSON: &quot; + e.getMessage());
        }
        var writer = new PrintWriter(response.getWriter());
        writer.printf(&quot;Hello %s!&quot;, name);
    }
</code></pre>
<p>I have written a integration test like below:</p>
<pre class=""lang-java prettyprint-override""><code>  @BeforeEach
    public void setUp() throws IOException {
        String baseDir = System.getProperty(&quot;user.dir&quot;);
        emulatorProcess = new ProcessBuilder()
            .command(&quot;./../gradlew&quot;, &quot;alo&quot;)
            .directory(new File(baseDir))
            .start();
    }

    @AfterEach
    public void tearDown() throws IOException {
        InputStream stdoutStream = emulatorProcess.getInputStream();
        ByteArrayOutputStream stdoutBytes = new ByteArrayOutputStream();
        stdoutBytes.write(stdoutStream.readNBytes(stdoutStream.available()));
        System.out.println(stdoutBytes.toString(StandardCharsets.UTF_8));

        if (emulatorProcess.isAlive()) {
            emulatorProcess.destroy();
        }
    }

    @Test
     void helloHttp_shouldRunWithFunctionsFramework() throws Throwable {
        String functionUrl = BASE_URL + &quot;/helloHttp&quot;;
        HttpRequest getRequest = HttpRequest.newBuilder().uri(URI.create(functionUrl)).GET().build();

        RetryRegistry registry = RetryRegistry.of(RetryConfig.custom()
            .maxAttempts(6)
            .intervalFunction(IntervalFunction.ofExponentialBackoff(200, 2))
            .retryExceptions(IOException.class)
            .retryOnResult(body -&gt; body.toString().length() == 0)
            .build());
        Retry retry = registry.retry(&quot;my&quot;);

        String body = Retry.decorateCheckedSupplier(retry, () -&gt; client.send(
            getRequest,
            HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)).body()
        ).apply();
        assertThat(body).isEqualTo(&quot;Hello world!&quot;);
    }
</code></pre>
<p>So I want to fake a params <code>name</code> in the integration test to pass to my GCP function.
so in my GCP function I can take it like this: <code> name = requestJson.get(&quot;name&quot;).getAsString();</code>. How do I do it?</p>
",https://stackoverflow.com/questions/68934054/google-cloud-function-integration-testing-pass-param,"['java', 'google-cloud-platform', 'google-cloud-functions', 'integration-testing']",55,False,0,1
"Automated integration testing in lambda support (golang, serverless)","<p>So I have a web app running in serverless. It spins up a bunch of lambdas and then a 'test' lambda is invoked at a later stage of our pipeline to run some api tests against the other lambbas. It passes or fails code pipeline depending on the result of the tests.</p>
<p>My concern is the implementation of the tests portion itself.</p>
<p>We're using golang, and I wasn't able to successfully find a way to have a bunch of go test files and run them, record the results and determine pass/fail or not.. but I wanted to use the test suite and library in order to run my assertions. So I came up with this solution which was to break about the go test library and run it myself using MainStart(), ex:</p>
<pre><code>// T is used to manage our test cases manually using MainStart
type T struct{}

func (*T) ImportPath() string                          { return &quot;&quot; }
func (*T) MatchString(pat, str string) (bool, error)   { return true, nil }
func (*T) SetPanicOnExit0(bool)                        {}
func (*T) StartCPUProfile(io.Writer) error             { return nil }
func (*T) StopCPUProfile()                             {}
func (*T) StartTestLog(io.Writer)                      {}
func (*T) StopTestLog() error                          { return nil }
func (*T) WriteHeapProfile(io.Writer) error            { return nil }
func (*T) WriteProfileTo(string, io.Writer, int) error { return nil }

func (h *Handler) Handle(ctx context.Context, event events.CodePipelineEvent) (interface{}, error) {

    job := event.CodePipelineJob
    ok := runTest()
    
    if ok {
        logger.Info(&quot;Tests Passed!&quot;)
        input := &amp;codepipeline.PutJobSuccessResultInput{
            JobId: &amp;job.ID, 
        success, err := h.service.PutJobSuccessResult(input)
        return success, err
    } else {
        logger.Info(&quot;Tests Failed :(&quot;)
        input := &amp;codepipeline.PutJobFailureResultInput{
            JobId: &amp;job.ID,
            FailureDetails: &amp;codepipeline.FailureDetails{
                Message: aws.String(&quot;tests failed&quot;),
                Type:    aws.String(&quot;JobFailed&quot;),
            },
            failure, err := h.service.PutJobFailureResult(input)
            return failure, err
        }
    }
}

// NewHandler returns a pointer to a Handler struct
func NewHandler(service *codepipeline.CodePipeline) *Handler {
    return &amp;Handler{
        service,
    }
}

// runTest returns the test results
func runTest() bool {

    testSuite := []testing.InternalTest{
        {Name: &quot;Test Service&quot;, F: TestService},
    }

    logger.Info(&quot;Running Tests&quot;)
    errors := testing.MainStart(&amp;T{}, testSuite, nil, nil).Run()

    if errors == 0 {
        return true
    } else {
        return false
    }
}
</code></pre>
<p>So the test looks like this:</p>
<pre><code>func TestServices(t *testing.T) {
    logger.Info(&quot;blah blah do tests&quot;)
}
</code></pre>
<p>And for reference, main.go contains:</p>
<pre><code>        // Initial code pipeline session
        cpSession := session.Must(session.NewSession())

        // Create the credentials from AssumeRoleProvider to assume the role
        // referenced by the &quot;putJobResultRoleArn&quot; ARN.
        creds := stscreds.NewCredentials(cpSession, &quot;putJobResultRoleArn&quot;, func(p *stscreds.AssumeRoleProvider) {
            p.RoleARN = roleArn
            p.RoleSessionName = &quot;put_job_result_session&quot;
        })

        // Create a new instance of the CodePipeline client with a session
        svc := codepipeline.New(cpSession, &amp;aws.Config{Credentials: creds})

        intTesthandler := inttest.NewHandler(
            svc,
        )

        lambda.Start(func(ctx context.Context, event events.CodePipelineEvent) (interface{}, error) {
            return intTesthandler.Handle(ctx, event)
        })
</code></pre>
<p>This works quite well, but what I don't like is:</p>
<ul>
<li>It's using an unsupported approach from golang that could break in the future</li>
<li>I have to handhold any failures, meaning if one fails, I need to write code to stop the rest of the suite (if there were more tests) from running.</li>
<li>Bit of a learning curve</li>
</ul>
<p>To note the tests I have mainly do an http request to an api endpoint and validate the response + parse/store the data.</p>
<p>Anyone have any other creative solution? Is there a repo out there that makes it simple to run integration tests in golang?</p>
<p>Cheers</p>
",https://stackoverflow.com/questions/70117474/automated-integration-testing-in-lambda-support-golang-serverless,"['go', 'lambda', 'automated-tests', 'integration-testing', 'aws-api-gateway']",113,False,1,0
Integration Testing a Node Server without much configuration,"<p>I want to set up a CI/CD workflow which includes testing my server as a whole.</p>
<p>Using node I have a couple options such as</p>
<ul>
<li>Jest,</li>
<li>Mocha,</li>
<li>Chai</li>
<li>or a different approach such as Postman/Newman.</li>
</ul>
<p>I have tried out Jest and found it very difficult to adjust my databases such as Postgres and Redis to the mock environment. In fact, I didn't get it to work at all, presumably because of all the technologies involved.</p>
<p>Is there is a tool, maybe one of the others mentioned, that takes the server as it is, without any additional configuration, calls the endpoints of the Server and gives me results, which I can then use to further take action (push/rollback/discard changes)?</p>
",https://stackoverflow.com/questions/67663974/integration-testing-a-node-server-without-much-configuration,"['node.js', 'continuous-integration', 'integration-testing', 'system-testing']",52,False,0,0
"Integration testing with MyBatis, H2 and Oracle procedures","<p>I have a stored Oracle procedure that I call like so:</p>
<pre><code>CALL MY_PROC(
        p_arg    =&gt;   #{arg,     jdbcType=INTEGER,  mode=IN},
        p_var    =&gt;   #{var,     jdbcType=VARCHAR,  mode=IN},
        p_date   =&gt;   #{date,    jdbcType=DATE,     mode=IN}
    )
</code></pre>
<p>and I have it written using <code>MyBatis</code> like so:</p>
<pre><code>&lt;!DOCTYPE mapper
        PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;
        &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;
&lt;mapper namespace=&quot;com.example.MyMapper&quot;&gt;
    &lt;update id=&quot;callMyProc&quot; statementType=&quot;CALLABLE&quot;&gt;
        CALL MY_PROC(
            p_arg    =&gt; #{arg,    jdbcType=INTEGER,  mode=IN},
            p_var    =&gt; #{var,    jdbcType=VARCHAR,  mode=IN},
            p_date   =&gt; #{date,   jdbcType=DATE,     mode=IN}
        )
    &lt;/update&gt;
&lt;/mapper&gt;
</code></pre>
<p>The procedure itself does some <code>FOR UPDATE</code> as I have to lock on rows before updating them. The code does its job but I now I wanted to write some integration tests for which I am using H2 as database. I know that in such cases I am supposed to write user-defined function to handle such occasions. I was pretty sure that writing one such as (the sql query is simplified for the sake of the question):</p>
<pre><code>CREATE ALIAS IF NOT EXISTS MY_PROC AS $$
import java.net.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.UUID;
import java.time.LocalDateTime;
@CODE
void callMyProc(Connection conn, Integer p_arg, String p_var, LocalDateTime p_date) throws Exception {
    String sqlStatement = String.format(&quot;UPDATE mytable SET myvar = '%s', mydate = '%t' WHERE myarg = %d&quot;, p_var, p_date, p_arg);
    PreparedStatement ps = conn.prepareStatement(sqlStatement);
    ps.execute();
}
$$;
</code></pre>
<p>would do the trick but unfortunately I am getting syntax errors due to MyBatis formatting:</p>
<pre><code>### The error may exist in com.example/MyMapper.xml
### The error may involve com.example.MyMapper.callMyProc
### The error occurred while executing an update
### SQL: CALL MY_PROC(                 p_arg       =&gt; ?, p_var =&gt; ?, p_date =&gt; ?  )
### Cause: org.h2.jdbc.JdbcSQLSyntaxErrorException: Błąd składniowy w wyrażeniu SQL &quot;CALL MY_PROC(
                P_ARG[*]       =&gt; ?,
                P_VAR[*]       =&gt; ?,
                P_DATE[*]       =&gt; ?
            )&quot;
Syntax error in SQL statement &quot;CALL MY_PROC(
                P_ARG[*]       =&gt; ?,
                P_VAR[*]       =&gt; ?,
                P_DATE[*]       =&gt; ?
CALL MY_PROC(
                p_arg       =&gt; ?,
                p_var[*]       =&gt; ?,
                p_date[*]       =&gt; ?
            ) [42000-200]
</code></pre>
<p>My question is, how could should I write my H2 alias for the procedure so that both MyBatis and H2 would be satisfied?</p>
",https://stackoverflow.com/questions/66713819/integration-testing-with-mybatis-h2-and-oracle-procedures,"['java', 'oracle', 'stored-procedures', 'h2', 'mybatis']",390,False,0,1
How to perform integration testing in Netty 4,"<p>In <a href=""https://www.manning.com/books/netty-in-action"" rel=""nofollow noreferrer"">Netty in Action</a>, I read about <a href=""https://netty.io/4.1/api/io/netty/channel/embedded/EmbeddedChannel.html"" rel=""nofollow noreferrer"">EmbeddedChannel</a> which can be used for unit testing.</p>
<p>My use case now goes beyond unit testing, and more of integration testing. I want to be able to start the server and then, and within the test, configure/modify the channel handlers.</p>
<p>How is such an integration test setup possible in Netty 4?</p>
",https://stackoverflow.com/questions/66159539/how-to-perform-integration-testing-in-netty-4,"['netty', 'netty4']",151,False,0,1
I can&#39;t target the Google Login for integration testing,"<p>Currently I'm trying to build out the integration testing for an app that someone else built.  I'm stuck with the Google sign in.</p>
<p>Specifically, the integration testing can't find the Google pop-up page.</p>
<p>Is there any way to use integration testing for the Google sign?</p>
<p>If not, how do I use integration to start on any page I choose for testing?</p>
<p>Please note that I have not built the app; I'm here to test the app.</p>
<p>I've tried to find a page or anything in the files and folders for the pop-up but I can't find anything.</p>
<p>I've even tried using Dart DevTools but I still can't target the sign-in page.</p>
<p>At the very least, can I bypass this step and start the integration on a different page?</p>
<p>Below is a picture of the sign-in page I'm trying to get the Flutter Integration test to interact with.  Note that it has been modified for privacy reasons.</p>
<p><a href=""https://i.stack.imgur.com/oYTdK.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/oYTdK.jpg"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/66884113/i-cant-target-the-google-login-for-integration-testing,"['flutter', 'dart', 'integration-testing', 'google-signin', 'flutter-integration-test']",199,False,3,0
Encountered org.hibernate.StaleStateException in production environment but not integration testing,"<p>Below error is encountered when the scheduled function runs in Spring Boot application, however, there is no problem in my integration test because <code>spring.jpa.hibernate.ddl-auto</code> is set to <code>create-only</code>, but I could not do the same for production server. I created the table with the following SQL statement. What could be the possible cause for this error ?</p>
<p><strong>Error</strong></p>
<pre><code>2021-11-23 18:22:37.005  INFO 26620 --- [pool-3-thread-1] com.itsedo.scheduler.ScheduledTasks      : 18:22:37: Resending all failed Delivery Orders... ... ...
Hibernate: insert into FailedDeliveryOrder (ccp_number, date, do_number, is_received, location_from, location_to, material_source, supplier, detail, status, title) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into DeliveryOrder$Product (product_description, quantity, unit_of_measurement, DeliveryOrder_ID, ProductDes_Position) values (?, ?, ?, ?, ?)
Hibernate: update DeliveryOrder$Product set DeliveryOrder_ID=?, ProductDes_Position=? where id=?
2021-11-23 18:22:37.036 ERROR 26620 --- [pool-3-thread-1] o.h.i.ExceptionMapperStandardImpl        : HHH000346: Error during managed flush [Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1]
2021-11-23 18:22:37.054  INFO 26620 --- [pool-3-thread-1] o.h.e.j.b.internal.AbstractBatchImpl     : HHH000010: On release of batch it still contained JDBC statements
2021-11-23 18:22:37.054 ERROR 26620 --- [pool-3-thread-1] o.s.s.s.TaskUtils$LoggingErrorHandler    : Unexpected error occurred in scheduled task.

org.springframework.orm.ObjectOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:320) ~[spring-orm-4.3.5.RELEASE.jar:4.3.5.RELEASE]
HibernateJpaDialect.java:320
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244) ~[spring-orm-4.3.5.RELEASE.jar:4.3.5.RELEASE]
HibernateJpaDialect.java:244
</code></pre>
<p><strong>SQL to create table</strong></p>
<pre><code>CREATE TABLE FAILEDDELIVERYORDER (
    id BIGINT,
    ccp_number VARCHAR(255),
    date VARCHAR(255),
    do_number VARCHAR(255),
    is_received BIT,
    location_from VARCHAR(255),
    location_to VARCHAR(255),
    material_source VARCHAR(255),
    supplier VARCHAR(255),
    detail VARCHAR(255),
    status VARCHAR(255),
    title VARCHAR(255)
);

CREATE TABLE DeliveryOrder$Product (
    id BIGINT,
    product_description VARCHAR(255),
    quantity VARCHAR(255),
    unit_of_measurement VARCHAR(255),
    deliveryorder_id BIGINT,
    productdes_position INTEGER(10)
);

ALTER TABLE DeliveryOrder$Product
ADD FOREIGN KEY (deliveryorder_id) REFERENCES FAILEDDELIVERYORDER(id);
</code></pre>
<p><strong>Scheduled function</strong></p>
<pre><code>@Scheduled(cron = &quot;* * * * * *&quot;)
    public void resendFailedDeliveryOrder() {
        logger.info(&quot;{}: Resending all failed Delivery Orders... ... ...&quot;, dateFormat.format(new Date()));
        // create Delivery Order Object
        List&lt;DeliveryOrder.Product&gt; product = new ArrayList&lt;DeliveryOrder.Product&gt;();
        product.add(new DeliveryOrder.Product());
        DeliveryOrder deliveryOrder = new DeliveryOrder(product);
        FailedDeliveryOrder failedDO_1 = new FailedDeliveryOrder(deliveryOrder);
        failedDeliveryOrderRepository.save(failedDO_1);
    }
</code></pre>
<p><strong>FailedDeliveryOrder.java</strong></p>
<pre><code>@Table(name = &quot;FailedDeliveryOrder&quot;)
@Entity
public class FailedDeliveryOrder {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Embedded
    private DeliveryOrder deliveryOrder;    

    public FailedDeliveryOrder() {
    }

    public FailedDeliveryOrder(DeliveryOrder deliveryOrder) {
        this.deliveryOrder = deliveryOrder;
    }
    //setter and getter
}
</code></pre>
<p><strong>DeliveryOrder.java</strong></p>
<pre><code>public class DeliveryOrder {    
    @Entity
    public static class Product {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private Long id;
        public Product() {}
        // setter and getter
    }

    @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.ALL})
    @JoinColumn(
        name = &quot;DeliveryOrder_ID&quot;,
        nullable = false
    )
    @OrderColumn(
        name = &quot;ProductDes_Position&quot;,
        nullable = false
    )
    private List&lt;Product&gt; product_descriptions = new ArrayList&lt;Product&gt;();

    public DeliveryOrder() {
    }

    public DeliveryOrder(List&lt;Product&gt; products) {
        this.setProduct_descriptions(products);
    }   

    public List&lt;Product&gt; getProduct_descriptions() {
        return product_descriptions;
    }

    public void setProduct_descriptions(List&lt;Product&gt; product_descriptions) {
        this.product_descriptions = product_descriptions;
    }
}
</code></pre>
",https://stackoverflow.com/questions/70081627/encountered-org-hibernate-stalestateexception-in-production-environment-but-not,"['sql', 'spring', 'spring-boot', 'hibernate', 'jpa']",122,False,1,0
Spring boot multiple database cause NoSuchBeanDefinitionException by integration testing,"<p>By configuring application to use two datasource instances, it cause an issue in one of my integration tests with the following message - &quot;Unsatisfied dependency expressed through method 'entityManagerFactoryBean' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}&quot;</p>
<p>Here is the bean that stores the information for both database instances:</p>
<pre><code>@Component
public class DataSourceRouting extends AbstractRoutingDataSource {
    private final DataSourcePrimeConfig dataSourcePrimeConfig;
    private final DataSourceSecondConfig dataSourceSecondConfig;
    private final DataSourceContextHolder dataSourceContextHolder;

    public DataSourceRouting(DataSourceContextHolder dataSourceContextHolder, DataSourcePrimeConfig dataSourcePrimeConfig,
                             DataSourceSecondConfig dataSourceSecondConfig) {
        this.dataSourcePrimeConfig = dataSourcePrimeConfig;
        this.dataSourceSecondConfig = dataSourceSecondConfig;
        this.dataSourceContextHolder = dataSourceContextHolder;

        Map&lt;Object, Object&gt; dataSourceMap = new HashMap&lt;&gt;();
        dataSourceMap.put(DataSourceEnum.DATASOURCE_PRIME, dataSourceOneDataSource());
        dataSourceMap.put(DataSourceEnum.DATASOURCE_SECOND, dataSourceTwoDataSource());
        this.setTargetDataSources(dataSourceMap);
        this.setDefaultTargetDataSource(dataSourceOneDataSource());
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return this.dataSourceContextHolder.getBranchContext();
    }

    public DataSource dataSourceOneDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl(dataSourcePrimeConfig.getUrl());
        dataSource.setUsername(dataSourcePrimeConfig.getUsername());
        dataSource.setPassword(dataSourcePrimeConfig.getPassword());
        return dataSource;
    }

    public DataSource dataSourceTwoDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl(dataSourceSecondConfig.getUrl());
        dataSource.setUsername(dataSourceSecondConfig.getUsername());
        dataSource.setPassword(dataSourceSecondConfig.getPassword());
        return dataSource;
    }
}
</code></pre>
<p>Here is the configuration class:</p>
<pre><code>@Configuration
@EnableJpaRepositories(basePackages = &quot;test.project.repository&quot;, transactionManagerRef = &quot;transcationManager&quot;, entityManagerFactoryRef = &quot;entityManager&quot;)
@EnableTransactionManagement
@RequiredArgsConstructor
@DependsOn(&quot;dataSourceRouting&quot;)
public class DataSourceConfig {
    private final DataSourceRouting dataSourceRouting;

    @Bean
    @Primary
    public DataSource dataSource() {
        return dataSourceRouting;
    }

    @Bean(name = &quot;entityManager&quot;)
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(dataSource()).packages(&quot;test.project&quot;).build();
    }

    @Bean(name = &quot;transcationManager&quot;)
    public JpaTransactionManager transactionManager(
            @Autowired @Qualifier(&quot;entityManager&quot;) LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) {
        return new JpaTransactionManager(entityManagerFactoryBean.getObject());
    }
}
</code></pre>
<p>And here is the failing test:</p>
<pre><code>@SpringBootTest
@Import(value = DataSourceConfig.class)
@RunWith(SpringRunner.class)
@ActiveProfiles(&quot;test&quot;)
public class MailBodyProviderServiceTest {
    @Autowired
    private MailService mailService;

    @Autowired
    private ReportService reportService;

    @MockBean
    private JPATransactionDataRepository jpaTransactionDataRepository;

    @Autowired
    private MailBodyBuilder builder;

    @Autowired
    private DataSourceRouting dataSourceRouting;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private LocalContainerEntityManagerFactoryBean entityManagerFactoryBean;

    @Autowired
    private JpaTransactionManager jpaTransactionManager;

    @Autowired
    private EntityManagerFactoryBuilder entityManagerFactoryBuilder;

    @Rule
    public SmtpServerRule smtpServerRule = new SmtpServerRule(2525);

    @Test
    public void shouldSendSingleMail() throws MessagingException {

        when(this.jpaTransactionDataRepository.mapTransactionData()).thenReturn(generateReportData());
        mailService.sendEmail(new ReportEvent(this, &quot;report event&quot;, EventType.CREDIT_CARD));

        MimeMessage[] receivedMessages = smtpServerRule.getMessages();
        assertEquals(3, receivedMessages.length);

        MimeMessage current = receivedMessages[0];
        String contentType = current.getContentType();
        assertTrue(contentType.contains(&quot;multipart&quot;));
    }

    private static Map&lt;Date, List&lt;TransactionDto&gt;&gt; generateReportData(){

        Date today = new Date();

        List&lt;Object[]&gt; objects = new ArrayList&lt;&gt;();
        Object[] object1 = new Object[] { today, AuthStatus.AUTH_CONFIRMED.name(), ProcessingType.DIRECT.name(), BigDecimal.valueOf(10l)};
        Object[] object2 = new Object[] { today, AuthStatus.AUTH_REJECTED.name(), ProcessingType.DIRECT.name(), BigDecimal.valueOf(10l)};
        Object[] object3 = new Object[] { new Date(today.getTime() + (1000 * 60 * 60 * 24)), AuthStatus.AUTH_CANCELED.name(), ProcessingType.TAN.name(), BigDecimal.valueOf(10l)};
        Object[] object4 = new Object[] { new Date(today.getTime() + (1000 * 60 * 60 * 24)), AuthStatus.AUTH_FAILED.name(), ProcessingType.TAN.name(), BigDecimal.valueOf(10l)};
        objects.add(object1);
        objects.add(object2);
        objects.add(object3);
        objects.add(object4);

        return TransactionMapper.mapFromDatabaseQuery(objects);
    }
}
</code></pre>
<p>I try with @TestConfiguration, also to exclude DataSourceConfig, but nothing helps. Hope someone to have idea what I do wrong or miss :)</p>
",https://stackoverflow.com/questions/68406320/spring-boot-multiple-database-cause-nosuchbeandefinitionexception-by-integration,"['spring-boot', 'unit-testing', 'jpa']",129,False,0,0
How to perform integration testing on AWS Step Function,"<p>I have a REST API in API Gateway with lambda proxy integration. The Lambda will invoke a Step Function workflow asynchronously and will return an ID in the payload. These AWS resources are deployed and managed by AWS CDK.</p>
<p>My question is, is there a proper way to perform integration test? There are two approaches I have in mind:</p>
<ol>
<li>Call the REST API endpoint, and make assertions on side effects. But since the workflow is executed asynchronously, the test needs to continuously poll until side effects become visible.</li>
<li>According to this blog <a href=""https://www.10printiamcool.com/step-function-integration-testing-with-cdk"" rel=""nofollow noreferrer"">https://www.10printiamcool.com/step-function-integration-testing-with-cdk</a>, it seems like we can use CDK to deploy a test stack with mocking the dependent resources (e.g Lambda). But this sounds more of like unit test.</li>
</ol>
<p>I am not sure if there are any better options. Any thoughts?</p>
",https://stackoverflow.com/questions/70376822/how-to-perform-integration-testing-on-aws-step-function,"['amazon-web-services', 'integration-testing', 'aws-step-functions']",1090,True,0,1
Best practice for integration testing in React Redux app?,"<p>I'm trying to set up tests for a React-Redux application. Most resources including <a href=""https://redux.js.org/usage/writing-tests"" rel=""nofollow noreferrer"">Redux Docs</a>, and <a href=""https://kentcdodds.com/blog/testing-implementation-details"" rel=""nofollow noreferrer"">the main contributor to react-testing-library</a> argues for a focus on integration tests and that the Redux code as far as possible should be considered an implementation detail. That's cool and all, but I'm struggling to do this in practice.</p>
<p>Most examples I've found on integration testing sets up a component where you can observe the effect in the immediate unit. But several places in my app, I have components that send dispatches to my store which causes a re-render in another part of the app. To illustrate my question, I've made a simplified component tree below where I want to click the <code>AddToListButton</code> to cause <code>Element1</code> to be added to the <code>List</code>.</p>
<p>If Redux is an implementation detail, how do I actually test that clicking the button causes the update without rendering (more or less) the whole app? I understand how to do unit-testing and end-to-end testing, but not sure how I would implement integration testing.</p>
<pre><code>&lt;App&gt;
  &lt;Search&gt;
    &lt;SearchResult&gt;
      &lt;Element1&gt;
        &lt;AddToListButton /&gt; //I WANT TO TEST THIS BUTTON
      &lt;/Element1&gt;
      &lt;Element2&gt;
        &lt;AddToListButton /&gt;
      &lt;/Element2&gt; 
    &lt;/SearchResult&gt;
  &lt;/Search&gt;
  &lt;List&gt;
    &lt;Element1 /&gt; // WHEN THE BUTTON IS PRESSED THE ELEMENT SHOULD GO HERE
  &lt;/List&gt;
&lt;/App&gt;

</code></pre>
",https://stackoverflow.com/questions/68939827/best-practice-for-integration-testing-in-react-redux-app,"['reactjs', 'redux', 'react-testing-library']",128,True,0,1
tester.scrollUntilVisible() not working with GridView in flutter integration testing,"<p>I am trying to scroll and find widget from the GridView in <code>integration testing</code> in flutter. But the code not working:</p>
<pre><code>tester.scrollUntilVisible(itemFinder, -100, scrollable: gridViewFinder)
</code></pre>
<p>But this is not working. It is saying GridView is not scrollable.</p>
",https://stackoverflow.com/questions/67751896/tester-scrolluntilvisible-not-working-with-gridview-in-flutter-integration-tes,"['flutter', 'gridview', 'integration-testing']",2146,True,0,1
Integration testing in multi module Maven project with Spring,"<p>I have a multi module maven project with several modules (parent, service, updater1, updater2).
The @SpringBootApplication is in 'service' module and the others doesn't have artifacts.</p>
<p>'updater1' is a module which have a Kafka listener and a http client, and when receives a kafka event launches a request to an external API. I want to create integration tests in this module with <code>testcontainers</code>, so I've created the containers and a Kafka producer to send a KafkaTemplate to my consumer.</p>
<p>My problem is the Kafka producer is autowiring to null, so the tests throws a NullPointerException. I think it should be a Spring configuration problem, but I can't find the problem. Can you help me? Thank's!</p>
<p>This is my test class:</p>
<pre><code>@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {KafkaConfiguration.class, CacheConfiguration.class, ClientConfiguration.class})
public class InvoicingTest {

@ClassRule
public static final Containers containers = Containers.Builder.aContainer()
        .withKafka()
        .withServer()
        .build();

private final MockHttpClient mockHttpClient =
        new MockHttpClient(containers.getHost(SERVER),
                containers.getPort(SERVER));

@Autowired
private KafkaEventProducer kafkaEventProducer;

@BeforeEach
@Transactional
void setUp() {
    mockHttpClient.reset();
}

@Test
public void createElementSuccesfullResponse() throws ExecutionException, InterruptedException, TimeoutException {

    mockHttpClient.whenPost(&quot;/v1/endpoint&quot;)
            .respond(HttpStatusCode.OK_200);

    kafkaEventProducer.produce(&quot;src/test/resources/event/invoiceCreated.json&quot;);

    mockHttpClient.verify();

}
</code></pre>
<p>And this is the event producer:</p>
<pre><code>@Component
public class KafkaEventProducer {

private final KafkaTemplate&lt;String, String&gt; kafkaTemplate;

private final String topic;

@Autowired
KafkaInvoicingEventProducer(KafkaTemplate&lt;String, String&gt; kafkaTemplate,
                            @Value(&quot;${kafka.topic.invoicing.name}&quot;) String topic){
    this.kafkaTemplate = kafkaTemplate;
    this.topic = topic;
}

public void produce(String event){
    kafkaTemplate.send(topic, event);
}
</code></pre>
<p>}</p>
",https://stackoverflow.com/questions/67306006/integration-testing-in-multi-module-maven-project-with-spring,"['java', 'spring', 'maven', 'multi-module', 'testcontainers']",583,True,0,1
Spring Boot Integration Testing - Mocking @Service before Application Context Starts?,"<p>I have to create a integration test for a microservice X which downloads, processes and importing csv files from external sftp servers. The whole process is started by a spring boot scheduler task which starts a spring batch job for processing and importing the data. The import process is done by the spring batch writer, which is a restTemplate Repository (so it calls post requests to another microservice Y).</p>
<p>I already managed to mock the sftp server, putting a test file on it and the current integration test is downloading the file. (<a href=""https://github.com/stefanbirkner/fake-sftp-server-rule/"" rel=""nofollow noreferrer"">https://github.com/stefanbirkner/fake-sftp-server-rule/</a>)</p>
<p>My problem is, that the task will be scheduled immediately when the application context starts so there is no trigger like a api call. To get the whole integration test working i have to mock the part where the external microservice Y is called through a restTemplate call. This repository is called in the spring batch writer and this repository is created by a repositoryFactory which is a @Service. The repositoryFactory is injected in the spring batch configuration class.</p>
<p>I already tried to use the @MockBean annotation in the test class as well as in a separate test configuration where i am mocking the create() function of the factory to deliver a repository mock. But at some point it does not work and it delivers still the original object which leads to interupt the import job.</p>
<p>I also tried to use the WireMock library, but also in this case it does not catched any api calls and at some point leads to interrupt the sftp socket. (?)</p>
<p>I hope someone could help me out.</p>
<p>The current test:</p>
<pre><code>@NoArgsConstructor
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = {JsonHalConfig.class})
@TestPropertySource(locations = &quot;classpath:application-test.properties&quot;)
@TestMethodOrder(MethodOrderer.MethodName.class)
public class ImportIT {

    @ClassRule
    public static final FakeSftpServerRule sftpServer = new FakeSftpServerRule();
    private static final String PASSWORD = &quot;password&quot;;
    private static final String USER = &quot;username&quot;;
    private static final int PORT = 14022;

    @BeforeClass
    public static void beforeClass() throws IOException {
        URL resource = getTestResource();
        if (resource != null) {
            sftpServer.setPort(PORT).addUser(USER, PASSWORD);
            sftpServer.createDirectories(&quot;/home/username/it-space/IMPORT&quot;, &quot;/home/username/it-space/EXPORT&quot;);
            sftpServer.putFile(&quot;/home/username/it-space/IMPORT/INBOX/testFile.csv&quot;,
                    resource.openStream());
        } else {
            throw new IOException(&quot;Failed to get test resources&quot;);
        }
    }

    private static URL getTestResource() {
        return ImportIT.class.getClassLoader().getResource(&quot;testFile.csv&quot;);
    }

    @Test
    public void test_A_() throws IOException, RepositoryException {
        assertTrue(true);
    }
}

</code></pre>
<p>I tried following configuration classes</p>
<p>(included in @ContextConfiguration)</p>
<pre><code>@Configuration/@TestConfiguration
public class RepositoryTestConfig {
    @Bean
    @Primary
    public IRepositoryFactory repositoryFactory() {
        IRepositoryFactory repositoryFactory = mock(IRepositoryFactory.class);
        IRepository repository = mock(IRepository.class);
        when(repositoryFactory.create(anyString())).thenReturn(repository);
        return repositoryFactory;
    }
}
</code></pre>
<p>(as static class in the test class)</p>
<pre><code>    @TestConfiguration/@Configuration
    public static class RepositoryTestConfig {
        @MockBean
        private IRepositoryFactory repositoryFactory;

        @PostConstruct
        public void initMock(){
            IRepository repository = mock(IRepository.class);
            Mockito.when(repositoryFactory.create(anyString())).thenReturn(
                    repository
            );
        }
    }
</code></pre>
<hr />
<p><strong>UPDATE 27.08.2021</strong>
I have a RestConfig @Component where a new RestTemplateBuilder is created. I tried to @MockBean this component to deliver a RestTemplateBuilder Mock and injected a MockRestServiceServer object to catch outgoing api calls. But unfortunately it does not work as aspected. Am i missing something? I also tried to create a &quot;TestRestController&quot; to trigger the scheduling of the task but it never delivers the mock...</p>
",https://stackoverflow.com/questions/68940583/spring-boot-integration-testing-mocking-service-before-application-context-st,"['java', 'spring', 'spring-boot', 'mocking', 'integration-testing']",2384,True,4,1
Integration testing loadUser call on custom OidcUserService in Spring Security,"<p>I have the following class that extends <code>OidcUserService</code>:</p>
<pre class=""lang-java prettyprint-override""><code>@Service
public class CustomOidcUserService extends OidcUserService {
    private final UserProfileService profileService;

    public CustomOidcUserService(UserProfileService profileService) {
        this.profileService = profileService;
    }

    @Override
    public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
        var id = UUID.fromString(userRequest.getIdToken().getSubject());
        var preferredUsername = userRequest.getIdToken().getPreferredUsername();

        var profile = profileService.findByUserId(id)
                .orElseGet(() -&gt; profileService.createProfile(id, preferredUsername));

        return new CustomUser(super.loadUser(userRequest), profile);
    }
}
</code></pre>
<p>Simple enough so far and it works fine when I run the application, however, I would like to test that this service is indeed working correctly. I've written the following integration test:</p>
<pre class=""lang-java prettyprint-override""><code>@SpringBootTest
class CustomOidcUserServiceTests {
    @MockBean
    private UserProfileService profileService;

    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;

    @BeforeEach
    public void setup() {
        mvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply(springSecurity())
                .build();
    }

    @Test
    public void whenLoadNewUser_createNewProfile() throws Exception {
        when(profileService.findByUserId(any())).thenReturn(Optional.empty());
        when(profileService.createProfile(any(UUID.class), anyString())).thenAnswer(i -&gt; {
            var id = i.getArgument(0, UUID.class);
            var displayName = i.getArgument(1, String.class);
            return new UserProfile(id, displayName);
        });

        mvc.perform(get(&quot;/organizations/create&quot;)
                .with(oidcLogin().idToken(token -&gt; {
                    token.claim(IdTokenClaimNames.SUB, UUID.randomUUID());
                    token.claim(&quot;preferred_username&quot;, &quot;testuser&quot;);
                })));

        assertThat(mockingDetails(profileService).getInvocations().size()).isEqualTo(2);
    }
}
</code></pre>
<p>However, the <code>loadUser</code> method is never called. How can I write a test that calls the <code>loadUser</code> method?</p>
",https://stackoverflow.com/questions/70354161/integration-testing-loaduser-call-on-custom-oidcuserservice-in-spring-security,"['java', 'spring-boot', 'testing', 'spring-security', 'spring-security-oauth2']",279,False,3,1
Integration testing concurrent idempotency in Grails 4 and Spock failing,"<p>I am running into some trouble with transactions &amp; hibernate sessions while testing concurrency in an integration test.</p>
<p>Essentially we have a process that updates a few different database entries including some accounting entries. This process should be idempotent for a given id, including when being called concurrently from different threads.</p>
<p>I am trying to update an old test that hasn't worked for a while to work in Grails 4.0.12. This test last worked in Grails 2.x.</p>
<p>The code below is generalized for simplicity.</p>
<pre><code>void testName() {
    given:
    Thing thing = Thing.findAll(someId)[0]
    int attemptsPerThing = 5
    
    when:
    def pool = Executors.newFixedThreadPool(attemptsPerThing)
    List&lt;Future&gt; futureList = []
    
    for (int i = 0; i &lt; attemptsPerThing; i++) {
        Future future = pool.submit({
            try {
                serviceToBeTested.functionToBeTestedThatCommitsThingsToDB(thing)
            } catch (Exception _) {}
        })
        futureList.add(future)
    }
    
    for (Future future in futureList) {
        def futureResults = future.get()
        assert futureResults == null
    }
    
    pool.shutdown()
    assert pool.awaitTermination(60, TimeUnit.SECONDS)

    sessionFactory.currentSession.clear()
    
    then:
    // QUERY DATABASE AND ASSERT THAT THE CALL ONLY COMPLETED ONCE AND DATA IS AS EXPECTED
}
</code></pre>
<p>This test fails. Upon initial investigation it looks to be failing because nothing within the future closures gets committed in a way that is visible within the test. It looks as if the function was never called.</p>
<p>Upon interrogating the exception caught in that try block I can see that all the iterations are actually failing with an exception unrelated to the business logic. The exception is:</p>
<pre><code>org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions. Collection : [com.kiind.coreservices.KiindUser.paymentInfoByCurrency#70]
</code></pre>
<p>The above <code>com.kiind.coreservices.KiindUser.paymentInfoByCurrency</code> is a collection of domain objects that live in the database but are only read in this function.</p>
<p>So my question is, is there a best practice for testing concurrency in Grails 4 / Spock? Is it bad practice to test concurrency in an integration test?</p>
<p>Specifically, is there a way to attach the test's hibernate session to the threads so that they can all share it? Or get the threads to work with their own session, complete their transactions, and then update the session in the test with the current state of the database during the <code>then</code>?</p>
<p>Thanks for any assistance and let me know if additional information is required.</p>
",https://stackoverflow.com/questions/69636031/integration-testing-concurrent-idempotency-in-grails-4-and-spock-failing,"['hibernate', 'grails', 'concurrency', 'integration-testing', 'grails-orm']",142,True,2,2
Why is IConfiguration null when integration testing my Azure Functions?,"<p>The current version of the <a href=""https://www.nuget.org/packages/Microsoft.Azure.Functions.Extensions/"" rel=""nofollow noreferrer"">Microsoft.Azure.Functions.Extensions</a> package exposes an additional property that allows you easy access to the <code>IConfiguration</code> provided to the function. Previously this required manually building a service provider, which was obviously problematic.</p>
<p>Using that package my <code>FunctionsStartup.cs</code> looks like this:</p>
<pre><code>public override void Configure(IFunctionsHostBuilder builder)
{
    base.Configure(builder);

    var config = builder.GetContext().Configuration; // new in v1.1.0 of Microsoft.Azure.Functions.Extensions
    var mySetting = config[&quot;MySetting&quot;];

    int.Parse(mySetting, out var mySetting);

    // ... use mySetting...
}
</code></pre>
<p>In order to test my HTTP-triggered functions I've used <a href=""https://saebamini.com/integration-testing-in-azure-functions-with-dependency-injection/"" rel=""nofollow noreferrer"">this article</a> as a base, which details how to manually build and start a host to execute my function as if it was running in Azure, similar to how <code>TestServer</code> works in ASP.NET Core:</p>
<pre><code>var host = new HostBuilder()
    .ConfigureWebJobs(new FunctionsStartup().Configure)
    .Build();

var functionsInstance = ActivatorUtilities.CreateInstance&lt;MyFunctions&gt;(host.Services);
</code></pre>
<p>I can then execute the function methods defined on <code>MyFunctions</code> to test their responses:</p>
<pre><code>var request = new DefaultHttpRequest(new DefaultHttpContext());

var response = (OkObjectResult)functionsInstance.HttpTriggerMethod(request);

... assert that response is valid
</code></pre>
<p>The problem is that when I run my tests, <code>builder.GetContext().Configuration</code> is returning <code>null</code> in <code>FunctionsStartup.Configure</code>, which of course causes those tests to fail. How can I work around this?</p>
",https://stackoverflow.com/questions/68591196/why-is-iconfiguration-null-when-integration-testing-my-azure-functions,"['c#', 'azure', 'azure-functions']",836,True,2,1
build.sbt it:test is not working for integration testing junit cases,"<p>I am new to scala,
junit test cases are not running in integration test.</p>
<p>folder structure</p>
<pre><code>src
  |- it
  |- main
  |- test
</code></pre>
<p>when i do <code>sbt test</code> all the test cases in &quot;test&quot; folder is executed fine,
but when i do <code>it:test</code></p>
<pre><code>[error] No such setting/task
[error] it:test
[error] 
</code></pre>
<p>where <code>it</code> folder contain Tester.scala</p>
<pre><code>        package RegexExtractor
        import org.junit.Assert.assertTrue
        import org.junit.Test
            
class  Tester   {
             @Test
     def testAdd1(): Unit = {
      val result = 2 + 4
      assertTrue(result == 6)
      System.out.println(&quot;Test final Passed&quot;)
     }
    }
    }
</code></pre>
<p>i added in build.sbt</p>
<pre><code>lazy val scalatest = &quot;org.scalatest&quot; %% &quot;scalatest&quot; % &quot;3.0.5&quot;
lazy val root = (project in file(&quot;.&quot;))
  .configs(IntegrationTest)
  .settings(
    Defaults.itSettings,
    libraryDependencies += scalatest % &quot;it,test&quot;,

    // other settings here

  )
</code></pre>
<p>Please help me for running integration test</p>
",https://stackoverflow.com/questions/70197167/build-sbt-ittest-is-not-working-for-integration-testing-junit-cases,"['java', 'scala', 'junit', 'sbt', 'integration-testing']",344,False,1,1
Is Injecting Repository dependency in Integration Testing is bad practice,"<p>I am developing REST CURD API using Spring Boot and following TDD. I am starting with READ operation to test the READ works I have to prepopulate data in my DB. For this purpose I am using H2 DB and created my Repository and using this Repository in my Integration testing Setup step to populate the data before my GET actual data being executed. My college told me its bad practice using Repository in integration testing to create data for this GET operation test instead he suggested to call POST API endpoint in Setup step and Execute GET test also implement PUT and DELETE IT tests.</p>
<p>My question is</p>
<ol>
<li>Is injecting actual repository for purpose of data setup in Integration test class is wrong?</li>
<li>Can we use/call and Endpoint (POST) in setup or in GET testcase before actual Test logic being executed?</li>
<li>Can we call POST endpoint in init/setup and populate the data instead using Repository and implement GET,PUT,DELETE tests using POST data? Is advisable calling direct POST endpoint in setup for purpose of testing another endpoint in Test class and using @TestOrder annotation on class level.</li>
</ol>
<p>Case 1</p>
<pre><code>@SpringBootTest
@AutoConfigureMockMvc
public class CURDTest() {
 
  @Autowired
  private TestMovieRepository testMovieRepository;

  @BeforeEach
  void init() {
   Movie myMovie = new Movie(&quot;test&quot;);
   testMovieRepository.save(myMovie);
}

@Test
void getMovie_whenReturnsMovie(){
  //Test logic using mockMvc;
}
}
</code></pre>
<p>Case 2:</p>
<pre><code>@SpringBootTest
@AutoConfigureMockMvc
public class CURDTest() {
 
  
  @BeforeEach
  void init() {
   //call POST Endpoint usin MockMvc populate data in table
}

@Test
void getMovie_whenReturnsMovie(){
  //Test logic using mockMvc;
}
}

</code></pre>
<p>Case 3:</p>
<pre><code>@SpringBootTest
@AutoConfigureMockMvc
@TestOrder
public class CURDTest() {
 
  
  @BeforeEach
  void init() {
   //call POST Endpoint usin MockMvc populate data in table
}

@Test
@Order(1)
void getMovie_whenReturnsMovie(){
  //Test logic using mockMvc;
}

@Test
@Order(2)
void updateMovie_whenReturnsMovie(){
  //Test logic using mockMvc;
}

}
</code></pre>
",https://stackoverflow.com/questions/66000350/is-injecting-repository-dependency-in-integration-testing-is-bad-practice,"['spring-boot', 'junit5', 'spring-test']",62,False,1,0
Stopping Karate mock server at the end of Integration testing,"<p>I am using Karate to do integration testing for a Spring Boot app. The app consumes two other services (Service A and Service B) . I have written Karate mocks for Service A and B.  My integration tests are written as two different feature files. One of the feature is tested using Mocks for service A and B. Another feature uses Mocks for service B and Spring Contract Stubs for service A.</p>
<p><strong>Feature with only mocks</strong></p>
<pre><code> Feature: Test Some feature

  Background:
    * configure headers = { Content-Type: 'application/json' }
    * url baseUrl

 #Start up the mocks
  Scenario: Start the Mocks
    * karate.start({ mock: '../mock/service/service-a.feature', port: 9000})
    * karate.start({ mock: '../mock/service/service-b.feature', port: 9001})
</code></pre>
<p><strong>Feature with mocks and Spring Contract stubs</strong></p>
<pre><code> Feature: Test Some more features

  Background:
    * configure headers = { Content-Type: 'application/json' }
    * url baseUrl

 #Start up the mocks
  Scenario: Start the Mocks
    # Service A will use Spring Contract stubrunner. 
    * karate.start({ mock: '../mock/service/service-b.feature', port: 9001})
</code></pre>
<p>Now, when we run the tests, the second one fails saying that the port is already used.  I tried using <code>karate.stop(9000)</code> at the end of the feature file which is running first, but it does not help. Also,  I am not sure about the behaviour of this stop method.  Any suggestions to solve this problem ? Why the mock service is still running even after the tests are done ?</p>
",https://stackoverflow.com/questions/68469723/stopping-karate-mock-server-at-the-end-of-integration-testing,"['java', 'spring-boot', 'integration-testing', 'karate']",924,True,1,1
Unable to resolve a type in Integration Testing using WebApplicationFactory,"<p>This is the problem I have: <code>InvalidOperationException: Unable to resolve service for type 'WebApi.Test.Repository.TestRepository' while attempting to activate 'WebApi.Test.Services.TestService'.</code></p>
<p>Of course, the problem is, It seems I cant construct a <code>TestRepository</code>, when the service needs it.</p>
<p>This is the Repo:</p>
<pre><code>public class TestRepository : GenericRepository&lt;TestEntity&gt;
{
    public TestRepository(TestContext dbContext
        , ILoggerFactory loggerFactory) : base(dbContext, loggerFactory)
    {
    }
}
</code></pre>
<p>The service basically has a <code>TestRepository</code> as a parameter in its constructor (but the issue seems to be before that).</p>
<p>This is my custom <code>WebApplicationFactory</code></p>
<pre><code>public class ApiWebApplicationFactory : WebApplicationFactory&lt;Startup&gt;
    {
        public IConfiguration Configuration { get; private set; }

        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration(config =&gt;
            {
                Configuration = new ConfigurationBuilder()
                    .AddJsonFile(&quot;appsettings.json&quot;)
                    .Build();

                config.AddConfiguration(Configuration);
            });


            //Add Services
            builder.ConfigureTestServices(services =&gt;
            {
                // Add framework services.
                services.AddMvc();

                //Add ApplicationDbContext using an in-memory database for testing.
                services.AddDbContext&lt;TestContext&gt;(options =&gt;
                    options.UseInMemoryDatabase(&quot;InMemoryDbForTesting&quot;));

                services.AddAutoMapper(typeof(Startup));

                // Build the service provider.
                var serviceProvider = services.BuildServiceProvider();

                // Create a scope to obtain a reference to the database
                // context (ApplicationDbContext).
                using var scope = serviceProvider.CreateScope();

                var db = scope.ServiceProvider.GetRequiredService&lt;TestContext&gt;();

                // Ensure the database is created.
                db.Database.EnsureCreated();

                // Seed the database with test data.
                InitializeTestDatabase(db);

                
                services.AddScoped&lt;GenericRepository&lt;TestEntity&gt;, TestRepository&gt;();
                services.AddScoped&lt;GenericService&lt;TestEntity, TestRequest, TestResponse&gt;, TestService&gt;();
                services.AddScoped&lt;GenericController&lt;TestEntity, TestRequest, TestResponse&gt;, TestController&gt;();
            });
        }

        private void InitializeTestDatabase(TestContext textContext)
        {
            textContext.TestEntities.Add(new TestEntity { Id = 1 });
        }
    }
</code></pre>
<p>All the Generic classes are abstract classes. This is the <code>GenericRepository</code>:</p>
<pre><code>public abstract class GenericRepository&lt;T&gt; : IGenericRepository&lt;T&gt;
        where T : BaseEntity
    {
        protected DbContext _context;
        private DbSet&lt;T&gt; _table;
        private ILogger _logger;

        public GenericRepository(DbContext context
            , ILoggerFactory loggerFactory)
        {
            _context = context;
            _table = context.Set&lt;T&gt;();
            _logger = loggerFactory.CreateLogger&lt;GenericRepository&lt;T&gt;&gt;();
        } 

         //CRUD Methods
    }
</code></pre>
<p>I was thinking if it is because Im not creating the ILoggerFactory on my Custom WebAppFactory, if that is the case, how can someone create an ILoggerFactory?.</p>
<p>What I tried:
I tried to add the following line:</p>
<pre><code>services.AddScoped&lt;DbContext, TestContext&gt;();
</code></pre>
<p>but I keep getting the same error.</p>
<p>This is the Service:</p>
<pre><code>public abstract class GenericService&lt;T, Request, Response&gt;
    where T : BaseEntity
    where Response : class, IResponseDto
    where Request : class, IRequestDto
{
    protected readonly GenericRepository&lt;T&gt; _genericRepository;
    protected readonly IMapper _mapper;
    protected readonly ILogger _logger;
    public GenericService(GenericRepository&lt;T&gt; genericRepository
        , IMapper mapper
        , ILoggerFactory loggerFactory)
    {
        _genericRepository = genericRepository;
        _mapper = mapper;
        _logger = loggerFactory.CreateLogger&lt;GenericService&lt;T, Request, Response&gt;&gt;();
    }

    //Methods
}
</code></pre>
",https://stackoverflow.com/questions/68564116/unable-to-resolve-a-type-in-integration-testing-using-webapplicationfactory,"['c#', 'dependency-injection', 'asp.net-core-3.1']",499,False,0,0
.NET Core C# web API integration testing an inmemory database,"<p>I'm currently trying to create an integration test for my .NET Core Web API.
I'm following the advice here:
<a href=""https://timdeschryver.dev/blog/how-to-test-your-csharp-web-api"" rel=""nofollow noreferrer"">https://timdeschryver.dev/blog/how-to-test-your-csharp-web-api</a></p>
<p>When I run my test to check the HttpStatusCode 'Should' 'Be' ok, the test is failing BUT the test does pass if I use the '/weatherforecast' example that comes with the .NET Core Web API template. If I use my project, the test fails. Is this because I have no values created in the DB when I start the app? How do I create those values? The code for my test is below:</p>
<pre><code>            [Fact]
    public async Task Get_Should_Retrieve_Score()
    {
        var response = await Client.GetAsync(&quot;/diceroll&quot;);
        response.StatusCode.Should().Be(HttpStatusCode.OK);

        //var DiceRoll = JsonConvert.DeserializeObject&lt;DiceRoll[]&gt;(await response.Content.ReadAsStringAsync());
        //forecast.Should().HaveCount(0);
    }
</code></pre>
<p>Thanks for any help anyone can provide!</p>
",https://stackoverflow.com/questions/68177210/net-core-c-web-api-integration-testing-an-inmemory-database,"['c#', '.net-core', 'automated-tests']",272,False,0,1
Mock webclient to call external api in Junit integration testing,"<p>I'm writing integration testing using <strong>@EmbeddedPostgres</strong>. I want mock webclient with response.
below is my method.</p>
<pre><code>import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

@Service
public class TranslateApiConnector {
public JsonNode translateApi(TranslationInput translationInput) {

  HttpClient httpClient = HttpClient.create();
  ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
  
   WebClient webclient = WebClient.builder().clientConnector(connector).baseUrl(&quot;baseUri&quot;).build();
   return webclient.post()
          .uri(&quot;uri&quot;)
          .body(Mono.just(translationInput),TranslationInput.class).exchange()
          .flatMap(clientResponse-&gt;clientResponse.bodyToMono(JsonNode.class)).block();
}
};
</code></pre>
<p>For above webclient method I need to mock webclient .How to write test case to call external api.
Here is my test method</p>
<pre><code>@EmbeddedPostgres
@SpringBootTest
@AutoConfigureMockMvc
@Sql(&quot;/scripts/metadata.sql&quot;)
class TestApi {

    @Autowired
    private final TranslateApiConnector translateApiConnector;

   @Test
   voidTestConnector(){
      TranslationInput translationInput = TranslationInput.builder().input(&quot;test&quot;).build()

     ObjectMapper mapper = new ObjectMapper()
     JsonNode jsonNode = mapper.readTree(&quot;{outputs: [{outputs: &quot;test&quot;}]}&quot;)
     
      Mockito.when(webClient.post().uri(&quot;uri&quot;).body(Mono.just(translaionInput),TranslationInput.class)
     .exchange()
     .flatMap(clientResponse -&gt; 
      clientResponse.bodyToMono(JsonNode.class)).block()).thenReturn(jsonNode);

   Mockito.verify(translateApiConnector).translateApi(translationInput);
}}
</code></pre>
",https://stackoverflow.com/questions/70473976/mock-webclient-to-call-external-api-in-junit-integration-testing,"['java', 'spring-boot', 'junit', 'mockito', 'junit-jupiter']",1082,False,0,0
Integration testing using Flutter Driver for OTPTextField widget in flutter,"<p>I am trying to do integration testing using flutter driver. I am using await driver.enterText(find.byType('OTPTextField')) to enter the otp using flutter driver. But it's stuck at that screen and does nothing and the test fails after termination error. The OTPTextField widget kind of has a different UI than normal text field. I am not sure whether enterText function will work in this or not. If not, what are some alternatives?</p>
<p>Here is my code for <a href=""https://pub.dev/packages/otp_text_field"" rel=""nofollow noreferrer"">OTPTextField</a> widget:</p>
<pre><code>OTPTextField(
                key: const Key('otpvalue'),
                length: 6,
                textFieldAlignment: MainAxisAlignment.spaceAround,
                fieldWidth: 30,
                fieldStyle: FieldStyle.underline,
                width: MediaQuery.of(context).size.width / 2,
                style: TextStyle(
                    fontSize: 17,
                    color: Colors.black,
                    fontWeight: FontWeight.bold),
                onCompleted: (pin) async {
                  print(&quot;Completed: &quot; + pin);
                  print(_user.status);
                  if (_user.status == Status.VerifyingOTP ||
                      _user.status == Status.VerifiedOTP) {
                    Navigator.of(context).push(
                        MaterialPageRoute(builder: (_) =&gt; LoaderScreen()));
                      return;
                  }
                  if (widget.isSignup) {
                    if (await _user.signUpWithPhoneNumber(
                      pin.toString(),
                      context,
                      email: widget.emailId,
                      firstName: widget.firstName,
                      lastName: widget.lastName,
                    )) {
                      Navigator.of(context).pushReplacement(
                          MaterialPageRoute(
                              builder: (context) =&gt; OtpVerified()));
                    } else {
                      Navigator.of(context).push(
                          MaterialPageRoute(
                              builder: (context) =&gt; LoaderScreen()));
                    }
                  } else {
                    if (await _user.signInWithPhoneNumber(
                        pin.toString(), context, _user.language, _user.country)) {
                      Navigator.of(context).pushReplacement(
                          MaterialPageRoute(
                              builder: (context) =&gt; OtpVerified()));
                    } else {
                      Navigator.of(context).push(
                          MaterialPageRoute(
                              builder: (context) =&gt; LoaderScreen()));
                    }
                  }
                },
              ),
</code></pre>
<p>And here is the code for integration testing what I tried for this widget.</p>
<pre><code>test('enter otp', () async {
 SerializableFinder enterotp = find.byValueKey('otpvalue');
  await driver.tap(enterotp);
  await driver.enterText('123456');
  expect(await driver.getText(enterotp), &quot;123456&quot;);
});
</code></pre>
",https://stackoverflow.com/questions/69235101/integration-testing-using-flutter-driver-for-otptextfield-widget-in-flutter,"['flutter', 'dart', 'integration-testing', 'flutter-test', 'flutterdriver']",935,False,0,1
RSpec integration testing -- instance variable in application controller is nil,"<p>Recently started a new job, no ruby/rails experience before this gig so bare with me.</p>
<p>Currently I have a method defined in my application controller which has a few instance variables defined, and is being called <code>:before_action do_something_on_start</code>
There is an instance variable that grabs an entry from our database and I set some instance variables that will be available in the view</p>
<pre><code>def do_something_on_start
@test = User.find_by(id: 1)
@enabled = @test.value == &quot;true&quot;
@start_date = @test.start_date
end
</code></pre>
<p>When running our suite of test specs, most of the feature specs come back with <code>undefined method `value' for nil:NilClass</code></p>
<p>Not entirely sure why this is happening. Are the instance variables not available to the test spec when they run? Or do I have to have those same instance variables defined in all of our feature specs to work?</p>
",https://stackoverflow.com/questions/69443512/rspec-integration-testing-instance-variable-in-application-controller-is-nil,"['ruby-on-rails', 'ruby', 'rspec', 'capybara']",130,True,0,1
C# .NET Core - Where to store LARGE files for integration testing?,"<p>I'm writing some .NET core API integration tests that verify if a file upload mechanism is working properly.</p>
<p>What is the best practice for storing large files (2Gb +) that I upload for testing purposes? It doesn't seem like a good idea to include these test files in the solution/source control due to their size.</p>
<p>What is the recommended path to take when it comes to writing integration tests using large files?</p>
",https://stackoverflow.com/questions/67475794/c-net-core-where-to-store-large-files-for-integration-testing,"['.net-core', 'integration-testing', 'web-api-testing']",364,True,1,1
ASP.Net Core XUnit Integration Testing when Two Factor Authenication is enabled,"<p>I've developing an Angular web application using ASP.Net Core 3.1 for the API.</p>
<p>So far, I've written some integration unit tests using a Custom WebApplicationFactory to create the test server.</p>
<p>All tests use the HttpClient to make GETs and POSTs to the API running under the Custom WebApplicationFactory. Most of these tests initially perform a login to obtain a token to use for subsequent requests.</p>
<p>I'd like to add Two Factor Authentication to the application, but this will inevitably break any tests, as they aren't able to get hold of the six digit code which would be sent via email.</p>
<p>Here is what a test currently looks like, without MFA being implemented.
Is there a way that the test can be given the MFA code so that it can continue to perform tests?</p>
<p>Do I simply need to seed a user that does not have MFA enabled?
I actually want all users to have MFA enabled in production.</p>
<p>Many thanks</p>
<pre><code>using Xunit;
using System.Threading.Tasks;
using MyCompany.ViewModels.Authentication;
using MyCompany.StaffPortal.Tests.Shared;
using StaffPortal;
using Newtonsoft.Json;
using MyCompany.ServiceA.ViewModels;
using System.Collections.Generic;
using System.Net.Http;

namespace MyCompany.Tests.StaffPortal.ServiceA
{
    public class ExtensionsControllerTests : TestBase
    {
        public ExtensionsControllerTests(CustomWebApplicationFactory&lt;Startup&gt; factory) : base(factory)
        {
        }

        [Fact]
        public async Task Test_GetExtensions()
        {
            //This line creates a new &quot;web browser&quot; and uses the login details provided to obtain and set up the token so that we can request information about an account.
            HttpClient httpClient = await CreateAuthenticatedHttpClient(&quot;abcltd1@MyCompany.com&quot;, &quot;test&quot;, 1);

            //Perform any work and get the information from the API
            //Contact the API using the token so check that it works
            var getExtensionsResponse = await httpClient.GetAsync(&quot;/api/ServiceA/extensions/GetExtensions&quot;);

            //Check that the response was OK
            Assert.True(getExtensionsResponse.StatusCode == System.Net.HttpStatusCode.OK, &quot;GetExtensions did not return an OK result.&quot;);

            //Get and Convert the Content we received into a List of ServiceAExtensionViewModel, as that is what GetExtensions sends back to the browser.
            var getExtensionsResponseContent = await getExtensionsResponse.Content.ReadAsStringAsync();
            List&lt;ServiceAExtensionViewModel&gt; extensionList = JsonConvert.DeserializeObject&lt;List&lt;ServiceAExtensionViewModel&gt;&gt;(getExtensionsResponseContent);


            //Check the information received matches our expectations
            Assert.True(extensionList.Count == 2);
            Assert.True(extensionList[0].PropertyA == 123);
            Assert.True(extensionList[0].PropertyB == 0161);
            Assert.True(extensionList[0].PropertyC == true);
        }
    }
}
</code></pre>
<p>Here is the content's of CreateAuthenticatedHttpClient() for reference.</p>
<pre><code>protected async Task&lt;HttpClient&gt; CreateAuthenticatedHttpClient(string username, string password, int companyAccountId)
        {
            var httpClient = _factory.CreateClient(
                new WebApplicationFactoryClientOptions
                {
                    AllowAutoRedirect = false
                });

            //Create the Login information to send to the server
            var loginInformation = new LoginRequestModel
            {
                Username = username,
                Password = password,
                ReturnUrl = &quot;&quot;
            };

            //Convert it into Json which the server will understand
            var validLoginRequestJson = ConvertToJson(loginInformation);

            //Send the Json Login information to the server, and put the response we receive into loginResponse
            //In the code below, httpClient is like a web browser. You give it the 
            var loginResponse = await httpClient.PostAsync(&quot;/api/authenticate&quot;, validLoginRequestJson);

            //Check the loginResponse was a CREATED response, which means that the token was made
            Assert.True(loginResponse.StatusCode == System.Net.HttpStatusCode.Created, &quot;New Token was not returned.&quot;);

            //Check the response is identified as being in Json format
            Assert.Equal(&quot;application/json; charset=utf-8&quot;, loginResponse.Content.Headers.ContentType.ToString());

            //Next we have to convert the received Json information into whatever we are expecting.
            //In this case, we are expecting a AuthenticationResponseViewModel (because that's what the API sends back to the person trying to log in)
            //First we get hold of the Content (which is in Json format)
            var responseJsonString = await loginResponse.Content.ReadAsStringAsync();

            //Second we convert the Json back into a real AuthenticationResponseViewModel
            AuthenticationResponseViewModel authenticationResponseViewModel = JsonConvert.DeserializeObject&lt;AuthenticationResponseViewModel&gt;(responseJsonString);

            //Now we take the Token from AuthenticationResponseViewModel, and add it into the httpClient so that we can check the Token works.
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(&quot;Bearer&quot;, authenticationResponseViewModel.token);

            httpClient.DefaultRequestHeaders.Add(&quot;CompanyId&quot;, companyAccountId.ToString());

            return httpClient;
        }
</code></pre>
",https://stackoverflow.com/questions/68228341/asp-net-core-xunit-integration-testing-when-two-factor-authenication-is-enabled,"['unit-testing', 'asp.net-core', 'asp.net-identity']",130,False,1,0
Can I Use EF Core 5 InMemory Database For Integration Testing,"<p>I'm working on migration from net core 3.1 to net 5 (EF Core 3 to EF Core 5 aswell). We are using EF Core 3 InMemory database for integration tests. After migration tests no longer passing and queries throw error:</p>
<blockquote>
<p>System.InvalidOperationException: The LINQ expression
'ShapedQueryExpression:
QueryExpression:
InMemoryQueryExpression:
ServerQueryExpression:
InMemoryTableExpression: Entity: RatingExclusionProduct
.Where(valueBuffer =&gt; IsFalse(ValueBufferTryReadValue(valueBuffer, 0, Property:
RatingExclusion.Id (UUId) Required PK AfterSave:Throw).Equals(null))
&amp;&amp; object.Equals(
objA: ExpressionExtensions.ValueBufferTryReadValue(
valueBuffer: valueBuffer,
index: 0,
property: Property: RatingExclusion.Id (UUId) Required PK AfterSave:Throw),
objB: ExpressionExtensions.ValueBufferTryReadValue(
valueBuffer: valueBuffer,
index: 0,
property: Property: RatingExclusionProduct.ExclusionId (UUId) Required PK FK
AfterSave:Throw)))
ProjectionMapping:
Member: EmptyProjectionMember Projection: EntityProjectionExpression:
Property: RatingExclusionProduct.ExclusionId (UUId) Required PK FK AfterSave:Throw -&gt;
ExpressionExtensions.ValueBufferTryReadValue(
valueBuffer: valueBuffer,
index: 0,
property: Property: RatingExclusionProduct.ExclusionId (UUId) Required PK FK
AfterSave:Throw)
Property: RatingExclusionProduct.ProductId (UUId) Required PK FK Index AfterSave:Throw -&gt;
ExpressionExtensions.ValueBufferTryReadValue(
valueBuffer: valueBuffer,
index: 1,
property: Property: RatingExclusionProduct.ProductId (UUId) Required PK FK Index
AfterSave:Throw)
,</p>
<pre><code>ShaperExpression: EntityShaperExpression: 
        EntityType: RatingExclusionProduct
        ValueBufferExpression: 
            ProjectionBindingExpression: EmptyProjectionMember
        IsNullable: False

.AsQueryable()
.LeftJoin(
    inner: DbSet&lt;ControlProduct&gt;(), 
    outerKeySelector: o0 =&gt; EF.Property&lt;UUId&gt;(o0, &quot;ProductId&quot;), 
    innerKeySelector: c =&gt; EF.Property&lt;UUId&gt;(c, &quot;Id&quot;), 
    resultSelector: (o, i) =&gt; new TransparentIdentifier&lt;RatingExclusionProduct, ControlProduct&gt;(
        Outer = o, 
        Inner = i
    ))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly
</code></pre>
<p>by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList',
or 'ToListAsync'</p>
</blockquote>
<p>Can we somehow fix thise issue or we need to switch to some another method of mocking the database? As far as I know there was breaking change:</p>
<p><a href=""https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/breaking-changes#no-client-methods"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/breaking-changes#no-client-methods</a></p>
<p>Does my problem related to it? I've search online and some people suggesting to use real database for testing purposes, but I have concern that would be realy slow solution and we have multiple contexts that uses single database, so it would be hard to create database on test start. Some suggest to create context aggregation (single context that contains all entities for database creation purposes only), but I have no idea how to implement that. I think my question looks more like combination of consequental questions, but I'm kinda lost a bit on this topic. Thanks a lot for your attention.</p>
<p><strong>UPDATE:</strong>
UUId is custom type, which is used as PK for all our tables.
To resolve it we use:</p>
<pre><code>    services
        .AddDbContext&lt;RatingsContext&gt;(opt =&gt;
            opt.AddRelationalTypeMappingSourcePlugin&lt;UUIdTypeMapperPlugin&gt;()
                .UseMySql(connectionString, mso =&gt; mso
                    .ServerVersion(new Version(5, 7, 29), ServerType.MySql)
                    .EnableRetryOnFailure()
                )
        );
</code></pre>
<p>Where UUIdTypeMapperPlugin:</p>
<pre><code>public class UUIdTypeMapperPlugin : ITypeMappingSourcePlugin, IRelationalTypeMappingSourcePlugin
{
    public CoreTypeMapping FindMapping(in TypeMappingInfo mappingInfo)
    {
        return mappingInfo.ClrType == typeof(UUId) ? new UUIdTypeMapper() : null;
    }

    public RelationalTypeMapping FindMapping(in RelationalTypeMappingInfo mappingInfo)
    {
        return mappingInfo.ClrType == typeof(UUId) ? new UUIdTypeMapper() : null;
    }
}
</code></pre>
<p>And UUIdTypeMapper:</p>
<pre><code>public class UUIdTypeMapper : RelationalTypeMapping
{
    private static readonly ValueConverter&lt;UUId, byte[]&gt; _converter
        = new ValueConverter&lt;UUId, byte[]&gt;(uuid =&gt; uuid.ToByteArray(),
            byteArray =&gt; new UUId(byteArray));

    protected UUIdTypeMapper(RelationalTypeMappingParameters parameters) : base(parameters)
    {
    }

    public UUIdTypeMapper() : base(new RelationalTypeMappingParameters(
        new CoreTypeMappingParameters(typeof(UUId), _converter), &quot;binary(16)&quot;)
    )
    {
    }

    protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters)
    {
        return new UUIdTypeMapper(parameters);
    }

    public override string GenerateSqlLiteral(object value)
    {
        return $&quot;0x{value}&quot;;
    }
}
</code></pre>
",https://stackoverflow.com/questions/69818124/can-i-use-ef-core-5-inmemory-database-for-integration-testing,"['asp.net', 'entity-framework-core', 'ef-core-3.1', 'ef-core-5.0']",749,True,0,1
Can Firebase Emulators be used for integration testing with a React frontend?,"<p>I have a simple React frontend application that uses Firebase for Auth and Firestore (<a href=""https://jlowen-netflix.netlify.app/"" rel=""nofollow noreferrer"">https://jlowen-netflix.netlify.app/</a> if additional context helpful).  I provide Firebase as a Context to my top-level application, and listen for a change in Auth to redirect the user to logged in content.</p>
<p>I would like to test end-to-end user workflow from anonymous, to sign-up, to logged in.  I have already installed the Firebase CLI as well as the Firebase emulators.  I can verify the emulators run correctly by visiting the Emulator UI on localhost.  I also can verify the application hooks in to the emulators when I start the dev server (npm start) for Create-React-App.  I made a test user in the Emulator UI, and was able to log in as expected.</p>
<p>When I try to get this to render in Jest, my auth listener custom hook attempts to access the auth() method on the firebase context prior to firebase initialization.</p>
<pre><code> TypeError: Cannot read property 'auth' of undefined

       9 |   // As recommended by Firebase - need to set up subscription
      10 |   useEffect(() =&gt; {
    &gt; 11 |     const listener = firebase.auth().onAuthStateChanged((authUser) =&gt; {
         |                               ^
      12 |       console.log(`Firebase detected auth change: ${authUser}`)
      13 |       if (authUser) {
      14 |         localStorage.setItem(&quot;authUser&quot;, JSON.stringify(authUser))

      at src/hooks/use-auth-listener.js:11:31
</code></pre>
<p>I can't seem to resolve what seems to be some sort of async issue that I encounter in Jest, but does not occur in the deployed application.</p>
<p>I am pretty new in React and Jest, so if I can provide additional information, please let me know!</p>
",https://stackoverflow.com/questions/65691925/can-firebase-emulators-be-used-for-integration-testing-with-a-react-frontend,"['javascript', 'reactjs', 'firebase', 'jestjs', 'firebase-tools']",276,False,3,1
Flutter integration testing: can I start the test on any page? How?,"<p>So I am testing an app that has multiple pages.</p>
<p>Sometimes, I just want to start a test from a page of choice.</p>
<p>However, I can't figure out how to do it.</p>
<p>Everywhere I look, everyone always starts their integration test at the beginning by calling <code>main()</code>.</p>
<p>This makes sense but my case is unique.  I tried to import the page that I want to start at and I tried calling the main class but I get the following error:</p>
<p><code>The constructor returns type 'dynamic' that isn't of expected type 'widget'.</code></p>
<p>My stack also states:</p>
<pre><code>When the exception was thrown, this was the stack:
#4      main.&lt;anonymous closure&gt;.&lt;anonymous closure&gt; (file:///D:/WEBDEV/EndevStudios/MedicalApp/gshDevWork/medical-app-frontend/integration_test/basic_app_test.dart:94:7)
&lt;asynchronous suspension&gt;
&lt;asynchronous suspension&gt;
(elided one frame from package:stack_trace)
</code></pre>
<p>I think the class I'm trying to call isn't built that way.  Here's the beginning part of that code:</p>
<pre><code>
class WelcomePage extends StatelessWidget {
  final String title = &quot;Welcome!&quot;;
  final String titleDev = &quot;Take Control of your Health!&quot;;
  final String boxDescription =
      &quot;It is for information purposes only and help you access health professionals through virtual means as well as screen for a selection of diseases.&quot;;
  final String innerContainerTextTitle =
      &quot;WARNING! This application is not a diagnosing tool.&quot;;
  final String descriptionTitle = 'App Features:';
  final String descriptionTitle1 =
      &quot;Technology to analyze a selection of diseases.&quot;;
    final String descriptionTitle2 =
      &quot;Resources to learn about different types of diseases; typical treatments; and management standards.&quot;;
  final String _titleImagePath = 'assets/appbar/diagnosis.webp';
  WelcomePage();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: _buildAppbar(context),
      body: Container(
          width: displayWidth(context),
          height: displayHeight(context),
          alignment: Alignment.center,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              // _logoImage(context),
              _welcomeInfo(context),
            ],
          )),
    );
  }
</code></pre>
<p>In my test I was calling <code>app.WelcomePage();</code></p>
",https://stackoverflow.com/questions/69653197/flutter-integration-testing-can-i-start-the-test-on-any-page-how,"['flutter', 'testing', 'mobile', 'integration-testing', 'mobile-application']",819,False,2,1
Angular Integration Testing - jasmine Spy - Can&#39;t mock a service method returning Observable,"<p>I am new to doing integration testing. And the whole thing is so confusing.</p>
<p>For my first test, Seems like my spying is not returning the data as i intend to return it. Gives and error: Expected 0 to be 3. Will be great if someone could  help me understand what am I doing wrong.</p>
<p>Here is my service,page,spec file along with template:</p>
<p><strong>MyService</strong></p>
<pre><code>
    import { Data } from './../data/data.model';
    import { Injectable } from '@angular/core';
    import { BehaviorSubject, of } from 'rxjs';
    import { tap } from 'rxjs/operators';

    @Injectable({
      providedIn: 'root',
    })
    export class MyService {
      private _data = new BehaviorSubject&lt;Data[]&gt;([]);

      get data() {
        return this._data;
      }

      constructor() {}

      getAllData() {
        return of([
          {
            id: '1',
            title: 'Rice',
          },
          {
            id: '2',
            title: 'Wheat',
          },
          {
            id: '33',
            title: 'Water',
          },
        ]).pipe(
          tap((data) =&gt; {
            this._data.next(data);
          })
        );
      }
    }

</code></pre>
<p><strong>DataPage Component</strong></p>
<pre><code>
    import { Component, OnInit } from '@angular/core';
    import { BehaviorSubject, Observable, of, Subscription } from 'rxjs';
    import { MyService } from '../services/my.service';
    import { Data } from './data.model';

    @Component({
      selector: 'app-data',
      templateUrl: './data.page.html',
      styleUrls: ['./data.page.scss'],
    })
    export class DataPage implements OnInit {
      allData: Data[];
      dataServiceSub: Subscription;
      isLoading: boolean;

      constructor(private myService: MyService) {}

      ngOnInit() {
        this.dataServiceSub = this.myService.data.subscribe(
          (data) =&gt; {
            console.log(data);
            this.allData = data;
          }
        );
      }

      ngOnDestroy() {
        if (this.dataServiceSub) {
          console.log('ngOnDestroy');
          this.dataServiceSub.unsubscribe();
        }
      }

      ionViewWillEnter() {
        this.isLoading = true;
        this.myService.getAllData().subscribe(() =&gt; {
          console.log('ionViewWillEnter');
          this.isLoading = false;
        });
      }
    }

</code></pre>
<p><strong>DataPage.spec</strong></p>
<pre><code>    import { MyService } from '../services/my.service';
    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    import { IonicModule } from '@ionic/angular';

    import { DataPage } from './data.page';
    import { of } from 'rxjs';

    describe('DataPage', () =&gt; {
      let component: DataPage;
      let fixture: ComponentFixture&lt;DataPage&gt;;
      let serviceSpy: jasmine.SpyObj&lt;MyService&gt;;

      beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
          declarations: [DataPage],
          providers: [
            {
              provide: MyService,
              useClass: MyService
            },
          ],
          imports: [IonicModule.forRoot()],
        }).compileComponents();

        fixture = TestBed.createComponent(DataPage);
        component = fixture.componentInstance;
        fixture.detectChanges();
      }));

      fit('Should show list of data if data is available', () =&gt; {
        serviceSpy = TestBed.get(MyService);
        spyOn(serviceSpy, 'getAllData').and.returnValue(of([
          {
            id: '1',
            title: 'Rice',
          },
          {
            id: '2',
            title: 'Wheat',
          },
          {
            id: '33',
            title: 'Water',
          },
        ]));
        fixture.detectChanges();
        const element = fixture.nativeElement.querySelectorAll(
          '[test-tag=&quot;dataList&quot;] ion-item'
        );
        console.log(
          fixture.nativeElement.querySelectorAll('[test-tag=&quot;dataList&quot;]')
        );
        expect(element.length).toBe(3);
      });
    });
</code></pre>
<p><strong>HTML</strong></p>
<pre><code>
    &lt;ion-content&gt;
      &lt;div test-tag=&quot;empty&quot; class=&quot;ion-text-center&quot;&gt;
        &lt;ion-text color=&quot;danger&quot;&gt;
          &lt;h1&gt;No data&lt;/h1&gt;
        &lt;/ion-text&gt;
      &lt;/div&gt;
      &lt;div test-tag=&quot;dataList&quot;&gt;
        &lt;ion-list&gt;
          &lt;ion-item *ngFor=&quot;let data of allData&quot;&gt;
            &lt;ion-label test-tag=&quot;title&quot;&gt;{{data.title}}&lt;/ion-label&gt;
          &lt;/ion-item&gt;
        &lt;/ion-list&gt;
      &lt;/div&gt;
    &lt;/ion-content&gt;


</code></pre>
",https://stackoverflow.com/questions/65866453/angular-integration-testing-jasmine-spy-cant-mock-a-service-method-returnin,"['angular', 'typescript', 'rxjs', 'jasmine', 'angular-test']",628,True,2,2
Options or alternatives to Testcontainers for Spring Boot integration testing in Kubernetes?,"<p>I need to setup integration tests in a Spring Boot project using Postgres, Redis and Elasticsearch (at some point later also Kafka will be added). So far I've found two options:</p>
<ol>
<li>H2 Database and Embedded Redis. This could work but we are using some Postgres specific functions in some of our queries so this would not allow to cover all the cases.</li>
<li><a href=""https://www.testcontainers.org/"" rel=""nofollow noreferrer"">Testcontainers</a>. This looked perfect but apparently it's not possible to run those in pipeline since we are using Kubernetes</li>
</ol>
<p>Third option requires a bit of manual work. It's definitely possible to make a docker compose file with all the services needed for testing for local usage and let infrastructure team build containers the way they want for running tests in a pipeline. But this way a developer would have to manually start/stop those containers when running tests locally.</p>
<p>Is there a way to automate this process? Or any options similar to Testcontainers that would work in Kubernetes? Or perhaps there is a way to run Testcontainers in Kubernetes?</p>
<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/69850525/options-or-alternatives-to-testcontainers-for-spring-boot-integration-testing-in,"['spring', 'spring-boot', 'kubernetes', 'integration-testing', 'testcontainers']",1571,True,2,1
How to do integration testing on an external API with ASP.NET Core,"<p>I'm trying to do some integration tests on an external API. Most of the guides I find online are about testing the ASP.NET web api, but there's not much to find about external API's. I want to test a GET request on this API and confirm if it passes by checking if the status code is OK. However this test is not passing and im wondering if i'm doing this correctly. Currently it's giving me a status code 404(Not found).</p>
<p>I'm using <code>xUnit</code> together with <code>Microsoft.AspNetCore.TestHost</code> How would you suggest me to test external API's?</p>
<pre><code>private readonly HttpClient _client;

public DevicesApiTests()
{
    var server = new TestServer(new WebHostBuilder()
        .UseEnvironment(&quot;Development&quot;)
        .UseStartup&lt;Startup&gt;());
    _client = server.CreateClient();
}

[Theory]
[InlineData(&quot;GET&quot;)]
public async Task GetAllDevicesFromPRTG(string method)
{
    //Arrange
    var request = new HttpRequestMessage(new HttpMethod(method), &quot;https://prtg.nl/api/content=Group,Device,Status&quot;);

    //Act
    var response = await _client.SendAsync(request);

    // Assert
    response.EnsureSuccessStatusCode();
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
</code></pre>
<p><strong>Edit</strong></p>
<p>The API call which im trying to test looks as follows, and is working properly</p>
<pre><code>private readonly DbContext _dbContext;
private readonly IDevicesRepository _devicesRepository;

public DevicesAPIController(DbContext dbContext, IDevicesRepository devicesRepository)
{
    _dbContext = dbContext;
    _devicesRepository = devicesRepository;
}

[HttpPost(&quot;PostLiveDevicesToDatabase&quot;)]
public async Task&lt;IActionResult&gt; PostLiveDevicesToDatabase()
{
    try
    {

        using (var httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));

            using (var response = await httpClient
                .GetAsync(
                    &quot;https://prtg.nl/api/content=Group,Device,Status&quot;)
            )
            {
                string apiResponse = await response.Content.ReadAsStringAsync();
                var dataDeserialized = JsonConvert.DeserializeObject&lt;Devices&gt;(apiResponse);

                devicesList.AddRange(dataDeserialized.devices);

                foreach (DevicesData device in devicesList)
                {

                    _dbContext.Devices.Add(device);
                    devicesAdded.Add(device);

                    _dbContext.SaveChanges();
                }
            }
        }
    }
    catch
    {
        return BadRequest();
    }
}
</code></pre>
",https://stackoverflow.com/questions/65866821/how-to-do-integration-testing-on-an-external-api-with-asp-net-core,"['c#', 'asp.net-core', 'integration-testing', 'xunit']",5683,True,1,3
Flutter Integration testing failed for multiple test cases in a single file,"<p>I have a simple login page with email and password text field. A button to login and another to sign up. I tried to write integration testing for the Sign in page.</p>
<pre><code>void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  testWidgets('''could type email and password in text filed''',
      (WidgetTester tester) async {
    await app.main();
    await tester.pumpAndSettle();

    final textFieldEmail = find.byType(InputTextWidget).first;
    final textFieldPassword = find.byType(InputTextWidget).last;

    await tester.enterText(textFieldEmail, &quot;asis.adh@gmail.com&quot;);
    await tester.pumpAndSettle();

    expect(find.text(&quot;asis.adh@gmail.com&quot;), findsOneWidget);
  });

testWidgets(
      'should redirect to Sign Up Page when create an account is tapped',
      (WidgetTester tester) async {
    await app.main();
    await tester.pumpAndSettle();

    final createAnAccount = find.text(&quot;Create an account&quot;);
    await tester.tap(createAnAccount);

    await tester.pumpAndSettle();

    expect(find.byType(SignupPage), findsOneWidget);
    expect(find.byType(LoginPage), findsNothing);
  });
}
</code></pre>
<p>When I execute the test case, it fails with the following error:</p>
<blockquote>
<p>The following ArgumentError was thrown running a test: Invalid
argument(s): Object/factory with  type AmenitiesProvider is already
registered inside GetIt.</p>
</blockquote>
<p>Here is my <code>main.dart</code> file</p>
<pre><code>Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  configureInjection(Environment.prod);

  /// for registering the factory.
  await Future.delayed(const Duration(seconds: 2));
  runApp(RoopaApp());
}
</code></pre>
<p>I tried with a <code>main_test.dart</code> and adding <code>configureInjection(Environment.test)</code> but nothing changes. I am not sure how to fix the error. Is there a way to clean the <code>app</code> or destroy it before going to new test case. If I combine the both testcase into one then it works without any problem.</p>
<p>Here is <code>configureInjection</code></p>
<pre><code>@injectableInit
void configureInjection(String environment) {
  $initGetIt(getIt, environment: environment);
}
</code></pre>
<p>I am using get_it and injection package for dependency injection.</p>
<p>Here is the auto generated initGetIt</p>
<pre><code>GetIt $initGetIt(
  GetIt get, {
  String environment,
  EnvironmentFilter environmentFilter,
}) {
  final gh = GetItHelper(get, environment, environmentFilter);
  final httpClientInjectableModule = _$HttpClientInjectableModule();
  final flutterStorageModule = _$FlutterStorageModule();
  gh.lazySingleton&lt;AmenitiesProvider&gt;(() =&gt; AmenitiesProvider());
  gh.factory&lt;Client&gt;(() =&gt; httpClientInjectableModule.client);
  gh.lazySingleton&lt;FileProvider&gt;(() =&gt; FileProvider());
  gh.lazySingleton&lt;FlutterSecureStorage&gt;(
      () =&gt; flutterStorageModule.secureStorate);
  gh.factory&lt;ProfilePageBloc&gt;(() =&gt; ProfilePageBloc());
  gh.factory&lt;SplashScreenBloc&gt;(() =&gt; SplashScreenBloc());
  gh.lazySingleton&lt;AuthLocalDataSourceProtocol&gt;(
      () =&gt; AuthLocalDataSource(secureStorage: get&lt;FlutterSecureStorage&gt;()));
  gh.lazySingleton&lt;AuthRemoteDataSourceProtocol&gt;(
      () =&gt; AuthRemoteDataSource(client: get&lt;Client&gt;()));
  return get;
}
</code></pre>
",https://stackoverflow.com/questions/66228575/flutter-integration-testing-failed-for-multiple-test-cases-in-a-single-file,"['flutter', 'dependency-injection', 'integration-testing', 'testcase', 'widget-test-flutter']",1471,True,1,2
Is there any way to perform Integration testing on API rate limiting?,"<p>I have been trying to add Integration testing for API rate limiting. I am using Xunit with Asp.NetCore.</p>
<p>Right now, I have rate limited my api calls to <strong>x calls per minute</strong>. In my Integration test, I try to run <strong>x+1 number</strong> of api calls and check for <strong>429 error status code</strong>. However, I see that my INT test waits for a minute and <strong>retry the (x+1)th</strong> call and report it as success. (I use Fiddler to check this)</p>
<pre><code>public async Task GetRateLimited()
{
    for (int i = 0; i &lt; x; i++)
    {
        var response = await client.GetApi();
    }
    Func&lt;Task&gt; action = async () =&gt; await client.GetApi();
    MyException exception = await Assert.ThrowsAsync&lt;MyException&gt;(action);
    exception.Response.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
}
</code></pre>
<p>Is there any way to check for the HttpStatusCode 429 requests?</p>
<p>Thanks,</p>
<p>Manisha</p>
",https://stackoverflow.com/questions/68472684/is-there-any-way-to-perform-integration-testing-on-api-rate-limiting,"['asp.net-core', 'integration-testing', 'xunit', 'rate-limiting']",210,False,0,0
Which in-memory MongoDB implementation is good for unit and integration testing?,"<p>We are trying to move from Fongo to some other in-memory MongoDB service. We are looking for one from org.mongodb and haven't found one. This is our preference because this will have long term support from MongoDB org.</p>
<p>We found bwaldvogel/mongo-java-server. However, they may not support for latest MongoDB dependencies versions like Fongo.</p>
<p>Please suggest.</p>
",https://stackoverflow.com/questions/68855296/which-in-memory-mongodb-implementation-is-good-for-unit-and-integration-testing,"['mongodb', 'in-memory-database']",167,False,0,1
How to use Mockito/PowerMockito to trigger IOException for Unit/Integration Testing,"<p>I am doing testing on the following piece of code, and i am having trouble getting this method to throw an IOException so i can get 100% coverage.
I have tried to mock the CharArrayReader, StringWriter classes but to no avail.
Would appreciate any help!</p>
<p>Class to test</p>
<pre><code>public static final String getValue(String content) {
    if (content == null) return null;
    CharArrayReader reader = new CharArrayReader(content.toCharArray());
    StringWriter writer = new StringWriter();
    try {
        int c;
        while ((c = reader.read()) != -1) {
            if (isChinese((char)c)) {
                writer.write(c);
            } else {
                if ( (char)c &gt; 0x20 &amp;&amp; (char)c &lt; 0x7f ) {
                    writer.write(c);
                } else {
                    writer.write(' ');
                }
            }
        }
    } catch (IOException e) {
        return null;
    } finally {
        reader.close();
    }
    return writer.toString();
}
</code></pre>
<p>My Attempts</p>
<pre><code>@Test
public void getValue_Exception() throws IOException {
    String content = &quot;asd&quot;;
    char[] chara = null;
    CharArrayReader reader = mock(CharArrayReader.class);
    when(content.toCharArray()).thenReturn(chara);
    
    when(reader.read()).thenThrow(IOException.class);
    StringWriter writer = mock(StringWriter.class);
    doThrow(IOException.class).when(writer).write(anyInt());


    spyController.getValue(content);
}
</code></pre>
",https://stackoverflow.com/questions/68310389/how-to-use-mockito-powermockito-to-trigger-ioexception-for-unit-integration-test,"['java', 'unit-testing', 'mockito', 'integration-testing', 'powermockito']",185,False,0,2
How to do integration testing for .NET 6 Web Api projects using WebApplicationFactory?,"<p>I have been using WebApplicationFactory for integration testing in .NET 5, .NET Core 3.1 and .NET Core 2.1 . It is all working fine for me.</p>
<p>I just create my project with:</p>
<pre><code>dotnet new webapi
</code></pre>
<p>and then I see a web api project <strong>with a Startup class</strong>.</p>
<p>Then I create an instance of the factory class:</p>
<pre><code>private readonly WebApplicationFactory&lt;Startup&gt; factory = new WebApplicationFactory&lt;Startup&gt;();
</code></pre>
<p>As explained <a href=""https://blog.markvincze.com/overriding-configuration-in-asp-net-core-integration-tests/"" rel=""nofollow noreferrer"">here</a> and <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-5.0#basic-tests-with-the-default-webapplicationfactory"" rel=""nofollow noreferrer"">here</a>.</p>
<p>The WebApplicationFactory class is something I really like. It makes it easy to write integration tests. I like it a lot. The Microsoft docs <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"">also refer to it for .NET 6</a>.</p>
<p>However, how do I, when using .NET 6, make sure my code compiles?</p>
<p>The mentioned command-line statement:</p>
<pre><code>dotnet new webapi
</code></pre>
<p>results in a nicely working project but (when having the .NET 6 SDK installed) without a Startup class...... Now my tests do not compile for just one reason: the Startup class does not exist.</p>
<p>How to fix this? I find it hard to imagine that I cannot write integration tests anymore because <code>WebApplicationFactory&lt;Startup&gt;</code> does not compile anymore. But right now, this is the reality I need to deal with. How can I solve the problem? I look forward to being able to use the <code>WebApplicationFactory</code> class and continue writing integration tests. But how?</p>
",https://stackoverflow.com/questions/68987057/how-to-do-integration-testing-for-net-6-web-api-projects-using-webapplicationfa,"['integration-testing', '.net-6.0', 'aspnetcore-environment']",5118,True,4,1
How to use RTL to do integration testing on component with complex reducer?,"<p>I want to introduce integration testing with React Testing Library into my app, but I'm running into some high-level roadblocks.</p>
<p>The examples in documentation are great, but I feel like there isn't an example where the redux state is very complicated and is hydrated from several APIs.</p>
<p>I have a component I want to test, but the data it needs comes from probably 8+ APIs, all stored in different parts of the reducer. Its child components also have their own redux connectors that come from other places in the reducer which are hydrated by other API calls.</p>
<p>Is this something that can be integration tested, and by that I mean not mocking the props, setting up a real reducer, and using MSW to intercept all the API calls needed? (vs mocking the props of the component and mocking its redux connected child components).</p>
<p>I am concerned that an engineer would need to understand far more than what should be necessary to write an integration test for these types of very complicated cases.</p>
<p>A toy Twitter example:</p>
<p>I have a parent <code>&lt;Tweets/&gt;</code> component that renders <code>&lt;Tweet/&gt;</code> children.</p>
<p>I have a tweet object that comes from the /tweets api.
I have a user object that comes from the /users api.</p>
<p>A tweet object</p>
<pre><code>{
  body: 'Hello World',
  userId: 123
}
</code></pre>
<p>A user object</p>
<pre><code>{
  id: 123,
  name: 'John Smith'
}
</code></pre>
<p><strong>Tweets.jsx</strong></p>
<pre><code>const mapState = (state) =&gt; ({
  tweets: selectTweets(state)
});

const Tweets = ({tweets}) =&gt; {
  return (
    tweets.map(tweet =&gt; (
      &lt;Tweet tweet={tweet} /&gt;
    ))
  );
}
</code></pre>
<p><strong>Tweet.jsx</strong></p>
<pre><code>const mapState = (state, {tweet}) =&gt; ({
  user: selectUserById(state, { id: tweet.userId })
});

const Tweet = ({user, tweet}) =&gt; {
  return (
    &lt;div&gt;
      &lt;div&gt;{ tweet.body }&lt;/div&gt;
      &lt;div&gt;{ user.name }&lt;/div&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>Although I feel this is a fairly contrived example, I can already imagine difficulties integration testing <code>Tweets</code> since I must also understand that its child <code>Tweet</code> requires data from <code>/users</code>. Once the app comes more complex, where perhaps the children of <code>Tweet</code> need their own data from redux, I feel like integration testing becomes unreasonably difficult.</p>
<p>Am I missing something? Or in cases like this, do I need to mock in order to decrease the scope of what I am testing?</p>
",https://stackoverflow.com/questions/67118457/how-to-use-rtl-to-do-integration-testing-on-component-with-complex-reducer,"['reactjs', 'redux', 'react-testing-library']",219,False,1,0
Integration testing with Events - Exceptions when running multiple tests at the same time,"<p>I am using a shared database fixture for my tests, but when running multiple tests at the same time, I get the following error message:</p>
<blockquote>
<p>System.InvalidOperationException: A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see <a href=""https://go.microsoft.com/fwlink/?linkid=2097913"" rel=""nofollow noreferrer"">https://go.microsoft.com/fwlink/?linkid=2097913</a>.</p>
</blockquote>
<p>This is my code of my Fixture:</p>
<pre><code>public class SharedDatabaseFixture : IDisposable
{
    public static readonly object _lock = new object();
    private static bool _databaseInitialized;

    private const string postgresConnectionString = &quot;Host=localhost;Database=IntegrationTests; Username=postgres;Password=password&quot;;

    public SharedDatabaseFixture()
    {
        Connection = new NpgsqlConnection(postgresConnectionString);

        Seed();

        Connection.Open();
    }

    public DbConnection Connection { get; }

    public AppDbContext CreateContext(DbTransaction transaction = null!)
    {
        var serviceProvider = new ServiceCollection()
            .AddEntityFrameworkNpgsql()
            .AddMediatR(typeof(IAggregateRoot).Assembly)
            .AddScoped(typeof(IAsyncRepository&lt;&gt;), typeof(EfRepository&lt;&gt;))
            .AddDbContext&lt;AppDbContext&gt;(options =&gt; options.UseNpgsql(Connection))
            .BuildServiceProvider();

        ServiceLocator.SetLocatorProvider(serviceProvider);
        DomainEvents.Mediator = () =&gt; ServiceLocator.Current.GetInstance&lt;IMediator&gt;();

        var builder = new DbContextOptionsBuilder&lt;AppDbContext&gt;();
        builder.UseNpgsql(Connection).UseInternalServiceProvider(serviceProvider);

        var context = new AppDbContext(builder.Options);

        if (transaction != null)
        {
            context.Database.UseTransaction(transaction);
        }

        return context;
    }

    private void Seed()
    {
        lock (_lock)
        {
            if (!_databaseInitialized)
            {
                using (var context = CreateContext())
                {
                    context.Database.EnsureDeleted();
                    context.Database.EnsureCreated();

                    var appDbContextSeed = new AppDbContextSeed(context);
                    appDbContextSeed.SeedAsync().Wait();
                }

                _databaseInitialized = true;
            }
        }
    }

    public void Dispose() =&gt; Connection.Dispose();
}
</code></pre>
<p>The code I am testing uses events and those events do queries to the database. Therefore, I am registering some services and also a <code>DbContext</code>.</p>
<p>The problem is, when I run multiple tests at the same time, events are raised at the same time as well and because they are all using the same <code>DbContext</code>, it throws an exception when two handlers try to use the <code>DbContext</code> at the same time.</p>
<p>So, my question is: how can I instantiate a <code>DbContext</code> for each test (but using the same connection) or prevent it from using the <code>DbContext</code> at the same time?</p>
<hr />
<p>An Example of one of my tests:</p>
<pre><code>public class Project_Create : IClassFixture&lt;SharedDatabaseFixture&gt;
{
    public SharedDatabaseFixture Fixture { get; }
    public Project_Create(SharedDatabaseFixture fixture) =&gt; Fixture = fixture;

    [Fact]
    public void Creates_succesfully()
    {
        var project = new Project(SeedConstants.TEST_COMPANY_ID, &quot;ABC&quot;, &quot;Hallo123&quot;, &quot;2018-123&quot;);

        Assert.Equal(SeedConstants.TEST_COMPANY_ID, project.CompanyId);
        Assert.Equal(&quot;ABC&quot;, project.Code);
        Assert.Equal(&quot;Hallo123&quot;, project.Description);
        Assert.Equal(&quot;2018-123&quot;, project.Number);
    }
}
</code></pre>
<p>Project.cs:</p>
<pre><code>public class Project : BaseEntity&lt;Guid, ProjectValidator, Project&gt;, IAggregateRoot
{
    public Guid CompanyId { get; private set; }

    public string Code {  get; private set; }

    public string Description { get; private set; }

    public string Number {  get; private set; }

    public Project(Guid companyId, string code, string description, string number)
    {
        CompanyId = companyId;
        Code = code;
        Description = description;
        Number = number;

        Validate(this);
        DomainEvents.Raise(new SetCompanyIdEvent(companyId)).GetAwaiter().GetResult();
    }
}
</code></pre>
<p>As you can see, this project class raises an event. This event has a handler and looks like this:</p>
<pre><code>public class CheckIfProjectIdExistsHandler : INotificationHandler&lt;SetProjectIdEvent&gt;
{
    private readonly IAsyncRepository&lt;Project&gt; _projectRepository;

    public CheckIfProjectIdExistsHandler(IAsyncRepository&lt;Project&gt; projectRepository)
    {
        _projectRepository = projectRepository;
    }

    public async Task Handle(SetProjectIdEvent notification, CancellationToken cancellationToken)
    {
        var project = await _projectRepository.GetByIdAsync(notification.ProjectId, cancellationToken);

        if (project == null)
        {
            throw new ProjectDoesNotExistsException($&quot;The project with ID {notification.ProjectId} does not exist.&quot;);
        }
    }
}
</code></pre>
<p>I hope this illustrates what I am testing</p>
",https://stackoverflow.com/questions/69546087/integration-testing-with-events-exceptions-when-running-multiple-tests-at-the,"['c#', 'asp.net-core', 'xunit', 'npgsql']",609,True,1,1
How to create a mock Oracle ADW database in Python for integration testing?,"<p>I am currently migrating data from AWS Redshift to Oracle ADW. I use postgres to create a mock database and run integration tests to simulate how my queries would run in production environment. Postgres is a good candidate for mocking Redshift database as they are similar, but that is not the case for Oracle ADW. I'm wondering if anyone has suggestions on how I could create a mock database that has the same syntax constraints as Oracle ADW.</p>
<p>I already know how to create mock connections to write unit tests. However, these integration tests help us validate pipelines end to end.</p>
",https://stackoverflow.com/questions/68385179/how-to-create-a-mock-oracle-adw-database-in-python-for-integration-testing,"['python-3.x', 'oracle', 'integration-testing']",147,True,0,1
How to Mock send method in MessageChannel of SpringBoot in Wiremock Integration Testing,"<p>I am using Spring Boot Java for my application. The application is sending some messages to Kafka using MessageChannel. Ex: this.messageChannel.send(message).</p>
<p>I would like to mock this message channel call in integration testing so that messages are not sent to Kafka. Currently using Wiremock for Spring Integration Testing.</p>
<p>Please suggest me the ways to mock the MessageChannel send method</p>
",https://stackoverflow.com/questions/68679545/how-to-mock-send-method-in-messagechannel-of-springboot-in-wiremock-integration,"['java', 'spring-boot', 'apache-kafka', 'integration-testing', 'wiremock']",935,False,0,1
integration testing in react native for dynamic dropdown list using testing-library/react-native,"<p>I Have wrote test case dropdown list its working fine when data of dropdown list is static</p>
<p>but its fails on dynamics data</p>
<p>so i called that api using <strong>rest.get(baseURL + <code>/location/getstates</code>, (req, res, ctx)</strong> and then i set response manually
still i getting error</p>
<p>any suggestion ? Where i went wrong ?</p>
<p><a href=""https://i.stack.imgur.com/XE255.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/XE255.png"" alt=""Error"" /></a></p>
<pre><code>import React from 'react';
import {
  fireEvent,
  render,
  waitFor,
  cleanup,
} from '@testing-library/react-native';
import {rest} from 'msw';
import {setupServer} from 'msw/node';
import {act, renderHook} from '@testing-library/react-hooks';
import EditProfile from '../Profile/ProfilEdit/InvestmentPreference';
import '@testing-library/jest-dom';
import {store} from '../../redux/store';
import {Provider} from 'react-redux';
import '@testing-library/jest-dom/extend-expect';
import {NavigationContainer} from '@react-navigation/native';
import {baseURL, postApi} from '../../helpers/api';
import AddProperty from '../Property/AddProperty';

const server = setupServer(
  rest.post(baseURL + `/property`, (req, res, ctx) =&gt; {
    console.log('res', req.body);
    return res(ctx.json({data: {data: {_id: '123'}}}));
  }),
  rest.get(baseURL + `/location/getstates`, (req, res, ctx) =&gt; {
    console.log('res', res);
    return res(
      ctx.json({
        data: {
          data: [
            {_id: '602fa607441edd89c26a9f82', name: 'Delhi'},
            {_id: '602fab68441edd89c26a9fe5', name: 'Gujarat'},
            {_id: '600977053d18389683c8babd', name: 'Karnataka'},
            {_id: '60097b65314a69997cf5593f', name: 'Maharashtra'},
            {_id: '602fab86441edd89c26a9fe6', name: 'Tamil Nadu'},
            {_id: '60097d1b314a69997cf55940', name: 'Telangana'},
            {_id: '602fab54441edd89c26a9fe4', name: 'West Bengal'},
          ],
        },
      }),
    );
  }),
);

beforeAll(() =&gt; server.listen());
afterEach(() =&gt; server.resetHandlers());
afterAll(() =&gt; server.close());

function renderWithRedux(component) {
  return {
    ...render(
      &lt;Provider store={store}&gt;
        &lt;NavigationContainer&gt;{component}&lt;/NavigationContainer&gt;
      &lt;/Provider&gt;,
    ),
  };
}

describe('AddProperty Screen', () =&gt; {
  it('should validate form', async () =&gt; {
    const callback = jest.fn();
    const navigation = {navigate: callback};
    const {getByTestId, getByPlaceholderText, getByText, getByDisplayValue} =
      renderWithRedux(
        &lt;AddProperty navigation={navigation} route={{params: {id: '123'}}} /&gt;,
      );

    const PropertyName = getByPlaceholderText('Property Name');
    const Khata = getByPlaceholderText('Khata');
    const ROI = getByPlaceholderText('Enter ROI');
    const EnterAmount = getByPlaceholderText('Enter Amount');
    const PropertySize = getByPlaceholderText('Enter Property Size');
    const BuildupArea = getByText('Buildup Area');
    const propertyStatus = getByText(new RegExp('Add Property Status', 'g'));
    fireEvent.press(propertyStatus);
    fireEvent.press(getByText(new RegExp('For Sale', 'g')));

    const propertyCurrentStatus = getByText(
      new RegExp('Add Property Position', 'g'),
    );
    fireEvent.press(propertyCurrentStatus);
    fireEvent.press(getByText(new RegExp('Rented', 'g')));

    const states = getByText(new RegExp('Select State', 'g'));
    fireEvent.press(states);
    fireEvent.press(getByText(new RegExp('Delhi', 'g')));

    expect(PropertyName).toBeDefined();
    expect(Khata).toBeDefined();
    expect(ROI).toBeDefined();
    expect(BuildupArea).toBeDefined();
    expect(EnterAmount).toBeDefined();
    expect(PropertySize).toBeDefined();
</code></pre>
",https://stackoverflow.com/questions/68480411/integration-testing-in-react-native-for-dynamic-dropdown-list-using-testing-libr,"['react-native', 'testing', 'jestjs']",355,True,1,1
How do I get Authorization working in ASP.net core integration testing (I&#39;m very close),"<p>I've followed <a href=""https://lukaszcoding.com/integration-testing-in-net-core/"" rel=""nofollow noreferrer"">these instructions</a> to get Authentication working with ASP.net core integration testing. It's very nearly working. My HttpContext.User is correctly populated with Claims. But my requests to Web API controllers with the <code>[Authorize]</code> attribute still fail, unless I specify the scheme: <code>[Authorize(AuthenticationSchemes = &quot;Test&quot;)]</code> works. I am careful to specify &quot;Test&quot; as the default scheme when I add it in my <code>builder.ConfigureTestServices()</code> method, so why isn't it being accepted as the default?</p>
<pre><code>builder.ConfigureTestServices(services =&gt;
{
    /* Overriding policies and adding Test Scheme defined in TestAuthHandler */
    services.AddMvc(options =&gt;
    {
        var policy = new AuthorizationPolicyBuilder(new[] { &quot;Test&quot; })
            .RequireAuthenticatedUser()
            .AddAuthenticationSchemes(&quot;Test&quot;)
            .Build();

        options.Filters.Add(new AuthorizeFilter(policy));
    });

    /* Adding Default Authentication schemes
        This is enough to prevent unauthorized client (if you wish to have that kind of tests) */
    services.AddAuthentication(options =&gt;
    {
        options.DefaultAuthenticateScheme = &quot;Test&quot;;
        options.DefaultChallengeScheme = &quot;Test&quot;;
        options.DefaultScheme = &quot;Test&quot;;
        options.DefaultForbidScheme = &quot;Test&quot;;
        options.DefaultChallengeScheme = &quot;Test&quot;;
        options.DefaultSignInScheme = &quot;Test&quot;;
        options.DefaultSignOutScheme = &quot;Test&quot;;
    })
    /* Here we're adding TestAuthentication Scheme with Handler that will Authenticate our client based on Claims */
    .AddScheme&lt;AuthenticationSchemeOptions, TestAuthHandler&gt;(&quot;Test&quot;, options =&gt; { });
});
</code></pre>
",https://stackoverflow.com/questions/70348066/how-do-i-get-authorization-working-in-asp-net-core-integration-testing-im-very,"['c#', 'asp.net-core', 'authentication']",521,False,0,0
Unable to launch from end to end Spring batch Job using groovy/spock - integration testing,"<p>I have recently start doing groovy testing in order to test a spring batch job that is using one step (ItemReader, ItemProcessor, ItemWriter)</p>
<p>Knowing that I am using h2 memory database, I have tried to launch the job also the step via the unit test, I am unable to verify that job has been completed:</p>
<pre><code>    def 'test launch job'() {
    given:
    def projectId = 1234L
    def fileType = FileType.TEST
    def sourceId = 1234506L
    def enteredBy = 'groovy_unit_test'
    def prePlanYear = 2022L

    when:
 
    JobParametersBuilder builder = new JobParametersBuilder();
    builder.addLong(&quot;projectId&quot;, projectId)
            .addString(&quot;fileType&quot;, fileType.toString())
            .addLong(&quot;sourceId&quot;, sourceId)
            .addString(&quot;enteredBy&quot;, enteredBy)
            .addLong(&quot;prePlanYear&quot;, prePlanYear)
    //JobExecution jobExecution = jobLauncher.launchJob( builder.toJobParameters())
    JobExecution jobExecution = jobLauncher.launchStep(JobConstants.StepNames.xwalkMappingStep.name(), builder.toJobParameters())
  then: 'Job completes with no errors.'
   jobExecution.status == BatchStatus.COMPLETED
   //jobExecution.exitStatus == ExitStatus.COMPLETED
}
</code></pre>
<p>the status of the job always remains STARTED:
<a href=""https://i.stack.imgur.com/2T0uq.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/2T0uq.png"" alt=""enter image description here"" /></a></p>
<p>Also, When I tried to debug it does not go from end to end, it stop in the ItemReader once the test has finished. I see that it doesn't wait for the job to be completed.</p>
<p>Is there a Way to complete the test only after the job has finished?</p>
<pre><code>@PropertySource('classpath:application.properties')
@ActiveProfiles('test')
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, properties = [&quot;spring.h2.console.enabled=true&quot;])
@ImportAutoConfiguration([ FeignAutoConfiguration.class])
@Import([TestConfig.class])
class BaseSpec extends Specification{

    @PersistenceContext
    EntityManager entityManager

    @Autowired
    JobRepository jobRepository

    @Autowired
    DataSource dataSource

    @Autowired
    JpaTransactionManager jpaTransactionManager

    @Autowired
    JobLauncherTestUtils jobLauncher

}

@Configuration
@EnableBatchProcessing
class TestConfig {
}
</code></pre>
<p>Thank you</p>
",https://stackoverflow.com/questions/67728968/unable-to-launch-from-end-to-end-spring-batch-job-using-groovy-spock-integrati,"['groovy', 'junit', 'spring-batch', 'spock']",168,True,0,1
Is there a way to follow a redirect url while doing integration testing in grails?,"<p>I am using grails 2.2</p>
<p>An integration test looks like this</p>
<pre><code>reservationController.params[&quot;participant&quot;] = [&quot;firstName&quot;: &quot;Hello&quot;, &quot;lastName&quot;: &quot;Hello&quot;, &quot;gender&quot;: &quot;MALE&quot;, 'phone': '1234567890','email': 'john@doe.com']

def mm = reservationController.save(m.sale.id)
</code></pre>
<p>Inside the save method of reservation contoller is a redirect at the end</p>
<pre><code>    redirect(action: &quot;referral&quot;, id: sale.id)
</code></pre>
<p>It seems like when i run integration test, after calling save it will not follow the redirect to 'referral'. When i add a breakpoint after reservationController.save() and then inspect reservationController.response.redirectedUrl then it shows the redirect url but it doesnt go to the redirected url.</p>
<p>Is there a way to follow the redirect url? i.e when i call .save on reservation controller it will complete the save method and also go to the redirected url and only it will return the model that the redirected url returns.</p>
<p>I appreciate any help.</p>
",https://stackoverflow.com/questions/67515050/is-there-a-way-to-follow-a-redirect-url-while-doing-integration-testing-in-grail,"['grails', 'integration-testing', 'grails-2.2']",36,False,0,0
Reactjs Integration Testing Cognito Native Crypto Module Could Not Be Used To Get Secure Random Number,"<p>I have an integration test that uses the AWS Cognito library; specifically, I'm calling CognitoUser.authenticateUser(). When I start my webpage this all works fine: however, in my tests I'm getting the following error:</p>
<pre><code>Error: Native crypto module could not be used to get secure random number.


at cryptoSecureRandomInt (/source/project/master/website/node_modules/amazon-cognito-identity-js/lib/utils/cryptoSecureRandomInt.web.js:38:9)
at WordArray.random (/source/project/master/website/node_modules/amazon-cognito-identity-js/lib/utils/WordArray.js:50:56)
at randomBytes (/source/project/master/website/node_modules/amazon-cognito-identity-js/lib/AuthenticationHelper.js:47:58)
at AuthenticationHelper.generateRandomSmallA (/source/project/master/website/node_modules/amazon-cognito-identity-js/lib/AuthenticationHelper.js:113:21)
at new AuthenticationHelper (/source/project/master/website/node_modules/amazon-cognito-identity-js/lib/AuthenticationHelper.js:67:29)
at CognitoUser.authenticateUserDefaultAuth (/source/project/master/website/node_modules/amazon-cognito-identity-js/lib/CognitoUser.js:264:32)
at CognitoUser.authenticateUser (/source/project/master/website/node_modules/amazon-cognito-identity-js/lib/CognitoUser.js:237:19)
</code></pre>
<p>Researching for answers I came across many posts suggesting:</p>
<pre><code> Object.defineProperty(global.self, 'crypto', {
        value: {
            getRandomValues: arr =&gt; crypto.randomBytes(arr.length),
        }
    }); 
</code></pre>
<p>Unfortunatley that does not work.</p>
<p>Looking at the crypto source:</p>
<pre><code> function cryptoSecureRandomInt() {
    if (crypto) {
        // Use getRandomValues method (Browser)
        if (typeof crypto.getRandomValues === 'function') {
            try {
                return crypto.getRandomValues(new Uint32Array(1))[0];
            } catch (err) {}
    } // Use randomBytes method (NodeJS)


    if (typeof crypto.randomBytes === 'function') {
        try {
            return crypto.randomBytes(4).readInt32LE();
        } catch (err) {}
        }
    }

    throw new Error('Native crypto module could not be used to get secure random number.');
  }
</code></pre>
<p>I can see where this error is being thrown. I'm guessing that under normal circumstances the crypto package is loaded by the browser which obviously doesn't exist when testing.</p>
<p>Any suggestions?</p>
<p><strong>Update 1</strong></p>
<p>Stepped through using the debugger and in the crypto source it's getting undefined for the 'crypto' variable on this line</p>
<pre><code> if (crypto) {
</code></pre>
<p>This means that the Object.defineProperty is not working. I tried attaching it to the window but that doesn't work either</p>
<pre><code> Object.defineProperty(window, 'crypto', {
        value: {
            getRandomValues: (arr) =&gt; crypto.randomBytes(arr.length)
        }
    });
</code></pre>
",https://stackoverflow.com/questions/69070625/reactjs-integration-testing-cognito-native-crypto-module-could-not-be-used-to-ge,"['reactjs', 'amazon-cognito', 'aws-sdk-js']",608,False,3,0
What should be the strategy for integration testing Jms Listeners/Consumers in a Spring Boot Application?,"<p>We have a Spring Boot JMS Listener Application that is made up of a Jms Listener, a service orchestration class, and a number of service classes underneath that orchestration class. The application requires integration testing. Originally, I was thinking about testing it using a combination of Spring Test and Mockito, but in order to do that, I would need to use create my mocks and then use them in two separate threads (thread[main] for the test and thread[DefaultMessageListenerContainer-1] for the Jms Listener) and as far as I understand, Mockito <strong>only</strong> keeps its state in Threadlocal as shown in their <a href=""https://github.com/mockito/mockito/wiki/FAQ#why-does-mockito-keep-threadlocal-state"" rel=""nofollow noreferrer"">documentation</a>. Please see the quote below.</p>
<blockquote>
<p>Mockito uses ThreadLocal
state to implement a gorgeous mocking syntax in a language full of
constraints (yes, it's java). Fortunately, every time you interact
with Mockito framework it validates the ThreadLocal state in case you
misused the api.</p>
</blockquote>
<p>Given this, I was thinking about having two separate test classes, one which will test that the listener is properly wired and it is able to take a message, and the other will test the service orchestrator and the service classes behaviour. Please let me know if there are other alternatives to this strategy that allows me to test both under the same test class.</p>
<p>Thanks,</p>
<p>Juan</p>
",https://stackoverflow.com/questions/66646831/what-should-be-the-strategy-for-integration-testing-jms-listeners-consumers-in-a,"['spring-boot', 'junit', 'mockito', 'spring-jms', 'spring-test']",602,True,1,1
How do I replace service implementations for Web API integration testing using TestHost.TestServer in .NET 5,"<p>I am trying to move my integration tests from <code>WebApplicationFactory</code> to <code>TestServer</code> in .NET 5. In my existing implementation I can override <code>ConfigureWebHost</code> and call <code>IWebHostBuilder.ConfigureServices</code> to replace service implementations with mocks. This runs after the <code>Startup</code> code, allowing me to remove the production implementation and add the mock.</p>
<p>When trying to achieve the same thing using <code>TestServer</code>, <code>ConfigureServices</code> always runs <em>before</em> the <code>Startup</code> code, no matter in which order I do the configuration, meaning I always end up with both implementations in the services collection and it seems &quot;last one wins&quot;, i.e. the prod version of the service always runs.</p>
<p>How can I configure the builder to use my test version?</p>
<p>I am using XUnit, so perhaps am not using it in the right way re <code>IClassFixture</code> etc.</p>
<p>Here is my code:</p>
<pre class=""lang-cs prettyprint-override""><code>public sealed class IntegrationTests : IDisposable
{
    private TestServer Server { get; }
    private HttpClient Client { get; }

    public IntegrationTests()
    {
        var builder = new WebHostBuilder()
            .UseConfiguration(new ConfigurationBuilder().AddJsonFile(&quot;appsettings.development.json&quot;).Build())
            .UseSerilog()
            // Changing the order of the following two lines doesn't help
            .UseStartup&lt;Startup&gt;()
            .ConfigureServices(UseDummyUserRepository);

        Server = new TestServer(builder);
        Client = Server.CreateClient();
    }

    private void UseDummyUserRepository(IServiceCollection services)
    {
        //Following line doesn't work as the service is not yet configured
        //services.Remove(services.First(s =&gt; s.ServiceType == typeof(IUserRepository)));
        services.AddTransient&lt;IUserRepository, DummyUserRepository&gt;();
    }
</code></pre>
",https://stackoverflow.com/questions/70019195/how-do-i-replace-service-implementations-for-web-api-integration-testing-using-t,"['.net', 'integration-testing', 'xunit', 'webapi', 'testserver']",196,False,0,2
ASP.NET Core TestHost Integration Testing &#39;System.ArgumentNullException : String reference not set to an instance of a String.&#39;,"<p>I am implemeting integration testing using xunit and</p>
<pre><code>&lt;PackageReference Include=&quot;Microsoft.AspNetCore.TestHost&quot; Version=&quot;2.0.0&quot; /&gt;
</code></pre>
<p>following this tutorial:
<a href=""https://dotnetcorecentral.com/blog/asp-net-core-web-api-integration-testing-with-xunit/"" rel=""nofollow noreferrer"">https://dotnetcorecentral.com/blog/asp-net-core-web-api-integration-testing-with-xunit/</a></p>
<p>When I run my test I get this message</p>
<blockquote>
<p>String reference not set to an instance of a String</p>
<p>IntegrationTests.Categories.TestAdd:<br />
Outcome: Failed<br />
Error Message:<br />
System.ArgumentNullException : String reference not set to an instance of a String.</p>
<p>Parameter name: s</p>
<p>Stack Trace:</p>
<p>at System.Text.Encoding.GetBytes(String s)<br />
at Dopshop.Startup.ConfigureServices(IServiceCollection services) in /Users/josueaceves/Desktop/dopshop/Startup.cs:line 114<br />
--- End of stack trace from previous location where exception was   thrown ---<br />
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)<br />
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()<br />
at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()<br />
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()<br />
at Microsoft.AspNetCore.TestHost.TestServer..ctor(IWebHostBuilder builder, IFeatureCollection featureCollection)<br />
at IntegrationTests.TestClientProvider..ctor() in /Users/josueaceves/Desktop/dopshop/IntegrationTests/TestClientProvider.cs:line 17<br />
at IntegrationTests.Categories.TestAdd() in /Users/josueaceves/Desktop/dopshop/IntegrationTests/Categories.cs:line 31<br />
--- End of stack trace from previous location where exception was thrown ---</p>
<p>IntegrationTests.Categories.TestGetAll:<br />
Outcome: Failed<br />
Error Message:<br />
System.ArgumentNullException : String reference not set to an instance of a String.</p>
<p>Parameter name: s</p>
<p>Stack Trace:</p>
<p>at System.Text.Encoding.GetBytes(String s)<br />
at Dopshop.Startup.ConfigureServices(IServiceCollection services) in /Users/josueaceves/Desktop/dopshop/Startup.cs:line 114<br />
--- End of stack trace from previous location where exception was thrown ---<br />
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)<br />
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()<br />
at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()<br />
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()<br />
at Microsoft.AspNetCore.TestHost.TestServer..ctor(IWebHostBuilder builder, IFeatureCollection featureCollection)<br />
at IntegrationTests.TestClientProvider..ctor() in /Users/josueaceves/Desktop/dopshop/IntegrationTests/TestClientProvider.cs:line 17<br />
at IntegrationTests.Categories.TestGetAll() in /Users/josueaceves/Desktop/dopshop/IntegrationTests/Categories.cs:line 19<br />
--- End of stack trace from previous location where exception was thrown ---</p>
<p>Total tests: 2. Passed: 0. Failed: 2. Skipped: 0</p>
</blockquote>
<p>this is at the startup file line 114:</p>
<pre><code>TokenValidationParameters validationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                    .GetBytes(this.Configuration.GetSection(&quot;AppSettings:Token&quot;).Value)),
                ValidateIssuer = false,
                ValidateAudience = false
            };

</code></pre>
<p>I have my <code>ClientTestProvider</code>:</p>
<pre><code>using System;
using System.Net.Http;
using Dopshop;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;

namespace IntegrationTests
{
    public class TestClientProvider
    {
        private TestServer server;
        public HttpClient Client { get; private set; }

        public TestClientProvider()
        {

            server = new TestServer(new WebHostBuilder().UseStartup&lt;Startup&gt;());

            Client =  server.CreateClient();
        }
    }
}
</code></pre>
<p>And my two integration tests</p>
<pre><code>using System.Net;
using System.Threading.Tasks;
using Contracts.v1;
using Xunit;
using FluentAssertions;
using System.Net.Http;
using Newtonsoft.Json;
using System.Text;
using Dopshop.Models;

namespace IntegrationTests
{
    public class Categories
    {
        [Fact]
        public async Task TestGetAll()
        {
            using (var client = new TestClientProvider().Client)
            {
                var response = await client.GetAsync(ApiRoutes.Categories.GetAll);
                response.EnsureSuccessStatusCode();

                response.StatusCode.Should().Be(HttpStatusCode.OK);
            }
        }

        [Fact]
        public async Task TestAdd()
        {
            using (var client = new TestClientProvider().Client)
            {
                var response = await client.PostAsync(ApiRoutes.Categories.Add
                    , new StringContent(
                        JsonConvert.SerializeObject(new Category(){Name = &quot;nike Shoes&quot;, Description = &quot;shoe category&quot;, Sequence = 2, ShopId = 3}), 
                        Encoding.UTF8, 
                        &quot;application/json&quot;));

                response.EnsureSuccessStatusCode();

                response.StatusCode.Should().Be(HttpStatusCode.OK);
            }
        }
    }
} 
</code></pre>
<p>Does anyone have an idea what's going on? I'm new to testing in .NET Core. If anyone could point me in the right direction it would be highly appreciated.</p>
<pre><code>&lt;PackageReference Include=&quot;FluentValidation.AspNetCore&quot; Version=&quot;9.1.1&quot;/&gt;
&lt;PackageReference Include=&quot;Microsoft.AspNetCore.App&quot;/&gt;
&lt;PackageReference Include=&quot;Pomelo.EntityFrameworkCore.MySql&quot; Version=&quot;2.1.1&quot;/&gt;
&lt;PackageReference Include=&quot;AutoMapper.Extensions.Microsoft.DependencyInjection&quot; Version=&quot;7.0.0&quot;/&gt;
&lt;PackageReference Include=&quot;Swashbuckle.AspNetCore&quot; Version=&quot;5.4.0&quot;/&gt;
&lt;PackageReference Include=&quot;CloudinaryDotNet&quot; Version=&quot;1.11.0&quot;/&gt;
&lt;PackageReference Include=&quot;xunit&quot; Version=&quot;2.4.0&quot;/&gt;
&lt;PackageReference Include=&quot;xunit.runner.visualstudio&quot; Version=&quot;2.4.0&quot;/&gt;
&lt;PackageReference Include=&quot;Moq&quot; Version=&quot;4.14.5&quot;/&gt;
&lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;16.7.1&quot;/&gt;
&lt;PackageReference Include=&quot;SendGrid&quot; Version=&quot;9.21.0&quot;/&gt;
&lt;PackageReference Include=&quot;Microsoft.AspNetCore.TestHost&quot; Version=&quot;2.0.0&quot; /&gt;
&lt;PackageReference Include=&quot;FluentAssertions&quot; Version=&quot;5.10.3&quot; /&gt; 
</code></pre>
<p>this is the startup file</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Authorization;
using AutoMapper;
using Data;
using Filters;
using FluentValidation.AspNetCore;
using Dopshop.Models;
using Dopshop.Services.Email;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Repositories.Implementations;
using Repositories.Interfaces;
using Services.Email;
using Services.Photos;
using Settings;
using Microsoft.AspNetCore.Http;
using static Contracts.v1.Validation.Validators;
using Newtonsoft.Json.Linq;
using System.Net;
using Services.Authentication;

namespace Dopshop
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext&lt;DopshopContext&gt;(x =&gt; x.UseMySql(Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));
            
            services.AddMvc(options =&gt; {
                options.Filters.Add&lt;ValidationFilter&gt;();
            })
                .AddJsonOptions(options =&gt; {
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddFluentValidation(fv =&gt; fv.RegisterValidatorsFromAssemblyContaining&lt;CreateShopValidator&gt;());;
            
            services.Configure&lt;ApiBehaviorOptions&gt;(options =&gt;
            {
                options.SuppressModelStateInvalidFilter = true;
            });
            
            services.AddCors(options =&gt; {
                options.AddPolicy(name: &quot;ProductionPolicy&quot;,
                    builder =&gt; {
                        builder.WithOrigins(&quot;https://hustlr.azurewebsites.net&quot;,
                                            &quot;https://hustlr.cards&quot;, 
                                            &quot;https://hustlr-39c77.web.app&quot;, 
                                            &quot;https://hustlr-39c77.firebaseapp.com&quot;)
                                            .WithMethods(&quot;*&quot;)
                                            .WithHeaders(&quot;*&quot;);
                    });
            });

            services.AddSwaggerGen(option =&gt; {

                option.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo{ Title  = &quot;Dopshop API&quot;, Version = &quot;v1&quot;});

                option.AddSecurityDefinition(&quot;Bearer&quot;, new OpenApiSecurityScheme
                {
                    Description = &quot;JWT Authorization header using the bearer scheme&quot;,
                    Name = &quot;Authorization&quot;,
                    In = Microsoft.OpenApi.Models.ParameterLocation.Header,
                    Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
                    Scheme = &quot;Bearer&quot;
                });
                
                option.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = &quot;Bearer&quot;
                            },
                            Scheme = &quot;oauth2&quot;,
                            Name = &quot;Bearer&quot;,
                            In = ParameterLocation.Header,

                        },
                        new List&lt;string&gt;()
                    }
                });
                
                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $&quot;{Assembly.GetExecutingAssembly().GetName().Name}.xml&quot;;
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                option.IncludeXmlComments(xmlPath);
                });

            TokenValidationParameters validationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                    .GetBytes(this.Configuration.GetSection(&quot;AppSettings:Token&quot;).Value)),
                ValidateIssuer = false,
                ValidateAudience = false
            };

            services.AddAuthentication(options =&gt; 
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =&gt; {
                    options.SaveToken = true;
                    options.TokenValidationParameters = validationParameters;
                    options.Events = new JwtBearerEvents();
                    options.Events.OnChallenge = context =&gt;
                    {
                        // Skip the default logic.
                        context.HandleResponse();

                        var payload = new JObject
                        {
                            [&quot;code&quot;] = 401,
                            [&quot;message&quot;] = &quot;Invalid JWT Token&quot;
                        };

                        context.Response.ContentType = &quot;application/json&quot;;
                        context.Response.StatusCode = 401;

                        return context.Response.WriteAsync(payload.ToString());
                    };
            });

            services.AddSingleton&lt;TokenValidationParameters&gt;(validationParameters);

            services.Configure&lt;CloudinarySettings&gt;(Configuration.GetSection(&quot;CloudinarySettings&quot;));
            services.Configure&lt;SendGridAPISettings&gt;(Configuration.GetSection(&quot;SendGridSettings&quot;));
            
            services.AddAutoMapper(typeof(Startup).Assembly);

            services.AddTransient&lt;IShopRepository, ShopRepository&gt;();
            services.AddTransient&lt;IAuthRepository, AuthRepository&gt;();
            services.AddTransient&lt;IUserRepository, UserRepository&gt;();
            services.AddTransient&lt;IProductRepository, ProductRepository&gt;();
            services.AddTransient&lt;ICategoryRepository, CategoryRepository&gt;();
            services.AddTransient&lt;IProductCategoryRepository, ProductCategoryRepository&gt;();
            services.AddTransient&lt;IPhotoRepository, PhotoRepository&gt;();
            services.AddTransient&lt;IProductPhotosRepository, ProductPhotosRepository&gt;();
            services.AddTransient&lt;IReviewsRepository, ReviewsRepository&gt;();
            services.AddTransient&lt;ICategoryRepository, CategoryRepository&gt;();
            services.AddTransient&lt;IGenericRepository&lt;ReviewPhoto&gt;, GenericRepository&lt;ReviewPhoto&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;ShopTheme&gt;, GenericRepository&lt;ShopTheme&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;Currency&gt;, GenericRepository&lt;Currency&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;Industry&gt;, GenericRepository&lt;Industry&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;ShopLocation&gt;, GenericRepository&lt;ShopLocation&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;ShopPaymentMethod&gt;, GenericRepository&lt;ShopPaymentMethod&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;PaymentMethodType&gt;, GenericRepository&lt;PaymentMethodType&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;SocialLink&gt;, GenericRepository&lt;SocialLink&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;LinkType&gt;, GenericRepository&lt;LinkType&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;Category&gt;, GenericRepository&lt;Category&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;ProductCategory&gt;, GenericRepository&lt;ProductCategory&gt;&gt;();
            services.AddTransient&lt;IProductOptionRepository, ProductOptionRepository&gt;();
            services.AddTransient&lt;IProductOptionValueRepository, ProductOptionValueRepository&gt;();
            services.AddTransient&lt;IProductQuestionRepository, ProductQuestionRepository&gt;();
            services.AddTransient&lt;IProductVariationRepository, ProductVariationRepository&gt;();
            services.AddTransient&lt;IProductOptionValueVariationRepository, ProductOptionValueVariationRepository&gt;();
            services.AddTransient&lt;IRefreshTokenRepository, RefreshTokenRepository&gt;();
            services.AddTransient&lt;ISocialLinkRepository, ShopSocialLinkRepository&gt;();
            services.AddTransient&lt;IShopPaymentMethodsRepository, ShopPaymentMethodsRepository&gt;();
            services.AddTransient&lt;IReviewSentimentRepository, ReviewSentimentRepository&gt;();
            services.AddTransient&lt;IPasswordRecoveryRepository, PasswordRecoveryRepository&gt;();
            services.AddTransient&lt;IEmailService, SendGridEmailSender&gt;();
            services.AddTransient&lt;IPhotosService, CloudinaryPhotosService&gt;();
            services.AddTransient&lt;IAuthorizationHandlers, AuthorizationHandlers&gt;();
            services.AddTransient&lt;IAuthTokenGenerator, AuthTokenGenerator&gt;();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseCors(x =&gt; x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
                app.UseSwagger();
                app.UseSwaggerUI(c =&gt; { 
                    c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;Hustlr API V1&quot;);
                    c.RoutePrefix = string.Empty;
                });

                app.UseDefaultFiles();
                app.UseStaticFiles();
            }
            else
            {
                app.UseCors(&quot;ProductionPolicy&quot;);
                app.UseHsts();
                //app.UseHttpsRedirection();
            }

            app.UseStatusCodePages(context =&gt; {
                var request = context.HttpContext.Request;
                var response = context.HttpContext.Response;
                response.ContentType = &quot;application/json&quot;;
                if (response.StatusCode == (int)HttpStatusCode.Unauthorized)
                {
                    var payload = new JObject
                    {
                        [&quot;code&quot;] = 401,
                        [&quot;message&quot;] = &quot;Unauthorized&quot;
                    };
                    response.WriteAsync(payload.ToString());
                }

                return Task.CompletedTask;
            });
            
            app.UseAuthentication();
            app.UseMvc();
        }
    }
}
</code></pre>
<p>this is my Program.cs file</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Data;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Dopshop
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var db = scope.ServiceProvider.GetService&lt;DopshopContext&gt;();
                db.Database.Migrate();
            }

            host.Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =&gt;
            WebHost.CreateDefaultBuilder(args)
                .UseStartup&lt;Startup&gt;()
                .UseUrls(&quot;http://*:5000&quot;);
    }
}
</code></pre>
",https://stackoverflow.com/questions/68029542/asp-net-core-testhost-integration-testing-system-argumentnullexception-string,"['c#', 'asp.net', 'asp.net-core', 'integration-testing', 'xunit.net']",872,True,0,1
Flutter firebase-auth integration testing signInWithCredential error: The caller does not have permission to execute the specified,"<p>I'm trying to run integration tests on my flutter app.
One of the flows I want to test is the Login flow. There is a firebase phone number authentication in the app.
When I'm trying to call signInWithCredential to sign in with the test phone number and test verification code, I'm getting an error:</p>
<pre><code>I/flutter (24151): The following FirebaseException was thrown running a test:
I/flutter (24151): [cloud_firestore/permission-denied] The caller does not have permission to execute the specified
I/flutter (24151): operation.
</code></pre>
<p>It looks like the SHA1 fingerprint configured in the Firebase project doesn't match the flutter driver app. Maybe I'm wrong about it.
My question is how to run an integration test for an app with firebase-auth. And I'm right about SHA1 - how to set up a singing configuration for the flutter driver app?</p>
",https://stackoverflow.com/questions/70186824/flutter-firebase-auth-integration-testing-signinwithcredential-error-the-caller,"['flutter', 'firebase-authentication', 'flutterdriver', 'flutter-integration-test']",170,False,2,0
How to do integration testing with spring and junit by scanning classpath instead of manually specifying classes to autowire?,"<p>I'm trying to do some sort of integration testing (not really full testing, only it's not  really unit testing either) on a service :</p>
<pre><code>package foo;


@Component
public class FooService {}
</code></pre>
<p>And the corresponding test :</p>
<pre><code>package foo;

@SpringBootTest
public FooTest {
   @Autowired FooService fooService;
}
</code></pre>
<p>Only when I try to test it says</p>
<pre><code>No qualifying bean of type 'foo.FooService' available
</code></pre>
<p>I could add the class to <code>@SpringBootTest</code> like this :</p>
<pre><code>@SpringBootTest(classes = {FooService.class})
</code></pre>
<p>But I don't want to manually select the classes I want to test. My application is much larger than the MWE, and I want to test without having to specify each class I am testing and their respective dependencies.</p>
<p>Is there anyway to tell spring to scan and autowire dependencies like it would outside of tests ?</p>
",https://stackoverflow.com/questions/69741747/how-to-do-integration-testing-with-spring-and-junit-by-scanning-classpath-instea,"['java', 'spring', 'testing']",98,True,0,1
how to create epic in jira- epics in jira,"<p>scenario : We are in the integration testing phase . We would like to group all bugs in this phase on JIRA .</p>
<p>My problem : I wanted to create an epic called &quot;testing phase&quot; and group all bugs in the testing phase . But I also wanted to create a subgroup for &quot;integration testing&quot; and group all bugs in this integration testing phase . How do I do this .Can I use tasks under epic and do this ?</p>
",https://stackoverflow.com/questions/67965788/how-to-create-epic-in-jira-epics-in-jira,['automation'],50,False,-1,1
Stage environment for Serverless Framework integration testing,"<p>Serverless Framework has its own integration testing of endpoints, as defined <a href=""https://www.serverless.com/framework/docs/guides/testing/"" rel=""nofollow noreferrer"">here</a>. The documentation does not mention any staging or parameters that can be used for complex authentication or other setup work that may need to be done to verify an endpoint is correctly setup.</p>
<p>Is it possible to use Serverless Framework's integration testing tool with staged information? If so, how? If not, what is the intended purpose of this integration testing framework - simply to verify that an endpoint returns unauthorized errors?</p>
",https://stackoverflow.com/questions/66790160/stage-environment-for-serverless-framework-integration-testing,"['serverless-framework', 'serverless']",48,False,-1,1
How to Mock send method in MessageChannel of SpringBoot in Wiremock Integration Testing,"<p>I am using Spring Boot Java for my application. The application is sending some messages to Kafka using MessageChannel. Ex: this.messageChannel.send(message).</p>
<p>I would like to mock this message channel call in integration testing so that messages are not sent to Kafka. Currently using Wiremock for Spring Integration Testing.</p>
<p>Please suggest me the ways to mock the MessageChannel send method</p>
",https://stackoverflow.com/questions/68679545/how-to-mock-send-method-in-messagechannel-of-springboot-in-wiremock-integration,"['java', 'spring-boot', 'apache-kafka', 'integration-testing', 'wiremock']",935,False,0,1
Spring boot integration testing issue,"<p>I am working on a project, i have completed but issue is in project i have to write integration testing code.</p>
<blockquote>
<p>This is the controller</p>
</blockquote>
<pre><code> @PostMapping(&quot;/newgame&quot;)
    public ResponseEntity&lt;Players&gt; beginNewGame(@RequestBody Players players) {

        Players savedPersion = playerService.beginNewGame(players);

        return savedPersion!=null ?  ResponseEntity.ok(savedPersion):
                (ResponseEntity&lt;Players&gt;) ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
}
</code></pre>
<blockquote>
<p>And this is service.</p>
</blockquote>
<pre><code>@Override
    public Players beginNewGame(Players players) {

            //new game state
            GameState gameState =new GameState();
            gameState.setWinner(&quot;null&quot;);


        GameState save = gameStateRepositery.save(gameState);

        //new score
        Score score = new Score();
        score.setGameId(save.getId());

        Score savedScore = scoreRepositery.save(score);
        players.setScoreId(savedScore.getId());
        players.setGameId(save.getId());

        Players savedPlayers=null;
            savedPlayers= playersRepositery.save(players);

        System.out.println(savedScore.getGameId()+&quot;ksdjfkjskn&quot;);

       return savedPlayers;
    }
</code></pre>
<blockquote>
<p>And if i hit the endpoints with proper required parameters, the is
working fine, and return me.</p>
</blockquote>
<pre><code>{
    &quot;gameId&quot;: 57,
    &quot;id&quot;: 1,
    &quot;playerOne&quot;: &quot;vinitSaini&quot;,
    &quot;playerTwo&quot;: &quot;anonymousKal&quot;,
    &quot;scoreId&quot;: 58
}
</code></pre>
<blockquote>
<p>This is the testing code, how i can check  what the response is
returning.</p>
</blockquote>
<pre><code>@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
public class PlayersIntTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private PlayersRepositery playersRepositery;


    @Test
    void newGame() throws Exception {
        
        //mockMvc.perform(post(&quot;/api/{forumId}/register&quot;, 42L)
        mockMvc.perform(post(&quot;/api/newgame&quot;)
                .contentType(&quot;application/json&quot;)
                .content(objectMapper.writeValueAsString(players)))
                .andExpect(status().isOk());




    }
</code></pre>
<p><strong>So please help me to write integration testing.</strong></p>
",https://stackoverflow.com/questions/67252093/spring-boot-integration-testing-issue,"['java', 'spring', 'spring-boot', 'spring-mvc', 'testing']",126,False,1,2
Is SemVer redundant for continuous delivery?,"<p>We are developing distributed system with continuous delivery.</p>
<p>Releases are being scheduled, tagged with non-technical marketing version names. Each release aggregates set of changed components with desired features, verified by integration testing pipeline. We aren't deploying continuously to production, but we <em>do</em> deploy continuously to test environment for release candidates integration testing.</p>
<p>System components are frontend, backend, adapter module and a shared database. They are packaged as docker containers. We use Docker registry as an artifact repository and docker compose to integrate the <code>latest</code> versions of each component for integration testing. See the following DAG diagram for pipelines and their dependencies. Basically change in the upstream project triggers a rebuild of each downstream project, until leaf nodes are reached. Integration testing is triggered, when leaf node docker image is pushed to registry. Trigger logic is codified in the registry webhooks.</p>
<p><a href=""https://i.stack.imgur.com/0eGS4.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0eGS4.png"" alt=""enter image description here"" /></a></p>
<p>Obviously components needs some technical version to associate production releases to particular builds of components for tracing and reproducing purposes. Currently, each master build is tagged with a semantic version. But is using SemVer and git tagging redundant in this case? Can we use just git hashes and build numbers instead? I don't see any additional value from using semantic versioning in this case. Automated changelog is a requirement.</p>
<p>Also, what is the best way include actual version number in docker container started with the <code>latest</code> tag by integration testing pipeline? Ideally, from integration pipeline results I would like to see actual component versions used for successful test run.</p>
<p>I would like to also hear, if this solution contains any anti-pattern or sub-optimal design.</p>
",https://stackoverflow.com/questions/66928716/is-semver-redundant-for-continuous-delivery,"['continuous-integration', 'microservices', 'release', 'continuous-deployment', 'semantic-versioning']",674,True,3,1
I can&#39;t target the Google Login for integration testing,"<p>Currently I'm trying to build out the integration testing for an app that someone else built.  I'm stuck with the Google sign in.</p>
<p>Specifically, the integration testing can't find the Google pop-up page.</p>
<p>Is there any way to use integration testing for the Google sign?</p>
<p>If not, how do I use integration to start on any page I choose for testing?</p>
<p>Please note that I have not built the app; I'm here to test the app.</p>
<p>I've tried to find a page or anything in the files and folders for the pop-up but I can't find anything.</p>
<p>I've even tried using Dart DevTools but I still can't target the sign-in page.</p>
<p>At the very least, can I bypass this step and start the integration on a different page?</p>
<p>Below is a picture of the sign-in page I'm trying to get the Flutter Integration test to interact with.  Note that it has been modified for privacy reasons.</p>
<p><a href=""https://i.stack.imgur.com/oYTdK.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/oYTdK.jpg"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/66884113/i-cant-target-the-google-login-for-integration-testing,"['flutter', 'dart', 'integration-testing', 'google-signin', 'flutter-integration-test']",199,False,3,0
Getting invalid method reference,"<p>I am working on a Junit5 integration testing with spring-test-mongo. While executing the below code, I am facing <strong>invalid method reference</strong> error.</p>
<pre><code>import com.jupiter.tools.spring.test.mongo.annotation.MongoDataSet;
import com.jupiter.tools.spring.test.mongo.junit5.meta.annotation.MongoDbIntegrationTest;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;

@MongoDbIntegrationTest
public class JUnit5ExampleTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    @MongoDataSet(value = &quot;/dataset/bar_dataset.json&quot;)
    void testPopulatingByMongoDataSet() throws Exception {

        Bar simpleDoc = mongoTemplate.findById(&quot;55f3ed00b1375a48e618300b&quot;, Bar.class);

        Assertions.assertThat(simpleDoc)
                .isNotNull()
                .extracting(Bar::getId, Bar::getData);

    }
}
</code></pre>
<p>Bar.class</p>
<pre><code>import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Bar {

    @Id
    private String id;

    private String data;
}
</code></pre>
<p>build.gradle:</p>
<pre><code>plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.projectlombok:lombok:1.18.20'
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
    testImplementation 'com.jupiter-tools:spring-test-mongo:0.15'
    testImplementation 'org.springframework.boot:spring-boot-starter-data-mongodb:2.5.4'
    testImplementation 'org.springframework.boot:spring-boot-starter-test:2.5.4'
    testImplementation 'org.projectlombok:lombok:1.16.20'

}

test {
    useJUnitPlatform()
}
</code></pre>
<p><a href=""https://i.stack.imgur.com/HY8iU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/HY8iU.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/69190382/getting-invalid-method-reference,"['java', 'lombok']",205,False,1,0
Integration testing using Flutter Driver for OTPTextField widget in flutter,"<p>I am trying to do integration testing using flutter driver. I am using await driver.enterText(find.byType('OTPTextField')) to enter the otp using flutter driver. But it's stuck at that screen and does nothing and the test fails after termination error. The OTPTextField widget kind of has a different UI than normal text field. I am not sure whether enterText function will work in this or not. If not, what are some alternatives?</p>
<p>Here is my code for <a href=""https://pub.dev/packages/otp_text_field"" rel=""nofollow noreferrer"">OTPTextField</a> widget:</p>
<pre><code>OTPTextField(
                key: const Key('otpvalue'),
                length: 6,
                textFieldAlignment: MainAxisAlignment.spaceAround,
                fieldWidth: 30,
                fieldStyle: FieldStyle.underline,
                width: MediaQuery.of(context).size.width / 2,
                style: TextStyle(
                    fontSize: 17,
                    color: Colors.black,
                    fontWeight: FontWeight.bold),
                onCompleted: (pin) async {
                  print(&quot;Completed: &quot; + pin);
                  print(_user.status);
                  if (_user.status == Status.VerifyingOTP ||
                      _user.status == Status.VerifiedOTP) {
                    Navigator.of(context).push(
                        MaterialPageRoute(builder: (_) =&gt; LoaderScreen()));
                      return;
                  }
                  if (widget.isSignup) {
                    if (await _user.signUpWithPhoneNumber(
                      pin.toString(),
                      context,
                      email: widget.emailId,
                      firstName: widget.firstName,
                      lastName: widget.lastName,
                    )) {
                      Navigator.of(context).pushReplacement(
                          MaterialPageRoute(
                              builder: (context) =&gt; OtpVerified()));
                    } else {
                      Navigator.of(context).push(
                          MaterialPageRoute(
                              builder: (context) =&gt; LoaderScreen()));
                    }
                  } else {
                    if (await _user.signInWithPhoneNumber(
                        pin.toString(), context, _user.language, _user.country)) {
                      Navigator.of(context).pushReplacement(
                          MaterialPageRoute(
                              builder: (context) =&gt; OtpVerified()));
                    } else {
                      Navigator.of(context).push(
                          MaterialPageRoute(
                              builder: (context) =&gt; LoaderScreen()));
                    }
                  }
                },
              ),
</code></pre>
<p>And here is the code for integration testing what I tried for this widget.</p>
<pre><code>test('enter otp', () async {
 SerializableFinder enterotp = find.byValueKey('otpvalue');
  await driver.tap(enterotp);
  await driver.enterText('123456');
  expect(await driver.getText(enterotp), &quot;123456&quot;);
});
</code></pre>
",https://stackoverflow.com/questions/69235101/integration-testing-using-flutter-driver-for-otptextfield-widget-in-flutter,"['flutter', 'dart', 'integration-testing', 'flutter-test', 'flutterdriver']",935,False,0,1
How to run python programs having command line arguments in jenkins job,"<p>I have a python project having programs accepts command line arguments. I wanted to do integration testing. How can I run these program as Jenkins job ?</p>
",https://stackoverflow.com/questions/69570561/how-to-run-python-programs-having-command-line-arguments-in-jenkins-job,"['python', 'jenkins']",31,False,0,0
How do I test my service which is calling a 3 party rest endpoint?,"<p>I'm trying to test my service which is sending a rest request to a 3rd party rest endpoint which is mocked during the integration testing (Assume that I know the required Request Body). The code provided is only a rough outline of what I'm trying to achieve. The rest endpoint itself may not be available at all times, which is why I want to mock it. Let's look at the pseudo-code:</p>
<p>First my test case:</p>
<pre class=""lang-java prettyprint-override""><code>public class FooExampleTest {

    private ExampleService exampleService;

    @BeforeEach
    void setup() {
        
        exampleService = new ExampleService();
        
    }

    @Test
    void example_TestCase() {

        SomeEntity entity = new SomeEntity();
        entity.setFoo(&quot;Foo!&quot;);
        // set more fields....
  
        // Calling the service containing the rest request to the 3rd party system
        exampleService.sendToClient(entity);

    }
}
</code></pre>
<p>The service containing the request to the 3rd party system is mocked</p>
<pre class=""lang-java prettyprint-override""><code>@Service
public class SomeServiceImpl {
  
    // some fields
    // ...
    @Autowired
    private RestTemplate restTemplate;


   // ......


    public void sendToClient(Entity entity){
        var uri = &quot;http://localhost:8080/foo&quot;
        var clientSystem = new ClientSystemRequest();
        clientSystem.setImportField(entity)
        log.info(&quot;Sending reqeust to client system&quot;);
        
        restTemplate.postForObject(uri, clientSystem, ClientSystemResponse.class);
    }

}

</code></pre>
<p>The 3rd party rest endpoint should be mocked during integration testing</p>
<pre class=""lang-java prettyprint-override""><code>
@RestController
@Slf4j
/**
 * Mocks the 3rd party rest endpoint
 */
public class 3rdPartyClientsystemResourceTest {
    

    @PostMapping(&quot;/foo&quot;)
    public ResponseEntity&lt;?&gt; foo(@RequestBody @Valid ClientSystemRequest clientSystemRequest){
        log.info(&quot;Received, with data: {}&quot;, clientSystemRequest);
        
        // Do some sort of validation....

        return new ResponseEntity&lt;&gt;(HttpStatus.OK);
    }


}

</code></pre>
",https://stackoverflow.com/questions/69574830/how-do-i-test-my-service-which-is-calling-a-3-party-rest-endpoint,"['java', 'spring', 'spring-boot', 'integration-testing']",404,True,2,1
Writing Test cases for Spring Integration Application,"<p>I am new for Unit/Integration testing. Hence looking for best approach for given scenario.
I have legacy application (REST) which was written in Spring Integration. Same application I have migrated to Spring Boot. Now I am wondering, how to mock Gateway in Controller and how to test Gateways, Routers. Application structure as:</p>
<p><strong>Controller:</strong></p>
<pre><code>@RestController
@RequestMapping(value = &quot;/acct&quot;)
public class AcctOpenImpl implements AcctOpen {
    /**
     * AcctMgmt Gateway Interface.
     */
    @Autowired
    AcctOpenService acctopenmgmtServiceGateway;
    
    @Override
    @RequestMapping(value = &quot;/product/{product_id_num}&quot;, method = RequestMethod.GET)
    public ResponseEntity&lt;RetrieveAppProdAplnResponse&gt; rtrvAppProdAplnByQueryParam(
        @PathVariable(&quot;product_id_num&quot;) final Long productIdNum) throws BusinessException,
        TechnicalException {
        Map&lt;String, Object&gt; headers = getHeaders();
       
        RetrieveAppProdAplnResponse response = this.acctopenmgmtServiceGateway.rtrvAppProdApln(request, headers);

        ResponseEntity&lt;RetrieveAppProdAplnResponse&gt; retrieveAppProdResponse = new ResponseEntity&lt;RetrieveAppProdAplnResponse&gt;(
            response, HttpStatus.OK);

        return retrieveAppProdResponse;
    }
} 
</code></pre>
<p><strong>Service Interface:</strong></p>
<pre><code>public interface AcctOpenService {
    public RetrieveAppProdAplnResponse rtrvAppProdApln(RetrieveAppProdAplnRequest retrieveAppProdAplnRequest,
        @Headers Map&lt;String, Object&gt; customHeaderMap) throws BusinessException, TechnicalException;
}
</code></pre>
<p><strong>geteways.xml:</strong></p>
<pre><code>&lt;int:gateway id=&quot;acctopenmgmtServiceGateway&quot; service-interface=&quot;com.hsbc.group.depositproduct.svc.gateway.AcctOpenService&quot;
    default-reply-channel=&quot;acctopenmgmtReplyChannel&quot; error-channel=&quot;acctopenmgmtErrorChannel&quot;&gt;
    &lt;int:method name=&quot;rtrvAppProdApln&quot; request-channel=&quot;rtrvAppProdAplnRequestChannel&quot; /&gt;
&lt;/int:gateway&gt;
</code></pre>
<p><strong>si-channels.xml:</strong></p>
<pre><code>&lt;int:channel id=&quot;rtrvAppProdAplnRequestChannel&quot;/&gt;
</code></pre>
<p><strong>si-routers.xml:</strong></p>
<pre><code>&lt;int:router input-channel=&quot;rtrvAppProdAplnRequestChannel&quot; default-output-channel=&quot;acctopenmgmtReplyChannel&quot;     expression=&quot;headers.SERVICE_HEADER.consumerEntyId.ctryCde.toLowerCase()+headers.SERVICE_HEADER.consumerEntyId.groupMbr+'RtrvAppProdAplnRequestChannel'&quot; /&gt;
</code></pre>
<p><strong>si-chain.xml:</strong></p>
<pre><code>&lt;int:chain input-channel=&quot;usMMBIRtrvAppProdAplnRequestChannel&quot; output-channel=&quot;acctopenmgmtReplyChannel&quot;&gt;
    &lt;int:transformer method=&quot;formatRequest&quot; ref=&quot;usRtrvAppProdAplnTransformer&quot;/&gt;
    &lt;int:service-activator method=&quot;rtrvAppProdApln&quot; ref=&quot;rtrvAppProdAplnActivator&quot; /&gt;
    &lt;int:transformer method=&quot;parseResponse&quot; ref=&quot;usRtrvAppProdAplnTransformer&quot;/&gt;
&lt;/int:chain&gt;
</code></pre>
<p><strong>si-transformers.xml:</strong></p>
<pre><code>&lt;bean id=&quot;usRtrvAppProdAplnTransformer&quot; class=&quot;com.hsbc.group.depositproduct.us.svc.transformer.RetrieveAppProdAplnTransformer&quot;&gt;
&lt;/bean&gt;
</code></pre>
<p>Could you please suggest best approach (Unit testing or Integration testing) for given scenario. Also, if some one gives any example that how can I start that will be appreciated.
Thanks in advance.</p>
",https://stackoverflow.com/questions/66843582/writing-test-cases-for-spring-integration-application,"['spring-boot', 'unit-testing', 'spring-integration', 'integration-testing']",120,False,-1,1
authorize camera test in integration testing,"<p>I am writing integration tests for Flutter App. The app let's users to take video. When writing test, how can I allow camera permission for my app inside the script for integration testing when the permission dialog appears?</p>
",https://stackoverflow.com/questions/67704165/authorize-camera-test-in-integration-testing,"['flutter', 'integration-testing']",1329,True,1,1
hapi/lab (and jest): is there a way to have a describe block in a separate js file?,"<p>I am working on a test script using hapi/lab in nodejs.
I would like to have a describe block that is using hapi.server to inject http options (to simulate integration testing).
Something like:</p>
<p>main.test.js:
...</p>
<pre><code>describe('main', async () =&gt; {
   before(async () =&gt; {...}

   describe('inner-main', async() =&gt; {
      **externalDescribe**(some params that exists in this file)

      it('test specific to this file', async () =&gt; {...})
   })
})
</code></pre>
<p>externalFile.test.js:
...</p>
<pre><code>function **externalDescribe**(some params) {
  describe('external', async () =&gt; {
      it('first it', async () =&gt; {
        ...
      })
  })
}
</code></pre>
<p>Or something similar.</p>
",https://stackoverflow.com/questions/69236221/hapi-lab-and-jest-is-there-a-way-to-have-a-describe-block-in-a-separate-js-fi,"['javascript', 'node.js', 'testing', 'integration-testing', 'hapi']",118,False,1,0
Deactivate Kafka message sending and receiving for testing in Spring boot project,"<p>I want to do some integration testing in a spring boot project, where kafka is used.</p>
<p>For these tests I don't want any messages to be sent or received from kafka. Is there a way to configure this?</p>
",https://stackoverflow.com/questions/68694323/deactivate-kafka-message-sending-and-receiving-for-testing-in-spring-boot-projec,"['spring-boot', 'apache-kafka']",49,False,0,1
Mock webclient to call external api in Junit integration testing,"<p>I'm writing integration testing using <strong>@EmbeddedPostgres</strong>. I want mock webclient with response.
below is my method.</p>
<pre><code>import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

@Service
public class TranslateApiConnector {
public JsonNode translateApi(TranslationInput translationInput) {

  HttpClient httpClient = HttpClient.create();
  ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
  
   WebClient webclient = WebClient.builder().clientConnector(connector).baseUrl(&quot;baseUri&quot;).build();
   return webclient.post()
          .uri(&quot;uri&quot;)
          .body(Mono.just(translationInput),TranslationInput.class).exchange()
          .flatMap(clientResponse-&gt;clientResponse.bodyToMono(JsonNode.class)).block();
}
};
</code></pre>
<p>For above webclient method I need to mock webclient .How to write test case to call external api.
Here is my test method</p>
<pre><code>@EmbeddedPostgres
@SpringBootTest
@AutoConfigureMockMvc
@Sql(&quot;/scripts/metadata.sql&quot;)
class TestApi {

    @Autowired
    private final TranslateApiConnector translateApiConnector;

   @Test
   voidTestConnector(){
      TranslationInput translationInput = TranslationInput.builder().input(&quot;test&quot;).build()

     ObjectMapper mapper = new ObjectMapper()
     JsonNode jsonNode = mapper.readTree(&quot;{outputs: [{outputs: &quot;test&quot;}]}&quot;)
     
      Mockito.when(webClient.post().uri(&quot;uri&quot;).body(Mono.just(translaionInput),TranslationInput.class)
     .exchange()
     .flatMap(clientResponse -&gt; 
      clientResponse.bodyToMono(JsonNode.class)).block()).thenReturn(jsonNode);

   Mockito.verify(translateApiConnector).translateApi(translationInput);
}}
</code></pre>
",https://stackoverflow.com/questions/70473976/mock-webclient-to-call-external-api-in-junit-integration-testing,"['java', 'spring-boot', 'junit', 'mockito', 'junit-jupiter']",1082,False,0,0
How to Inject CustomWebApplicationFactory&lt;Startup&gt; in ASP.NET Core 3.1 Integration Tests?,"<p>I'm using <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1"" rel=""nofollow noreferrer"">Microsoft's ASP.NET Core Integration Testing Article</a> and <a href=""https://github.com/maxkagamine/Moq.Contrib.HttpClient/blob/master/test/IntegrationTestExample.Test/ExampleTests.cs"" rel=""nofollow noreferrer"">Moq.Contrib.HttpClient .NET 5 project example</a>, to setup an IntegrationTest Project. My actual app and test project are .NET Core 3.1. I'm getting an error in the constructor:
<a href=""https://i.stack.imgur.com/xEk4c.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/xEk4c.png"" alt=""Error"" /></a></p>
<p>Not sure why there's an issue. Here's the test class:</p>
<pre><code>using FluentAssertions;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Moq.Contrib.HttpClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace API.IntegrationTests
{
    // This shows how you can mock HttpClient at the service collection level in integration tests. Note: &quot;factory&quot; and
    // &quot;client&quot; here are part of the integration test framework, TestServer, not our mock. For more info on integration
    // tests in ASP.NET Core, see https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests
    public class ExampleTests : IClassFixture&lt;CustomWebApplicationFactory&lt;Startup&gt;&gt;
    {
        private readonly CustomWebApplicationFactory&lt;Startup&gt; factory;
        private readonly Mock&lt;HttpMessageHandler&gt; githubHandler = new Mock&lt;HttpMessageHandler&gt;();

        public ExampleTests(CustomWebApplicationFactory&lt;Startup&gt; factory)
        {
            this.factory = factory.WithWebHostBuilder(builder =&gt;
            {
                builder.ConfigureTestServices(services =&gt;
                {
                    // This will configure the &quot;github&quot; named client to use our mock handler while keeping the default
                    // IHttpClientFactory infrastructure and any configurations made in Startup intact (as opposed to
                    // replacing the IHttpClientFactory implementation outright). This will work with typed clients,
                    // too. For the default (unnamed) client, use `Options.DefaultName`.
                    services.AddHttpClient(&quot;github&quot;)
                        .ConfigurePrimaryHttpMessageHandler(() =&gt; githubHandler.Object);
                });
            });
        }

        [Fact]
        public async Task GetReposTest()
        {
            // This is the integration test client used to make requests against the ASP.NET Core app under test
            var client = factory.CreateClient();

            var mockRepos = new GitHubRepository[]
            {
                new GitHubRepository()
                {
                    Name = &quot;Foo&quot;,
                    Language = &quot;TypeScript&quot;,
                    Stars = 39
                },
                new GitHubRepository()
                {
                    Name = &quot;Bar&quot;,
                    Language = &quot;C#&quot;,
                    Stars = 9001 // It's over 9000!!!
                }
            };

            var expectedResponse =
                &quot;Foo (TypeScript, ★39)\n&quot; +
                &quot;Bar (C#, ★9001)\n&quot;;

            // Notice there was no need to set a BaseAddress in this test class. All of the dependency injection and the
            // AddHttpClient() in ConfigureServices() are essentially unchanged and working as they would normally.
            githubHandler.SetupRequest(HttpMethod.Get, &quot;https://api.github.com/users/maxkagamine/repos&quot;)
                .ReturnsResponse(JsonConvert.SerializeObject(mockRepos), &quot;application/vnd.github.v3+json&quot;);

            var response = await client.GetStringAsync(&quot;/&quot;);

            response.Should().Be(expectedResponse,
                &quot;the app's requests should hit the mock handler now instead of the real API&quot;);
        }
    }
}
</code></pre>
<p>And here's the <code>CustomWebApplicationFactory</code>:</p>
<pre><code>using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Linq;

namespace API.IntegrationTests
{
    public class CustomWebApplicationFactory&lt;TStartup&gt;
    : WebApplicationFactory&lt;TStartup&gt; where TStartup : class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =&gt;
            {
                var descriptor = services.SingleOrDefault(
                    d =&gt; d.ServiceType ==
                        typeof(DbContextOptions&lt;ApplicationDBContext&gt;));

                services.Remove(descriptor);

                //services.AddDbContext&lt;ApplicationDBContext&gt;(options =&gt;
                //{
                //    options.UseInMemoryDatabase(&quot;InMemoryDbForTesting&quot;);
                //});

                var sp = services.BuildServiceProvider();

                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var db = scopedServices.GetRequiredService&lt;ApplicationDBContext&gt;();
                    var logger = scopedServices
                        .GetRequiredService&lt;ILogger&lt;CustomWebApplicationFactory&lt;TStartup&gt;&gt;&gt;();

                    db.Database.EnsureCreated();

                    //try
                    //{
                    //    Utilities.InitializeDbForTests(db);
                    //}
                    //catch (Exception ex)
                    //{
                    //    logger.LogError(ex, &quot;An error occurred seeding the &quot; +
                    //        &quot;database with test messages. Error: {Message}&quot;, ex.Message);
                    //}
                }
            });
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/69258146/how-to-inject-customwebapplicationfactorystartup-in-asp-net-core-3-1-integrati,"['c#', 'asp.net-core', 'integration-testing']",858,False,1,0
Springboot Unit Tesiting with Jwt spring security,"<p>I am a Newbie to Unit Testing/ Integration Testing
I am getting some errors while testing the rest api which is secured with Jwt Token authentication by spring security.</p>
<p><strong>userControllerTest</strong></p>
<pre><code>@ExtendWith({ RestDocumentationExtension.class, MockitoExtension.class })
@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(UserController.class)
@AutoConfigureRestDocs(outputDir = &quot;target/generated-snippets&quot;)
@ContextConfiguration(classes = ApplicationContext.class)
@AutoConfigureMockMvc
//@WithMockUser
class UserControllerTest {

    @Mock
    private IUserService&lt;User&gt; userService;

    @Autowired
    private MockMvc mockMvc;

    @InjectMocks
    private UserController userController;

    @Spy
    private ModelMapper modelMapper;

    @Autowired 
    private JwtUtility jwtUtil;


    @Spy
    private JwtRequestFilter filer;

    @Autowired
    private ObjectMapper objectMapper;

    @Spy
    private EntityManager entityManager;

    private final static String ACCEPT_TYPE = &quot;application/user-details&quot;;

    @BeforeEach
    public void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) {

        mockMvc = MockMvcBuilders

                .webAppContextSetup(webApplicationContext)
                .apply(documentationConfiguration(restDocumentation).snippets()
                        .withDefaults(HttpDocumentation.httpRequest(), HttpDocumentation.httpResponse()))// .apply(springSecurity())
                .addFilters(new JwtRequestFilter()).build();
    }

    private User getUser() {
        User user = new User();
        user.setId(1L);
        user.setFirstName(&quot;Saurabh&quot;);
        user.setLastName(&quot;Kohade&quot;);
        user.setEmail(&quot;user@cc.com&quot;);
        user.setReseller(null);
        user.setRoleName(&quot;ADMIN&quot;);
        return user;
    }

    @Test
    @DisplayName(&quot;Will create User&quot;)
//  @WithAnonymousUser
    void testCreate() throws Exception {

        User entity = getUser();

        when(userService.saveUser(entity, 1L)).thenReturn(entity);

        UserDto dtoresponse = userController.create(entity, ACCEPT_TYPE);

        assertNotNull(dtoresponse);

        String token = &quot;Bearer JhbGciOiJIUzI1NiJ9.eyJzdWIiOiuY29tIiwicmVzZWxsZXJJbmZvIjoie1wiZG9tYWluTmFtZTgQ.W0Xnl1j7PAAxqV97uE6s6iGU1IfCZHmiVLYN5iZwsbI&quot;;

        String URI = &quot;/user&quot;;

        String inputToJson = objectMapper.writeValueAsString(entity);

        MvcResult mvcResult = mockMvc
                .perform(post(URI).with(SecurityMockMvcRequestPostProcessors.jwt())
                        .with(SecurityMockMvcRequestPostProcessors.csrf())
                        .contentType(MediaType.APPLICATION_JSON_VALUE)
                        .content(inputToJson).accept(ACCEPT_TYPE))//.header(HttpHeaders.AUTHORIZATION, token))
                .andExpect(status().isOk()).andReturn();

        assertEquals(HttpStatus.OK.value(), mvcResult.getResponse().getStatus());

    }
</code></pre>
<p><strong>junit Stacktrace</strong></p>
<pre><code>java.lang.NoClassDefFoundError: org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverter
    at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors$JwtRequestPostProcessor.&lt;init&gt;(SecurityMockMvcRequestPostProcessors.java:1032)
    at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors$JwtRequestPostProcessor.&lt;init&gt;(SecurityMockMvcRequestPostProcessors.java:1028)
    at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt(SecurityMockMvcRequestPostProcessors.java:262)
    at cloudcodes.customermanagement.controller.UserControllerTest.testCreate(UserControllerTest.java:169)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    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:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:84)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:768)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: java.lang.ClassNotFoundException: org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:606)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    ... 71 more


</code></pre>
<p>I think i am missing some configuration for authentication to fake token can anyone help me with this?.....</p>
",https://stackoverflow.com/questions/68620941/springboot-unit-tesiting-with-jwt-spring-security,"['java', 'spring-boot', 'junit', 'spring-security', 'jwt']",422,False,0,0
Regex validation fails to stop invalid data,"<p>Regex validation is not working in my integration testing. The spock test fails as I get a <code>200</code> response. The string regex validation is failing on the request param even for alphanumeric and integers. How can I fix this?</p>
<pre class=""lang-java prettyprint-override""><code>def &quot;GetDataByTopic should return 400 with invalid output case&quot;() {
  when:
  def result = mvc.perform(
    MockMvcRequestBuilders.get(&quot;/data/getDataByTopic?topic=&quot; + topic)
  )

  then:
  result
    .andExpect(MockMvcResultMatchers.status().is4xxClientError())
    .andExpect(MockMvcResultMatchers.jsonPath('$.error').exists())

  where:
  topic       | _
  &quot;&lt;%script&gt;&quot; | _
}
</code></pre>
<p>The controller class for the below method is annotatied using <code>@Validated</code>
REGEX for string is <code>^[-A-Za-z_]{0,255}$</code></p>
<pre class=""lang-java prettyprint-override""><code>@RequestMapping(method = RequestMethod.GET, path = &quot;/getDataByTopic&quot;)
public Response getDataByTopic(
  @Valid
  @Pattern(
    regexp = REGEX_STRING_VALIDATION, 
    message = &quot;Topic format is incorrect :  ${validatedValue}&quot;
  )
  @RequestParam(&quot;topic&quot;) String topic
) {
  return dataService.getDataByTopic(topic);
}
</code></pre>
",https://stackoverflow.com/questions/65704152/regex-validation-fails-to-stop-invalid-data,"['java', 'spring-boot', 'spock']",68,False,1,0
WebApplicationFactory always return 404 for controllers calls in .net core 6,"<p>I followed the documentation of microsoft for Integration testing:
<a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0#introduction-to-integration-tests"" rel=""noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0#introduction-to-integration-tests</a></p>
<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 csproj, I added:</p>
<pre><code>&lt;ItemGroup&gt;
        &lt;InternalsVisibleTo Include=&quot;Integration.Tests&quot; /&gt;
&lt;/ItemGroup&gt;
</code></pre>
<p>and here is the Integration.Tests csproj:</p>
<pre><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;

    &lt;PropertyGroup&gt;
        &lt;TargetFramework&gt;net6.0&lt;/TargetFramework&gt;
        &lt;IsPackable&gt;false&lt;/IsPackable&gt;
        &lt;IsTestProject&gt;true&lt;/IsTestProject&gt;
    &lt;/PropertyGroup&gt;

    &lt;ItemGroup&gt;
        &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Hosting.Abstractions&quot; Version=&quot;2.2.0&quot; /&gt;
        &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Mvc.Testing&quot; Version=&quot;6.0.0&quot; /&gt;
        &lt;PackageReference Include=&quot;Microsoft.EntityFrameworkCore&quot; Version=&quot;6.0.0&quot; /&gt;
        &lt;PackageReference Include=&quot;Microsoft.EntityFrameworkCore.InMemory&quot; Version=&quot;6.0.0&quot; /&gt;
        &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;17.0.0&quot; /&gt;
        &lt;PackageReference Include=&quot;xunit&quot; Version=&quot;2.4.1&quot; /&gt;
        &lt;PackageReference Include=&quot;xunit.runner.visualstudio&quot; Version=&quot;2.4.3&quot;&gt;
            &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;
            &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;
        &lt;/PackageReference&gt;
        &lt;PackageReference Include=&quot;coverlet.collector&quot; Version=&quot;3.1.0&quot;&gt;
            &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;
            &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;
        &lt;/PackageReference&gt;
    &lt;/ItemGroup&gt;

    

&lt;/Project&gt;
</code></pre>
<p>I created a TestWebAppFactory.cs like:</p>
<pre><code>public class TestWebAppFactory&lt;TEntryPoint&gt; : WebApplicationFactory&lt;Program&gt; where TEntryPoint : Program
{
    public ITestOutputHelper Output { get; set; }
    public List&lt;string&gt; Logs { get; private set; } = new List&lt;string&gt;();

    public TestWebAppFactory([NotNull] ITestOutputHelper output)
    {
        Output = output;
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder
            .ConfigureServices(services =&gt;
            {
                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.UseInMemoryDatabase(&quot;My.Sample&quot;);
                });
            })
            .Configure(app =&gt;  {
                var serviceProvider = app.ApplicationServices;
                using var scope = serviceProvider.CreateScope();
                var itemManager = serviceProvider.GetRequiredService&lt;IItemManager&gt;();
                TestDbInitializer.Seed(scope.ServiceProvider, Output);
            });

    }
}
</code></pre>
<p>And my Item_Tests.cs:</p>
<pre><code>public class Items_Tests : IClassFixture&lt;Program&gt;
    {
        private readonly HttpClient _client;
        private readonly TestServer _server;
        private readonly IWebHost _host;

        public Items_Tests(ITestOutputHelper output)
        {
            var factory = new TestWebAppFactory&lt;Program&gt;(output);
            _client = factory
                .CreateClient();
        } 

        [Fact]
        public async Task Index_WhenCalled_ReturnsApplicationForm()
        {
            var response = await _client.GetAsync(Constants.Api.V1.Items.Url);

            response.EnsureSuccessStatusCode();

            var responseString = await response.Content.ReadAsStringAsync();

            Assert.Contains(&quot;Mark&quot;, responseString);
            Assert.Contains(&quot;Evelin&quot;, responseString);
        }

    }
</code></pre>
<p>Note: I would like to be able to send the ITestOuputHelper to TestWebAppFactory to write few information useful in the output that I don't share here to reduce the amount of code.</p>
<p>Note2: 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 returnsw.</p>
<p>So each time the test fails here:</p>
<pre><code>            var response = await _client.GetAsync(Constants.Api.V1.Items.Url);

            response.EnsureSuccessStatusCode();
</code></pre>
<p>The response always get a 404 error.</p>
<p>What should I do to make it works correctly?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/70299688/webapplicationfactory-always-return-404-for-controllers-calls-in-net-core-6,"['integration-testing', 'asp.net-core-6.0']",2547,True,5,3
Unable to load one or more of the requested types. Could not load file or assembly &#39;Microsoft.VisualStudio.Coverage.CoreLib.Net,"<p>I created an XUnit Test for integration testing and followed the example here (<a href=""https://i.stack.imgur.com/3Gi1O.png"" rel=""nofollow noreferrer"">Integration Tests in ASP.NET Core</a>)
This loads the Startup of the mvc project but fails with an exception where auto mapper is being injected.</p>
<p>Any ideas on what this means?</p>
<p>[![Exception User-Unhandled][2]][2]</p>
<p>Test Class</p>
<pre><code>// WebApplicationFactory&lt;TEntryPoint&gt; is used to create a TestServer for the integration tests.
public class ServiceHttpClientTest : IClassFixture&lt;WebApplicationFactory&lt;Startup&gt;&gt;
{
    private readonly WebApplicationFactory&lt;Startup&gt; _factory;

    public ServiceHttpClientTest(WebApplicationFactory&lt;Startup&gt; factory)
    {
        _factory = factory;
    }

    [Theory]
    [InlineData(&quot;/Index&quot;)]
    [InlineData(&quot;/About&quot;)]
    [InlineData(&quot;/Contact&quot;)]
    [InlineData(&quot;/Privacy&quot;)]
    public async Task Get_EndpointsReturnSuccessAndCorrectContentType(string url)
    {
        // Arrange
        var client = _factory.CreateClient();

        // Act
        var response = await client.GetAsync(url);

        // Assert
        response.EnsureSuccessStatusCode();  // Status Code 200-299
        Assert.Equal(&quot;text/html; charset=utf-8&quot;, response.Content.Headers.ContentType.ToString());
    }
}



enter code here
</code></pre>
<p>Project File
<a href=""https://i.stack.imgur.com/3Gi1O.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/3Gi1O.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/66824949/unable-to-load-one-or-more-of-the-requested-types-could-not-load-file-or-assemb,"['c#', 'dependency-injection', 'automapper', 'integration', 'xunit']",733,True,0,2
How to correct error CS0122: &#39;WebHost&#39; is inaccessible due to its protection level,"<p>i'm currently trying to do integration testing on a asp.net application which i'm developing in Visual Studio Code in C#.</p>
<p>Since i'm very new to integration testing i was trying to follow a tutorial or some steps another person had taken to do the same, so i started following this tutorial, <a href=""https://referbruv.com/blog/posts/writing-integration-tests-in-aspnet-core-using-xunit"" rel=""nofollow noreferrer"">https://referbruv.com/blog/posts/writing-integration-tests-in-aspnet-core-using-xunit</a>.
In this tutorial it is explained that a necessary step to the integration tests is to define a setup class for booting up the ASP.NET test server along with the necessary settings to be passed and they do that by overriding the default WebApplicationFactory class and providing our own implementation of the WebHostBuilder method.</p>
<p>And they do it like this:</p>
<pre><code>public class MyReaderApiAppFactory : WebApplicationFactory&lt;Startup&gt;
{
    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return WebHost.CreateDefaultBuilder()
            .UseStartup&lt;Startup&gt;();
    }
}
</code></pre>
<p>So i tried to mimic what they did like this:</p>
<pre><code>using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Testing;
using DDDSample1;
using Microsoft.AspNetCore.Hosting;

public class TripApiAppFactory : WebApplicationFactory&lt;Startup&gt;
{
    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return WebHost.CreateDefaultBuilder().UseStartup&lt;Startup&gt;();
    }
}
</code></pre>
<p>This is the class i have in my program now, and so i basically only switched the name of the class from their class and added some packages that were needed. And now when i try to run dotnet build on my project this error appears:</p>
<pre><code>C:\Users\berna\OneDrive\Área de Trabalho\Informática\3ºano - Informática\Arqsi\Projecto\projeto_integrador_grupo67\mdv\Tests\IntegrationTests\TripApiAppFactory.cs(10,10): 
error CS0122: 'WebHost' is inaccessible due to its protection level [C:\Users\berna\OneDrive\Área de Trabalho\Informática\3ºano - Informática\Arqsi\Projecto\projeto_integrador_grupo67\mdv\DDDNetCore.csproj]
</code></pre>
<p>Can someone explain me if i can fix this error and if so how? Any help will be greatly appreciated. Also if someone has any advice on how to do integration testing, more precisely on .net app developed in C# on VSCode that would be great too.</p>
<p>Thank you in advance for any kind of comment, help or feedback you might give.</p>
",https://stackoverflow.com/questions/65547089/how-to-correct-error-cs0122-webhost-is-inaccessible-due-to-its-protection-lev,"['c#', 'asp.net', 'integration-testing', 'visual-studio-code']",993,True,0,1
How to set header on Apache Camel 3.X.X route?,"<p>I am doing integration testing on the Camel route.</p>
<p>The Camel route:</p>
<pre><code>from(&quot;direct:abc&quot;)
  .routeId(&quot;abc-route&quot;)
  .process(MyProcessor())
  .toD(&quot;direct:xyz&quot;)
</code></pre>
<p>As this route is getting tested into isolation, I need to set headers in the test; previously, they arrived from another route. How can I do it?</p>
<p>Simplified test class:</p>
<pre><code>@SpringBootTest
@MockEndpoints
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
class MyRouteTest {

  @Autowired
  lateinit var camelContext: CamelContext

  @Produce(uri = &quot;direct:abc&quot;)
  lateinit var template: ProducerTemplate

  @EndpointInject(uri = &quot;mock:direct:xyz&quot;)
  lateinit var destEndpoint: MockEndpoint

  @Test
  fun `should test route`() {
    template.sendBody(&quot;&quot;)
  }
}
</code></pre>
<p>I have tried doing <code>camelContext.adapt(ModelCamelContext::class.java)</code> but still cannot get to the route and forcibly modify it.</p>
",https://stackoverflow.com/questions/68894058/how-to-set-header-on-apache-camel-3-x-x-route,"['spring-boot', 'kotlin', 'testing', 'apache-camel']",883,True,2,1
Flutter integration tests - multiple tests,"<p>So I recently wanted to add some integration testing to the my app, and followed the official guidelines from the flutter.dev on the integration testing. I managed to run a single test, so I wanted to add another one, and this is where the problems started.</p>
<p>I don't know how to add another test suite in the same run, so something like</p>
<p>TEST 1:</p>
<ol>
<li>click button</li>
<li>check if counter incremented</li>
</ol>
<p>TEST2:</p>
<ol>
<li>click the button again</li>
<li>check if counter incremented again</li>
</ol>
<pre><code>void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  group('Integration test', () {
    testWidgets('test 1', (WidgetTester tester) async {
      app.main();
      await tester.pumpAndSettle();

      // doing stuff here works
    });
  });
}
</code></pre>
<p>This is what I have working right now. I expected that moving the <code>app.main()</code> call before the <code>group</code> and simply adding another testWidgets call will work (similar to unit testing) but it doesn't:</p>
<pre><code>void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();
  // app.main(); &lt;&lt;--- moving here...
  group('Integration test', () {
    // app.main(); &lt;&lt;--- ... or here didn't help
    testWidgets('test 1', (WidgetTester tester) async {
      // do stuff
    });
    testWidgets('test 2', (WidgetTester tester) async {
      // how to add this? And do stuff with the same app session
    });
  });
}
</code></pre>
<p>EDIT:
For better clarity of what I'm trying to achieve. The following are some current flutter driver tests that I have. I just want to migrate to the new api of integration_test package, without losing the names &quot;test 1&quot;, &quot;test 2&quot; etc</p>
<pre><code>void main() {
  group(&quot;group name&quot;, () {
    FlutterDriver driver;
    setUpAll(() async {
      driver = await FlutterDriver.connect();
    });

    tearDownAll(() async {
      if (driver != null) {
        await driver.close();
      }
    });

    test('test 1', () async {
      // do stuff with the driver
    });
    test('test 2', () async {
      // do other stuff with the driver with the same seesion
    });
    test('test 3', () async {
      // etc
    });
  });
}
</code></pre>
",https://stackoverflow.com/questions/68480678/flutter-integration-tests-multiple-tests,"['flutter', 'testing']",2564,True,3,3
Quarkus OpenId Connect Bearer Token Integration/Security Testing,"<p>I'm following <a href=""https://quarkus.io/guides/security-openid-connect#integration-testing-wiremock"" rel=""nofollow noreferrer"">https://quarkus.io/guides/security-openid-connect#integration-testing-wiremock</a> to create some tests for my Quarkus app:</p>
<pre><code>@QuarkusTest
@TestHTTPEndpoint(BannerApi.class)
@QuarkusTestResource(OidcWiremockTestResource.class)
public class BannerApiTest {
    @Test
    public void testListUnauthenticated() {
        when().get().then().statusCode(401);
    }
}
</code></pre>
<p>I followed the setup as-is, except I created <code>application.properties</code> in <code>src/test/resources</code> with the following contents:</p>
<pre><code>quarkus.oidc.auth-server-url=${keycloak.url}/realms/quarkus/
quarkus.oidc.client-id=quarkus-service-app
quarkus.oidc.application-type=service
smallrye.jwt.sign.key.location=privateKey.jwk
</code></pre>
<p>But here's what I get:</p>
<pre><code>2021-08-03 21:18:41,731 INFO  [org.ecl.jet.uti.log] (pool-5-thread-1) Logging initialized @14312ms to org.eclipse.jetty.util.log.Slf4jLog
...
2021-08-03 21:18:42,041 INFO  [io.qua.tes.oid.ser.OidcWiremockTestResource] (pool-5-thread-1) Keycloak started in mock mode: http://localhost:64289
...
2021-08-03 21:18:44,348 INFO  [org.ecl.jet.ser.han.ContextHandler] (main) Stopped o.e.j.s.ServletContextHandler@520fdce4{/__admin,null,STOPPED}
2021-08-03 21:18:44,349 INFO  [io.qua.tes.oid.ser.OidcWiremockTestResource] (main) Keycloak was shut down

java.lang.RuntimeException: java.lang.RuntimeException: Failed to start quarkus

    at io.quarkus.test.junit.QuarkusTestExtension.throwBootFailureException(QuarkusTestExtension.java:686)
    at io.quarkus.test.junit.QuarkusTestExtension.interceptTestClassConstructor(QuarkusTestExtension.java:759)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
...
Caused by: java.lang.RuntimeException: Failed to start quarkus
    at io.quarkus.runner.ApplicationImpl.doStart(ApplicationImpl.zig:1114)
    at io.quarkus.runtime.Application.start(Application.java:101)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    ... 31 more
Caused by: javax.enterprise.inject.spi.DeploymentException: Configuration validation failed:
    keycloak.url does not map to any root
    at io.quarkus.arc.runtime.ConfigRecorder.registerConfigMappings(ConfigRecorder.java:67)
    at io.quarkus.deployment.steps.ConfigBuildStep$registerConfigClasses-2116437784.deploy_0(ConfigBuildStep$registerConfigClasses-2116437784.zig:292)
    at io.quarkus.deployment.steps.ConfigBuildStep$registerConfigClasses-2116437784.deploy(ConfigBuildStep$registerConfigClasses-2116437784.zig:40)
    ... 46 more
Caused by: io.smallrye.config.ConfigValidationException: Configuration validation failed:
    keycloak.url does not map to any root
    at io.smallrye.config.ConfigMappingProvider.mapConfiguration(ConfigMappingProvider.java:829)
    at io.smallrye.config.ConfigMappingProvider.mapConfiguration(ConfigMappingProvider.java:785)
    at io.smallrye.config.ConfigMappings.mapConfiguration(ConfigMappings.java:54)
    ... 49 more


org.opentest4j.TestAbortedException: Boot failed


    at io.quarkus.test.junit.QuarkusTestExtension.throwBootFailureException(QuarkusTestExtension.java:688)
    at io.quarkus.test.junit.QuarkusTestExtension.interceptTestClassConstructor(QuarkusTestExtension.java:759)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
...
</code></pre>
<p>As you can see from the log, <code>Keycloak started in mock mode: http://localhost:64289 ...</code> but then <code>keycloak.url does not map to any root</code>.</p>
<p>Where do I miss? I'm using Quarkus 2.1.0.</p>
",https://stackoverflow.com/questions/68637903/quarkus-openid-connect-bearer-token-integration-security-testing,['quarkus'],580,False,0,0
How to run cosmos emulator in Azure devops with Ubuntu?,"<p>How to run Azure cosmos DB Emulator in Azure devops with spring boot Integration testing (java)?</p>
<p>Currently the cosmos DB emulator only supports Windows server not linux?</p>
<p>Any suggestion how to proceed here?</p>
<p><strong>Update:1</strong>
For windows build agent, below task can be used which is from azure pipelines.</p>
<pre><code>- task: CosmosDbEmulator@2       
    inputs:        
        containerName: 'azure-cosmosdb-emulator'   
        enableAPI: 'SQL'    
        portMapping: '8081:8081, 8901:8901, 8902:8902, 8979:8979, 10250:10250, 10251:10251, 10252:10252, 10253:10253, 10254:10254, 10255:10255, 10256:10256, 10350:10350'       
        hostDirectory: '$(Build.BinariesDirectory)\azure-cosmosdb-emulator'
    
</code></pre>
<p>For Linux:
I am using the same as of @Ricardo</p>
",https://stackoverflow.com/questions/69068268/how-to-run-cosmos-emulator-in-azure-devops-with-ubuntu,"['java', 'spring-boot', 'azure-devops', 'azure-pipelines', 'azure-cosmosdb']",558,True,1,1
Is there a way to setup dummy database to test a .NET Framework 4.7.2 repository/database integration?,"<p>I am trying to set up integration testing between the repository and database for a .NET Framework app, which has already been built. I have been trying to find a way to setup and seed a test database or in memory database that I could use to run some tests against, but don't see much in terms of .NET Framework apps.</p>
<p>I have seen that there is a <code>Microsoft.EntityFrameworkCore.InMemory</code> library that accomplishes what I need, but it is only available for .NET Core projects running version 6.0. I have also found little to no similar mention of this being possible on a .NET Framework Project, but imagine that there has to be a way.</p>
<p>My work on this legacy app is my first foray into the .NET world, so I may be misunderstanding things from my research on this topic. Is it possible to set up a test/in memory database for integration testing a .NET Framework app? If so, what are the best practices for doing so?</p>
",https://stackoverflow.com/questions/70381827/is-there-a-way-to-setup-dummy-database-to-test-a-net-framework-4-7-2-repository,"['c#', '.net', 'entity-framework', 'integration-testing']",688,True,2,1
Is it worth implementing service integration tests in Spring Boot application?,"<p>I have come accross multiple articles on integration testing on Spring Boot applications. Given that the application follows three layer pattern (Web Layer - Service Layer - Repository Layer) I have not seen a single article with integration testing the application up to just the service layer (ommiting the web layer) where all the business logic is contained. All of the integration tests seem like controller unit tests - mostly veryfing only request and response payloads, parameters etc.</p>
<p>What I would like however is to verify the business logic using service integration tests. Since the web layer is responsible only for taking the results from services and exchanging them with the client I think this makes much more sense. Such tests could also contain some database state verifications after running services to e.g. ensure that there are no detached leftovers.</p>
<p>Since I have never seen such a test, is it a good practice to implement one? If no, then why?</p>
",https://stackoverflow.com/questions/69949590/is-it-worth-implementing-service-integration-tests-in-spring-boot-application,"['spring', 'spring-boot', 'unit-testing', 'integration-testing', 'spring-test']",1055,True,1,2
How to perform integration testing in Netty 4,"<p>In <a href=""https://www.manning.com/books/netty-in-action"" rel=""nofollow noreferrer"">Netty in Action</a>, I read about <a href=""https://netty.io/4.1/api/io/netty/channel/embedded/EmbeddedChannel.html"" rel=""nofollow noreferrer"">EmbeddedChannel</a> which can be used for unit testing.</p>
<p>My use case now goes beyond unit testing, and more of integration testing. I want to be able to start the server and then, and within the test, configure/modify the channel handlers.</p>
<p>How is such an integration test setup possible in Netty 4?</p>
",https://stackoverflow.com/questions/66159539/how-to-perform-integration-testing-in-netty-4,"['netty', 'netty4']",151,False,0,1
End-End test and Integration test in Micronaut using Test Container,"<p>I have a Micronaut application with the following structure</p>
<ol>
<li>API Gateway (Communicate with the producer)</li>
<li>Product Producer (RabbitMq-Producer)</li>
<li>Product Consumer (RabbitMq-Consumer)</li>
</ol>
<p>Now I want to perform End-to-End and Integration testing for the application in local development and CI/CD.</p>
<p>I am using the RabbitMq Test container for the End-End and Integration testing.</p>
<p><strong>CI/CD pipeline</strong></p>
<p>After merging code and deployed the application to the server, run the integration and end-end test. Because producer and consumer will be running and all the test cases will work.</p>
<p><strong>Local Development</strong></p>
<p>Since the RabbitMQ Consumer is dependent on the Producer. While running Integration or End-to-End testing the Product producer application might not be running. So all the test case will be failed. A solution will be to run the producer application manually before running the tests.</p>
<p>Or Containerise all the applications and run the Test. What are the best practices for Integration or End-to-End testing in a microservice architecture?</p>
",https://stackoverflow.com/questions/68799663/end-end-test-and-integration-test-in-micronaut-using-test-container,"['java', 'junit', 'rabbitmq', 'microservices', 'micronaut']",943,True,1,1
Unresolved reference: FlutterTestRunner,"<p>I'm following <a href=""https://github.com/flutter/flutter/tree/master/packages/integration_test#android-device-testing"" rel=""nofollow noreferrer"">Flutter integration test setup for Android</a> and getting &quot;Unresolved reference: FlutterTestRunner&quot; problem. Cannot figure out how to import it correctly as <code> import dev.flutter.plugins.integration_test.FlutterTestRunner</code> gives &quot;Unresolved reference: dev&quot; error. So how should I import <code>FlutterTestRunner</code>?</p>
<p>Also <code>ActivityTestRule</code> is deprecated in <code>androidx.test:rules:1.4.0</code>. So my additional question would be what is the proper setup for flutter integration testing in Android?</p>
<p>The code from the guide that gives me problems:</p>
<pre><code>import androidx.test.rule.ActivityTestRule;
import dev.flutter.plugins.integration_test.FlutterTestRunner;
import org.junit.Rule;
import org.junit.runner.RunWith;

@RunWith(FlutterTestRunner.class)
public class MainActivityTest {
  @Rule
  public ActivityTestRule&lt;MainActivity&gt; rule = new ActivityTestRule&lt;&gt;(MainActivity.class, true, false);
}
</code></pre>
",https://stackoverflow.com/questions/70433506/unresolved-reference-fluttertestrunner,"['android', 'flutter', 'integration-testing']",170,False,1,0
Rust Workspace: Is it possible to use a binary crate for integrationstests in lib crate?,"<p>I have the following workspace structure:</p>
<pre class=""lang-toml prettyprint-override""><code>[workspace]

members = [
    &quot;skserver&quot;, # binary
    &quot;skclient&quot;, # binary
    &quot;skcommon&quot;, # lib
    &quot;skintegrationtests&quot; # lib
]
</code></pre>
<p>The intention was to have an extra lib crate for integration testing of client/server-functionality. The <code>Cargo.toml</code> of <code>skintegrationtests</code> is as follows:</p>
<pre class=""lang-toml prettyprint-override""><code># for integration tests of own programs etc.
skcommon = {path = &quot;../skcommon&quot;}
skclient = {path = &quot;../skclient&quot;}
skserver = {path = &quot;../skserver&quot;}
</code></pre>
<p><code>skcommon</code> can be referenced, but not <code>skclient</code> (I haven't tried <code>skserver</code>). Is that intentional from Rust? And if so, why?
I started doing integrationtests with <code>skcommon</code>. I want to avoid circular dependencies with <code>skclient</code> and <code>skserver</code>, and so I created <code>skintegrationtests</code>.</p>
",https://stackoverflow.com/questions/68963429/rust-workspace-is-it-possible-to-use-a-binary-crate-for-integrationstests-in-li,"['testing', 'rust', 'dependency-management', 'rust-cargo']",307,True,1,1
Asking me for CucumberContextConfiguration when I already have,"<p>I currently working on integration testing of one the Restful APIs. I have received an exception asking me to <code>annotate a glue class</code> using @CucumberContextConfiguration. At the moment, I have</p>
<p><strong>ApplicationTests.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import io.cucumber.spring.CucumberContextConfiguration;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;

@RunWith(Cucumber.class)
@CucumberContextConfiguration
@SpringBootTest(classes = {VehicleRegApplication.class, 
    VehicleRegApplicationTests.class, 
    CucumberSpringConfiguration.class})
@CucumberOptions(features = &quot;src/test/resources/Features&quot;, 
    glue = {&quot;com.vehiclereg.StepDefinitions&quot;}, 
    plugin = {&quot;pretty&quot;})
public class VehicleRegApplicationTests {

    @Test
    void contextLoads() {

    }

}
</code></pre>
<p><strong>CucumberSpringConfiguration.java</strong> in the same folder as the <code>ApplicationTests.java</code></p>
<pre class=""lang-java prettyprint-override""><code>import io.cucumber.spring.CucumberContextConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;

@CucumberContextConfiguration
@SpringBootTest
@AutoConfigureMockMvc
public class CucumberSpringConfiguration {
}
</code></pre>
<p>I have <code>cucumber-java</code>, <code>cucumber-spring</code>, <code>cucumber-junit</code>, <code>junit</code> injected. I have done what the exception says and when I run the test the same error comes back.</p>
<pre><code>io.cucumber.core.backend.CucumberBackendException: Please annotate a glue class with some context configuration.
</code></pre>
<p>I wonder if I have done something wrong?</p>
",https://stackoverflow.com/questions/68092911/asking-me-for-cucumbercontextconfiguration-when-i-already-have,"['spring', 'spring-boot', 'cucumber']",3807,False,0,0
"When extracting smaller classes from a larger class, at what point do the smaller classes become their own units that should be tested as such?","<p>I keep hearing conflicting ideas:
that unit tests should have no dependencies and create mocks
and that they shouldn't care about implementation details/structure</p>
<p>but if I extract a smaller class out of a larger one, it becomes a dependency. and if I test that independently, its testing + &quot;locking in&quot; the structure. If I test it via the larger class, its integration testing.</p>
",https://stackoverflow.com/questions/68415717/when-extracting-smaller-classes-from-a-larger-class-at-what-point-do-the-smalle,"['unit-testing', 'refactoring']",41,False,0,1
How to reach value from the response in Karate?,"<p>Thanks for your time reading this question! I really appreciate it.
After some api call I receive response like:</p>
<pre><code>{
   &quot;version&quot;: {
       &quot;1.0.0&quot;: {
         &quot;reqId&quot;:&quot;1sad2342-3246-vdw2-36nd-12fshuiy65r1&quot;
       }
   }
}
</code></pre>
<p>I need to def the &quot;reqId&quot; value for integration testing. How can I reach it? Karate treats 1.0.0 as 3 different keys. So, I tried:
Then def requestId = response.version.1.0.0.reqId . I also tried to make it with quotation &quot;1.0.0&quot; or hashtag but nothing worked. Any suggestions?</p>
",https://stackoverflow.com/questions/69858387/how-to-reach-value-from-the-response-in-karate,"['api', 'testing', 'karate']",14,False,1,0
Firebase Test Lab for Instrumentation Lab on Flutter - &quot;The uploaded test APK does not contain the test runner class specified in the manifest file.&quot;,"<p>I am trying to use Firebase Test Lab as part of my integration testing using Flutter but I am running into this error on Firebase Console.</p>
<pre><code>The uploaded test APK does not contain the test runner class specified in the manifest file. This is probably because the test runner isn't built into the test APK (might be in the app APK instead).
</code></pre>
<p>I followed the steps specified by the Flutter documentation @ <a href=""https://github.com/flutter/flutter/tree/master/packages/integration_test#integration_test"" rel=""nofollow noreferrer"">here</a></p>
<p>This is the firebase command I run on the terminal. But I also tried manually uploading the app builds to the FB TL console and get the same error.</p>
<pre><code>gcloud firebase test android run \
--type instrumentation \
--app build/app/outputs/apk/debug/app-debug.apk \
--test build/app/outputs/apk/androidTest/debug/app-debug-androidTest.apk \
--timeout 3m
</code></pre>
",https://stackoverflow.com/questions/68596437/firebase-test-lab-for-instrumentation-lab-on-flutter-the-uploaded-test-apk-do,"['android', 'firebase', 'flutter', 'testing', 'instrumentation']",189,False,1,0
"Kafka Integration Test, unable to set SASL enabled mechanism","<p>I'm doing integration testing with <code>TestContainers</code> and trying to enable SASL so I can keep the same configuration file and not duplicate code.</p>
<pre class=""lang-java prettyprint-override""><code>  public static KafkaContainer kafka =
      new KafkaContainer(DockerImageName.parse(KAFKA_TEST_IMAGE))
              .withNetwork(Network.newNetwork())
              .withEnv(&quot;KAFKA_AUTO_CREATE_TOPICS_ENABLE&quot;, &quot;false&quot;)
              .withEnv(&quot;KAFKA_ALLOW_EVERYONE_IF_NO_ACL_FOUND&quot;, &quot;true&quot;)
              .withEnv(&quot;KAFKA_SUPER_USERS&quot;, &quot;User:OnlySuperUser&quot;)
//              .withEnv(&quot;KAFKA_CFG_SASL_ENABLED_MECHANISMS&quot;, &quot;PLAIN&quot;)
//              .withEnv(&quot;KAFKA_CFG_SASL_MECHANISM_INTER_BROKER_PROTOCOL&quot;, &quot;SASL_PLAINTEXT&quot;)
              .withEnv(&quot;KAFKA_SASL_ENABLED_MECHANISMS&quot;, &quot;PLAIN,SASL_PLAINTEXT&quot;)
              .withEnv(&quot;KAFKA_SASL_JAAS_CONFIG&quot;, JAAS_CONFIG);
</code></pre>
<p>Here is what I'm playing with, but I get the following error:</p>
<pre><code>org.apache.kafka.common.errors.IllegalSaslStateException: Unexpected handshake request with client mechanism PLAIN, enabled mechanisms are []
</code></pre>
<p>It seems like the enabled mechanism (PLAIN) is being completely ignored. Why is this? I checked the documentation and don't see how else I could configure this within the container.</p>
",https://stackoverflow.com/questions/66724948/kafka-integration-test-unable-to-set-sasl-enabled-mechanism,"['docker', 'apache-kafka', 'testcontainers']",595,False,1,0
Micronaut to reuse testcontainer,"<p>I am using Micronaut 2.4.0 and using testContainers for SQL Server Integration testing.</p>
<p>Here is my gradle.build</p>
<pre><code>    testImplementation(&quot;org.testcontainers:testcontainers&quot;)
    testImplementation(&quot;org.testcontainers:junit-jupiter&quot;)
    testImplementation(&quot;org.testcontainers:mssqlserver&quot;)
</code></pre>
<p>Here is application.yml for test</p>
<pre><code>    url: jdbc:tc:sqlserver://localhost;databaseName=test-db
    username: sa
    password: sa
    driverClassName: org.testcontainers.jdbc.ContainerDatabaseDriver
</code></pre>
<p>These are the only changes and micronaut handles creating and starting of testcontainers.</p>
<p><strong>Problem</strong></p>
<p>For each test classes, it creates new container.
Most of the time test takes is in container creation.</p>
<p>Is there a way we can re-use the container ? (clearing the DB might still be okay)</p>
",https://stackoverflow.com/questions/66671102/micronaut-to-reuse-testcontainer,"['micronaut', 'testcontainers', 'testcontainers-junit5']",956,True,3,3
Angular Integration Testing - jasmine Spy - Can&#39;t mock a service method returning Observable,"<p>I am new to doing integration testing. And the whole thing is so confusing.</p>
<p>For my first test, Seems like my spying is not returning the data as i intend to return it. Gives and error: Expected 0 to be 3. Will be great if someone could  help me understand what am I doing wrong.</p>
<p>Here is my service,page,spec file along with template:</p>
<p><strong>MyService</strong></p>
<pre><code>
    import { Data } from './../data/data.model';
    import { Injectable } from '@angular/core';
    import { BehaviorSubject, of } from 'rxjs';
    import { tap } from 'rxjs/operators';

    @Injectable({
      providedIn: 'root',
    })
    export class MyService {
      private _data = new BehaviorSubject&lt;Data[]&gt;([]);

      get data() {
        return this._data;
      }

      constructor() {}

      getAllData() {
        return of([
          {
            id: '1',
            title: 'Rice',
          },
          {
            id: '2',
            title: 'Wheat',
          },
          {
            id: '33',
            title: 'Water',
          },
        ]).pipe(
          tap((data) =&gt; {
            this._data.next(data);
          })
        );
      }
    }

</code></pre>
<p><strong>DataPage Component</strong></p>
<pre><code>
    import { Component, OnInit } from '@angular/core';
    import { BehaviorSubject, Observable, of, Subscription } from 'rxjs';
    import { MyService } from '../services/my.service';
    import { Data } from './data.model';

    @Component({
      selector: 'app-data',
      templateUrl: './data.page.html',
      styleUrls: ['./data.page.scss'],
    })
    export class DataPage implements OnInit {
      allData: Data[];
      dataServiceSub: Subscription;
      isLoading: boolean;

      constructor(private myService: MyService) {}

      ngOnInit() {
        this.dataServiceSub = this.myService.data.subscribe(
          (data) =&gt; {
            console.log(data);
            this.allData = data;
          }
        );
      }

      ngOnDestroy() {
        if (this.dataServiceSub) {
          console.log('ngOnDestroy');
          this.dataServiceSub.unsubscribe();
        }
      }

      ionViewWillEnter() {
        this.isLoading = true;
        this.myService.getAllData().subscribe(() =&gt; {
          console.log('ionViewWillEnter');
          this.isLoading = false;
        });
      }
    }

</code></pre>
<p><strong>DataPage.spec</strong></p>
<pre><code>    import { MyService } from '../services/my.service';
    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    import { IonicModule } from '@ionic/angular';

    import { DataPage } from './data.page';
    import { of } from 'rxjs';

    describe('DataPage', () =&gt; {
      let component: DataPage;
      let fixture: ComponentFixture&lt;DataPage&gt;;
      let serviceSpy: jasmine.SpyObj&lt;MyService&gt;;

      beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
          declarations: [DataPage],
          providers: [
            {
              provide: MyService,
              useClass: MyService
            },
          ],
          imports: [IonicModule.forRoot()],
        }).compileComponents();

        fixture = TestBed.createComponent(DataPage);
        component = fixture.componentInstance;
        fixture.detectChanges();
      }));

      fit('Should show list of data if data is available', () =&gt; {
        serviceSpy = TestBed.get(MyService);
        spyOn(serviceSpy, 'getAllData').and.returnValue(of([
          {
            id: '1',
            title: 'Rice',
          },
          {
            id: '2',
            title: 'Wheat',
          },
          {
            id: '33',
            title: 'Water',
          },
        ]));
        fixture.detectChanges();
        const element = fixture.nativeElement.querySelectorAll(
          '[test-tag=&quot;dataList&quot;] ion-item'
        );
        console.log(
          fixture.nativeElement.querySelectorAll('[test-tag=&quot;dataList&quot;]')
        );
        expect(element.length).toBe(3);
      });
    });
</code></pre>
<p><strong>HTML</strong></p>
<pre><code>
    &lt;ion-content&gt;
      &lt;div test-tag=&quot;empty&quot; class=&quot;ion-text-center&quot;&gt;
        &lt;ion-text color=&quot;danger&quot;&gt;
          &lt;h1&gt;No data&lt;/h1&gt;
        &lt;/ion-text&gt;
      &lt;/div&gt;
      &lt;div test-tag=&quot;dataList&quot;&gt;
        &lt;ion-list&gt;
          &lt;ion-item *ngFor=&quot;let data of allData&quot;&gt;
            &lt;ion-label test-tag=&quot;title&quot;&gt;{{data.title}}&lt;/ion-label&gt;
          &lt;/ion-item&gt;
        &lt;/ion-list&gt;
      &lt;/div&gt;
    &lt;/ion-content&gt;


</code></pre>
",https://stackoverflow.com/questions/65866453/angular-integration-testing-jasmine-spy-cant-mock-a-service-method-returnin,"['angular', 'typescript', 'rxjs', 'jasmine', 'angular-test']",628,True,2,2
Best practice for integration testing in React Redux app?,"<p>I'm trying to set up tests for a React-Redux application. Most resources including <a href=""https://redux.js.org/usage/writing-tests"" rel=""nofollow noreferrer"">Redux Docs</a>, and <a href=""https://kentcdodds.com/blog/testing-implementation-details"" rel=""nofollow noreferrer"">the main contributor to react-testing-library</a> argues for a focus on integration tests and that the Redux code as far as possible should be considered an implementation detail. That's cool and all, but I'm struggling to do this in practice.</p>
<p>Most examples I've found on integration testing sets up a component where you can observe the effect in the immediate unit. But several places in my app, I have components that send dispatches to my store which causes a re-render in another part of the app. To illustrate my question, I've made a simplified component tree below where I want to click the <code>AddToListButton</code> to cause <code>Element1</code> to be added to the <code>List</code>.</p>
<p>If Redux is an implementation detail, how do I actually test that clicking the button causes the update without rendering (more or less) the whole app? I understand how to do unit-testing and end-to-end testing, but not sure how I would implement integration testing.</p>
<pre><code>&lt;App&gt;
  &lt;Search&gt;
    &lt;SearchResult&gt;
      &lt;Element1&gt;
        &lt;AddToListButton /&gt; //I WANT TO TEST THIS BUTTON
      &lt;/Element1&gt;
      &lt;Element2&gt;
        &lt;AddToListButton /&gt;
      &lt;/Element2&gt; 
    &lt;/SearchResult&gt;
  &lt;/Search&gt;
  &lt;List&gt;
    &lt;Element1 /&gt; // WHEN THE BUTTON IS PRESSED THE ELEMENT SHOULD GO HERE
  &lt;/List&gt;
&lt;/App&gt;

</code></pre>
",https://stackoverflow.com/questions/68939827/best-practice-for-integration-testing-in-react-redux-app,"['reactjs', 'redux', 'react-testing-library']",128,True,0,1
Integration testing DRF,"<p>I'm using Django with DRF as just an API--it doesn't serve any FE assets of any kind. I know the Django testing suite is built on the Python native <code>unittest</code> library and plan on using it for unit testing.</p>
<ul>
<li>When it comes to integration testing, is it sufficient or should something like Behave be used?</li>
<li>If <code>unittest</code> is sufficient, should it be used in conjunction with some kind of faker?</li>
</ul>
",https://stackoverflow.com/questions/66676964/integration-testing-drf,"['django', 'testing', 'django-rest-framework', 'integration-testing']",835,True,2,1
TestEngine with ID &#39;junit-jupiter&#39; failed to discover tests - Caused by: org.junit.platform.commons.JUnitException: ClassSelector resolution failed,"<p>I am having an issue running my Integration Test.</p>
<p>As part of my Test, I use <code>exec-maven-plugin</code> to pull down other projects from source control and then run them locally so my Test can use that to perform against.</p>
<p>My Maven dependencies for JUnit are:</p>
<pre><code>&lt;plugins&gt;
    &lt;plugin&gt;
        &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt;
        &lt;version&gt;3.0.0-M5&lt;/version&gt;
        &lt;configuration&gt;
            &lt;useModulePath&gt;false&lt;/useModulePath&gt;
            &lt;useSystemClassLoader&gt;false&lt;/useSystemClassLoader&gt;
            &lt;skipTests&gt;false&lt;/skipTests&gt;
            &lt;includes&gt;
                &lt;include&gt;**/*IntegrationTest.java&lt;/include&gt;
            &lt;/includes&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;
&lt;/plugins&gt;
...
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
    &lt;version&gt;2.4.2&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
    &lt;exclusions&gt;
        &lt;exclusion&gt;
            &lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
            &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
        &lt;/exclusion&gt;
    &lt;/exclusions&gt;
&lt;/dependency&gt;
</code></pre>
<p>I have created a profile called <code>integration-test</code> so that I can choose when to enable integration testing and also added an argument to <code>maven-surefire-plugin</code> called <code>skipUTs</code> so I can skip Unit Tests.</p>
<p>The output of running: <code>mvn clean verify -Pintegration-test -DskipUTs=true</code></p>
<pre><code>org.junit.platform.commons.JUnitException: TestEngine with ID 'junit-jupiter' failed to discover tests
    at org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discoverEngineRoot(EngineDiscoveryOrchestrator.java:111)
    at org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discover(EngineDiscoveryOrchestrator.java:85)
    at org.junit.platform.launcher.core.DefaultLauncher.discover(DefaultLauncher.java:92)
    at org.junit.platform.launcher.core.DefaultLauncher.discover(DefaultLauncher.java:67)
    at org.apache.maven.surefire.junitplatform.TestPlanScannerFilter.accept(TestPlanScannerFilter.java:56)
    at org.apache.maven.surefire.api.util.DefaultScanResult.applyFilter(DefaultScanResult.java:102)
    at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.scanClasspath(JUnitPlatformProvider.java:147)
    at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invoke(JUnitPlatformProvider.java:128)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:428)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:162)
    at org.apache.maven.surefire.booter.ForkedBooter.run(ForkedBooter.java:562)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:548)
Caused by: org.junit.platform.commons.JUnitException: ClassSelector [className = 'com.farmlandbee.app.integration.IntegrationTest'] resolution failed
    at org.junit.platform.launcher.listeners.discovery.AbortOnFailureLauncherDiscoveryListener.selectorProcessed(AbortOnFailureLauncherDiscoveryListener.java:39)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolveCompletely(EngineDiscoveryRequestResolution.java:102)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.run(EngineDiscoveryRequestResolution.java:82)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolver.resolve(EngineDiscoveryRequestResolver.java:113)
    at org.junit.jupiter.engine.discovery.DiscoverySelectorResolver.resolveSelectors(DiscoverySelectorResolver.java:45)
    at org.junit.jupiter.engine.JupiterTestEngine.discover(JupiterTestEngine.java:69)
    at org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discoverEngineRoot(EngineDiscoveryOrchestrator.java:103)
    ... 11 more
Caused by: java.lang.ArrayStoreException
    at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:724)
    at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:531)
    at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:355)
    at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:286)
    at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120)
    at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72)
    at java.lang.Class.getAnnotationCache(Class.java:2535)
    at java.lang.Class.getDeclaredAnnotation(Class.java:2221)
    at org.junit.platform.commons.util.AnnotationUtils.findAnnotation(AnnotationUtils.java:128)
    at org.junit.platform.commons.util.AnnotationUtils.findAnnotation(AnnotationUtils.java:115)
    at org.junit.jupiter.engine.descriptor.DisplayNameUtils.determineDisplayName(DisplayNameUtils.java:68)
    at org.junit.jupiter.engine.descriptor.JupiterTestDescriptor.&lt;init&gt;(JupiterTestDescriptor.java:69)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.&lt;init&gt;(ClassBasedTestDescriptor.java:94)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.&lt;init&gt;(ClassTestDescriptor.java:51)
    at org.junit.jupiter.engine.discovery.ClassSelectorResolver.newClassTestDescriptor(ClassSelectorResolver.java:119)
    at org.junit.jupiter.engine.discovery.ClassSelectorResolver.lambda$resolve$0(ClassSelectorResolver.java:71)
    at org.junit.jupiter.engine.discovery.ClassSelectorResolver$$Lambda$61/0000000000000000.apply(Unknown Source)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution$DefaultContext.createAndAdd(EngineDiscoveryRequestResolution.java:246)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution$DefaultContext.addToParent(EngineDiscoveryRequestResolution.java:209)
    at org.junit.jupiter.engine.discovery.ClassSelectorResolver.resolve(ClassSelectorResolver.java:71)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.lambda$resolve$2(EngineDiscoveryRequestResolution.java:134)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution$$Lambda$47/0000000000000000.apply(Unknown Source)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.ArrayList$ArrayListSpliterator.tryAdvance(ArrayList.java:1359)
    at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
    at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:514)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:501)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:487)
    at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:241)
    at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:531)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolve(EngineDiscoveryRequestResolution.java:185)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolve(EngineDiscoveryRequestResolution.java:125)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolveCompletely(EngineDiscoveryRequestResolution.java:91)
    ... 16 more
</code></pre>
<p>Test Class is roughly:</p>
<pre><code>@SpringBootTest(classes = Application.class,
        webEnvironment = WebEnvironment.RANDOM_PORT)
@Import({SSLRestTemplateConfig.class})
@ExtendWith(SpringExtension.class)
@ActiveProfiles(profiles = {&quot;integration&quot;})
public class IntegrationTest {

    @LocalServerPort
    private int port;

    private final RestTemplate restTemplate;

    @Spy
    private final Service Service;

    private final IQueue&lt;String&gt; queue;

    @Captor
    ArgumentCaptor&lt;String&gt; captor;

    @Autowired
    public IntegrationTest(RestTemplate restTemplate,
                                Service service,
                                HazelcastInstance hazelcastInstance) {
        this.restTemplate = restTemplate;
        this.service = accountingQueueService;
        this.queue = hazelcastInstance.getQueue(&quot;queue&quot;);
    }

    @BeforeEach
    public void setup() {
        queue.clear();
    }

    @Test
    public void IntegrationTest() throws InterruptedException {
        ...
    }

}

</code></pre>
<p>Any help would be greatly appreciated.</p>
",https://stackoverflow.com/questions/66227706/testengine-with-id-junit-jupiter-failed-to-discover-tests-caused-by-org-jun,"['java', 'maven', 'junit', 'junit5']",19992,True,13,5
How to use RTL to do integration testing on component with complex reducer?,"<p>I want to introduce integration testing with React Testing Library into my app, but I'm running into some high-level roadblocks.</p>
<p>The examples in documentation are great, but I feel like there isn't an example where the redux state is very complicated and is hydrated from several APIs.</p>
<p>I have a component I want to test, but the data it needs comes from probably 8+ APIs, all stored in different parts of the reducer. Its child components also have their own redux connectors that come from other places in the reducer which are hydrated by other API calls.</p>
<p>Is this something that can be integration tested, and by that I mean not mocking the props, setting up a real reducer, and using MSW to intercept all the API calls needed? (vs mocking the props of the component and mocking its redux connected child components).</p>
<p>I am concerned that an engineer would need to understand far more than what should be necessary to write an integration test for these types of very complicated cases.</p>
<p>A toy Twitter example:</p>
<p>I have a parent <code>&lt;Tweets/&gt;</code> component that renders <code>&lt;Tweet/&gt;</code> children.</p>
<p>I have a tweet object that comes from the /tweets api.
I have a user object that comes from the /users api.</p>
<p>A tweet object</p>
<pre><code>{
  body: 'Hello World',
  userId: 123
}
</code></pre>
<p>A user object</p>
<pre><code>{
  id: 123,
  name: 'John Smith'
}
</code></pre>
<p><strong>Tweets.jsx</strong></p>
<pre><code>const mapState = (state) =&gt; ({
  tweets: selectTweets(state)
});

const Tweets = ({tweets}) =&gt; {
  return (
    tweets.map(tweet =&gt; (
      &lt;Tweet tweet={tweet} /&gt;
    ))
  );
}
</code></pre>
<p><strong>Tweet.jsx</strong></p>
<pre><code>const mapState = (state, {tweet}) =&gt; ({
  user: selectUserById(state, { id: tweet.userId })
});

const Tweet = ({user, tweet}) =&gt; {
  return (
    &lt;div&gt;
      &lt;div&gt;{ tweet.body }&lt;/div&gt;
      &lt;div&gt;{ user.name }&lt;/div&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>Although I feel this is a fairly contrived example, I can already imagine difficulties integration testing <code>Tweets</code> since I must also understand that its child <code>Tweet</code> requires data from <code>/users</code>. Once the app comes more complex, where perhaps the children of <code>Tweet</code> need their own data from redux, I feel like integration testing becomes unreasonably difficult.</p>
<p>Am I missing something? Or in cases like this, do I need to mock in order to decrease the scope of what I am testing?</p>
",https://stackoverflow.com/questions/67118457/how-to-use-rtl-to-do-integration-testing-on-component-with-complex-reducer,"['reactjs', 'redux', 'react-testing-library']",219,False,1,0
How do I get Authorization working in ASP.net core integration testing (I&#39;m very close),"<p>I've followed <a href=""https://lukaszcoding.com/integration-testing-in-net-core/"" rel=""nofollow noreferrer"">these instructions</a> to get Authentication working with ASP.net core integration testing. It's very nearly working. My HttpContext.User is correctly populated with Claims. But my requests to Web API controllers with the <code>[Authorize]</code> attribute still fail, unless I specify the scheme: <code>[Authorize(AuthenticationSchemes = &quot;Test&quot;)]</code> works. I am careful to specify &quot;Test&quot; as the default scheme when I add it in my <code>builder.ConfigureTestServices()</code> method, so why isn't it being accepted as the default?</p>
<pre><code>builder.ConfigureTestServices(services =&gt;
{
    /* Overriding policies and adding Test Scheme defined in TestAuthHandler */
    services.AddMvc(options =&gt;
    {
        var policy = new AuthorizationPolicyBuilder(new[] { &quot;Test&quot; })
            .RequireAuthenticatedUser()
            .AddAuthenticationSchemes(&quot;Test&quot;)
            .Build();

        options.Filters.Add(new AuthorizeFilter(policy));
    });

    /* Adding Default Authentication schemes
        This is enough to prevent unauthorized client (if you wish to have that kind of tests) */
    services.AddAuthentication(options =&gt;
    {
        options.DefaultAuthenticateScheme = &quot;Test&quot;;
        options.DefaultChallengeScheme = &quot;Test&quot;;
        options.DefaultScheme = &quot;Test&quot;;
        options.DefaultForbidScheme = &quot;Test&quot;;
        options.DefaultChallengeScheme = &quot;Test&quot;;
        options.DefaultSignInScheme = &quot;Test&quot;;
        options.DefaultSignOutScheme = &quot;Test&quot;;
    })
    /* Here we're adding TestAuthentication Scheme with Handler that will Authenticate our client based on Claims */
    .AddScheme&lt;AuthenticationSchemeOptions, TestAuthHandler&gt;(&quot;Test&quot;, options =&gt; { });
});
</code></pre>
",https://stackoverflow.com/questions/70348066/how-do-i-get-authorization-working-in-asp-net-core-integration-testing-im-very,"['c#', 'asp.net-core', 'authentication']",521,False,0,0
"How to use in-memory MongoDB with Rails, Mongoid, and Rspec?","<p>On unit or integration testing, I need to be able to use in-memory mongoDB just for convenience. Am I able to do that? I tried searching for solution and there is no tutorial in how to write mongoid.yml to use in-memory.</p>
<p>Other than that, can I just use default env inside mongoid.yml rather than writing duplicates for both development and production? It is like moving from</p>
<pre><code>development:
  client:
    ...

production:
  client:
    ...
</code></pre>
<p>into</p>
<pre><code>default: &amp;default
  client:
    ...
</code></pre>
",https://stackoverflow.com/questions/67121162/how-to-use-in-memory-mongodb-with-rails-mongoid-and-rspec,"['ruby-on-rails', 'ruby', 'mongodb', 'mongoid', 'rspec-rails']",191,False,0,1
Use a Spring JPA repository exclusively for tests,"<p>Using a repository in Spring is straightforward. For integration testing, I'd like to define a repository which provides test-specific methods without &quot;polluting&quot; the original repository.</p>
<p><strong>Example</strong></p>
<p>Let's say there is the following repo:</p>
<pre class=""lang-java prettyprint-override""><code>@Repository
public interface UserRepo extends JpaRepository&lt;User, Long&gt; {
}
</code></pre>
<p>For testing purposes I'd like to have something like the following but this repo shall only reside in a package in <code>src/test</code>.</p>
<pre class=""lang-java prettyprint-override""><code>@Repository
public interface UserTestRepo extends JpaRepository&lt;User, Long&gt; {

  boolean existsByEmail(String email);
}
</code></pre>
<p>When adding <code>@Autowired public UserTestRepo userTestRepo</code> in my test, then the following exception occurs:</p>
<p><code>No EntityManager with actual transaction available for current thread</code></p>
<p>Is it possible to have a distinct repo which is only accessible for testing?</p>
",https://stackoverflow.com/questions/66429023/use-a-spring-jpa-repository-exclusively-for-tests,"['spring-boot', 'spring-data-jpa', 'spring-test']",386,False,4,1
Wire Mock Stub Response body is not read by Spring Boot,"<p>I am creating a Spring Boot based Micro Service. This service will call a external service. I want to create Stub for that service to do my integration testing.</p>
<p>I have following configuration. But for some reason my while running my test class Stub is not properly created due to which my test is failing.</p>
<p>Test class</p>
<pre><code>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
        properties = {&quot;server.context-path=/app&quot;, &quot;app.baseUrl=http://restapi-2.herokuapp.com&quot;})
@AutoConfigureWireMock
@AutoConfigureMockMvc
class Restapi1ApplicationTests {


    @Autowired
    private ApiService apiService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MockMvc mockMvc;

    @Test
    void contextLoads() {
    }

    @Test
    void getMessage() throws Exception {

        MockRestServiceServer mockRestServiceServer = WireMockRestServiceServer.with(this.restTemplate)
                                                                              .baseUrl(&quot;http://restapi-2.herokuapp.com&quot;)
                                                                              .stubs(&quot;classpath:/stubs/companyresponse.json&quot;).build();

        CompanyDetail companyDetail = new CompanyDetail();
        companyDetail.setCompanyName(&quot;Test&quot;);

    
        mockMvc.perform(MockMvcRequestBuilders.get(&quot;/api/v1/messages&quot;))
                       .andExpect(status().isOk())
                        //.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
                       .andExpect(MockMvcResultMatchers.jsonPath(&quot;$.companyName&quot;).value(&quot;Test&quot;));

                       //.andExpect(MockMvcResultMatchers.content().json(objectMapper.writeValueAsString(companyDetail)));

    }
}



@RestController
public class Api_1_Controller {

    private final ApiService apiService;

    public Api_1_Controller(ApiService apiService) {
        this.apiService = apiService;
    }

    @GetMapping(path = &quot;/api/v1/messages&quot;)
    public CompanyDetail getMessage(){
        CompanyDetail companyDetail = apiService.getMessageFromApi();
        return companyDetail;
    }
}


@Service
public class ApiService {

    private RestTemplate restTemplate;

    public ApiService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }


    public CompanyDetail getMessageFromApi(){
        CompanyDetail companyDetail = null;
        try{
            companyDetail = restTemplate.getForEntity(&quot;http://restapi-2.herokuapp.com/companies&quot;,CompanyDetail.class).getBody();
        }catch(Exception exception){
            exception.printStackTrace();
            throw exception;
        }

        return  companyDetail;
    }
}


@JsonInclude(value = JsonInclude.Include.NON_NULL)
public class CompanyDetail {

    
    private String companyName;

    //Getter and Setters
}

</code></pre>
<p>companyresponse.json is in below path</p>
<pre><code>test/resources/stubs


{
  &quot;request&quot;: {
    &quot;urlPath&quot;: &quot;/companies&quot;,
    &quot;method&quot;: &quot;GET&quot;
  },
  &quot;response&quot;: {
    &quot;status&quot;: 200,
    &quot;jsonBody&quot;: {&quot;companyName&quot; : &quot;Test&quot;},
    &quot;headers&quot;: {
      &quot;Content-Type&quot;: &quot;application/json&quot;
    }
  }
}

</code></pre>
<p>pom.xml</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;2.4.4&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;
    &lt;groupId&gt;com.heroku&lt;/groupId&gt;
    &lt;artifactId&gt;restapinew-1&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
    &lt;name&gt;restapinew-1&lt;/name&gt;
    &lt;description&gt;restapi-1 project for Spring Boot&lt;/description&gt;
    &lt;properties&gt;
        &lt;java.version&gt;11&lt;/java.version&gt;
        &lt;spring-cloud.version&gt;2020.0.2&lt;/spring-cloud.version&gt;
    &lt;/properties&gt;
    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
            &lt;artifactId&gt;spring-cloud-starter-contract-stub-runner&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-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
            &lt;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
                    &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;dependencyManagement&gt;
        &lt;dependencies&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
                &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;
                &lt;version&gt;${spring-cloud.version}&lt;/version&gt;
                &lt;type&gt;pom&lt;/type&gt;
                &lt;scope&gt;import&lt;/scope&gt;
            &lt;/dependency&gt;
        &lt;/dependencies&gt;
    &lt;/dependencyManagement&gt;

    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
                &lt;configuration&gt;
                    &lt;imageName&gt;restapinew-1&lt;/imageName&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;

&lt;/project&gt;

</code></pre>
<p>When Running this test case getting Response body as null</p>
<pre><code>MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = []
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: No value at JSON path &quot;$.companyName&quot;

    at org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:304)
    at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:99)

</code></pre>
",https://stackoverflow.com/questions/66828298/wire-mock-stub-response-body-is-not-read-by-spring-boot,"['spring-boot', 'wiremock', 'spring-cloud-contract']",841,False,1,1
Is Injecting Repository dependency in Integration Testing is bad practice,"<p>I am developing REST CURD API using Spring Boot and following TDD. I am starting with READ operation to test the READ works I have to prepopulate data in my DB. For this purpose I am using H2 DB and created my Repository and using this Repository in my Integration testing Setup step to populate the data before my GET actual data being executed. My college told me its bad practice using Repository in integration testing to create data for this GET operation test instead he suggested to call POST API endpoint in Setup step and Execute GET test also implement PUT and DELETE IT tests.</p>
<p>My question is</p>
<ol>
<li>Is injecting actual repository for purpose of data setup in Integration test class is wrong?</li>
<li>Can we use/call and Endpoint (POST) in setup or in GET testcase before actual Test logic being executed?</li>
<li>Can we call POST endpoint in init/setup and populate the data instead using Repository and implement GET,PUT,DELETE tests using POST data? Is advisable calling direct POST endpoint in setup for purpose of testing another endpoint in Test class and using @TestOrder annotation on class level.</li>
</ol>
<p>Case 1</p>
<pre><code>@SpringBootTest
@AutoConfigureMockMvc
public class CURDTest() {
 
  @Autowired
  private TestMovieRepository testMovieRepository;

  @BeforeEach
  void init() {
   Movie myMovie = new Movie(&quot;test&quot;);
   testMovieRepository.save(myMovie);
}

@Test
void getMovie_whenReturnsMovie(){
  //Test logic using mockMvc;
}
}
</code></pre>
<p>Case 2:</p>
<pre><code>@SpringBootTest
@AutoConfigureMockMvc
public class CURDTest() {
 
  
  @BeforeEach
  void init() {
   //call POST Endpoint usin MockMvc populate data in table
}

@Test
void getMovie_whenReturnsMovie(){
  //Test logic using mockMvc;
}
}

</code></pre>
<p>Case 3:</p>
<pre><code>@SpringBootTest
@AutoConfigureMockMvc
@TestOrder
public class CURDTest() {
 
  
  @BeforeEach
  void init() {
   //call POST Endpoint usin MockMvc populate data in table
}

@Test
@Order(1)
void getMovie_whenReturnsMovie(){
  //Test logic using mockMvc;
}

@Test
@Order(2)
void updateMovie_whenReturnsMovie(){
  //Test logic using mockMvc;
}

}
</code></pre>
",https://stackoverflow.com/questions/66000350/is-injecting-repository-dependency-in-integration-testing-is-bad-practice,"['spring-boot', 'junit5', 'spring-test']",62,False,1,0
Manipulate browser history in Cypress,"<p>I'm using <a href=""https://docs.cypress.io/guides/overview/why-cypress"" rel=""nofollow noreferrer"">Cypress</a> for integration testing. On the page I have added &quot;Back&quot; button. I want to test, that when I click that button, the browser displays the previous page. I'm looking for a way to add some url in browser history from Cypress. This way, I'll click the button, I'll check that corresponding page is rendered and that's all. Is there any way from Cypress to manipulate browser history? For example like:</p>
<pre><code>cy.history.push(newUrl);
</code></pre>
<p>or something?</p>
",https://stackoverflow.com/questions/67906753/manipulate-browser-history-in-cypress,"['javascript', 'react-native', 'browser', 'cypress']",995,False,0,1
What ThreadX uses to do its testing?,"<p>I am a student developing a microcontroller application that uses the Azure RTOS ThreadX, and I never used tests and want to start doing unit testing, integration testing, and automatic tests. I found out the Ceedling and Google Test frameworks, but I would like to know what the community and the ThreadX team uses or recommends to proceed with the tests.</p>
<p>My programming language is C, and I'm using a Cortex M0+.</p>
",https://stackoverflow.com/questions/68845339/what-threadx-uses-to-do-its-testing,"['unit-testing', 'testing', 'threadx', 'azure-rtos']",263,False,0,1
Flutter Integration Test: Mock Application Class Values,"<p>I want to mock my App state values in integration_test package in Flutter. Suppose I have a class that returns my particular sensor is on/off or permission is granted or not. They have a function like <code>isOn()</code>. In case of integration testing I want that returns always true. How can I mock that values which loads while integration Test?</p>
<p>N.B.: Shared Preferences values are modifiable using the following method <code>SharedPreferences.setMockInitialValues({})</code>. but don't know how can I modify Custom class values.</p>
",https://stackoverflow.com/questions/66095376/flutter-integration-test-mock-application-class-values,"['flutter', 'integration-testing']",99,False,1,0
Flutter integration test firebase auth (email link or google sign in),"<p>I'm adding integration testing (using the integration_test package) to my app but I am running into a problem.</p>
<p>Let me explain. The first step when my app launch is authentication for which I have 3 options: firebase email link, firebase google sign in, and firebase facebook sign in.</p>
<p>What is blocking me is that all these sign in methods require actions outside of the main app dart code and thus are not accessible by flutter driver.</p>
<p>Am I missing something here? And if not how should that case be handled?</p>
<p>Cheers!</p>
",https://stackoverflow.com/questions/66816264/flutter-integration-test-firebase-auth-email-link-or-google-sign-in,"['flutter', 'firebase-authentication', 'flutter-integration-test']",1594,True,9,3
Spring @DynamicPropertySource does not work if an empty constructor is present in an @Configuration class,"<p>I am using <code>TestContainers</code> for integration testing and i am using <code>@DynamicPropertySource</code> to set-up the <code>KafkaContainer</code> bootstrap servers like so:</p>
<pre><code>@DynamicPropertySource
static void kafkaProperties(DynamicPropertyRegistry registry) {
    registry.add(&quot;spring.kafka.bootstrap-servers&quot;, () -&gt; { 
        return kafkaContainer1.getHost() + &quot;:&quot; + kafkaContainer1.getFirstMappedPort();
    });
}
</code></pre>
<p>And this works like a charm, i.e as intended in my <code>KafkaTopicConfiguration</code> class:</p>
<pre><code>@Configuration
public class KafkaTopicConfiguration {

    private String bootstrapServers;

    public KafkaTopicConfiguration(@Value(&quot;${spring.kafka.bootstrap-servers}&quot;) String bootstrapServers) {
        this.bootstrapServers = bootstrapServers;
    }
</code></pre>
<p>where <code>bootstrapServers</code> will get the address of the KafkaContainer exposed by Docker on the host.
Now, i added an empty constructor, because i wanted to troubleshoot something, like so:</p>
<pre><code>public KafkaTopicConfiguration() {
    System.out.println(&quot;In KafkaTopicConfiguration constructor&quot;);
}
</code></pre>
<p>and suddenly the <code>boostrapServers</code> value become <code>null</code>. When i remove the empty constructor, it's back to normal. Does anyone know why? Thanks.</p>
",https://stackoverflow.com/questions/66899258/spring-dynamicpropertysource-does-not-work-if-an-empty-constructor-is-present-i,"['spring', 'testcontainers']",922,True,0,1
How to mock a service in Panther test?,"<p>I have a web page that does an external API call when a form being submitted. My idea is to mock <code>HttpClientInterface</code> as long as a complete E2E scenario will require a running dev server for that purpose, which is not always possible in my case.</p>
<p>Here is what I tried so far:</p>
<p><code>services.yaml</code></p>
<pre><code>when@test:
    services:
        _defaults:
            public: true

        test.Symfony\Contracts\HttpClient\HttpClientInterface: '@Symfony\Contracts\HttpClient\HttpClientInterface'
</code></pre>
<p>My testing scenario:</p>
<pre><code>class ClientAppointmentControllerTest extends PantherTestCase
{
    public function testForm(): void
    {
        $client = static::createPantherClient();
        
        $response = new MockResponse(null, ['http_code' =&gt; 400]);
        $this-&gt;mockResponse($response);

        $crawler = $client-&gt;request('GET', '/our-survey');

        $form = $crawler-&gt;selectButton('Save')-&gt;form();
        $client-&gt;submit($form);

        static::assertEquals($response-&gt;getRequestMethod(), 'POST');
        static::assertEquals($response-&gt;getRequestOptions()['body'], []);
        static::assertEquals($response-&gt;getRequestUrl(), 'ad');
    }

    private function mockResponse(MockResponse $response): void
    {
        self::getContainer()-&gt;set(
            'test.Symfony\Contracts\HttpClient\HttpClientInterface',
            new TraceableHttpClient(new MockHttpClient($response))
        );
    }
}
</code></pre>
<p>But it gives me the following error: <code>Symfony\Component\HttpClient\Exception\InvalidArgumentException: MockResponse instances must be issued by MockHttpClient before processing</code>. Apparently it does not work for <code>PantherTestCase</code> (it works for <code>WebTestCase</code> tests though).</p>
<p>Is it possible to mock response somehow during integration testing?</p>
",https://stackoverflow.com/questions/69256138/how-to-mock-a-service-in-panther-test,"['php', 'symfony', 'integration-testing', 'symfony5', 'symfony-panther']",386,False,1,0
Spock: How to properly share features between implementations of Specification,"<p>I encountered an unfortunate aspect of Spock Framework (1.3-groovy-2.5), which I use for integration testing of a Gradle plugin.</p>
<p><strong>The code sample</strong></p>
<p>Parent class:</p>
<pre><code>class ClassA extends Specification {

    def setupSpec() {
        System.out.println(&quot;In ClassA setupSpec()&quot;)
    }

    def &quot;base feature&quot;() {
        expect:
        true
    }
}
</code></pre>
<p>Child class:</p>
<pre><code>class ClassB extends ClassA {

    @Override
    def setupSpec() {
        System.out.println(&quot;In ClassB setupSpec()&quot;)
    }

    def &quot;extended feature&quot;() {
        expect:
        true
    }
}
</code></pre>
<p>When I run tests in <code>ClassB</code>, both versions of <code>setupSpec()</code> are called:</p>
<pre><code>In ClassA setupSpec()
In ClassB setupSpec()
</code></pre>
<p>Of course, if I call method via native Groovy ways:</p>
<pre><code>class Main {

    static void main(String[] args) {
        ClassB classB = new ClassB()
        classB.setupSpec()
    }
}
</code></pre>
<p>Then I see only what is expected:</p>
<pre><code>In ClassB setupSpec()
</code></pre>
<p>So, evidently, this is a Spock feature of some kind.</p>
<p><strong>Question</strong></p>
<p>In practice, what is the suggested way of inheriting from implementations of <code>Specification</code> while overriding setup logic?</p>
",https://stackoverflow.com/questions/65709174/spock-how-to-properly-share-features-between-implementations-of-specification,"['testing', 'groovy', 'spock']",1415,True,1,2
Simulate Search and Select an option react-select,"<p>I am trying simulate search and select an option from the react-select component version 3.1.1. But it always returning the first item in the list.</p>
<p>Below is my component which is working fine in UI but not for integration testing.</p>
<pre><code>&lt;Select
       id=&quot;test-dropdown&quot;
       inputId=&quot;testsInput&quot;
       className=&quot;select-label-input-margin&quot;
       classNamePrefix=&quot;select&quot;
       name=&quot;test-dropdown&quot;
       placeholder='test placeholder'
       isSearchable={true}
       isClearable={true}
       options={testsOptions}
       value={selectedValue}
       onChange={option =&gt; console.log(option)}
       noOptionsMessage={() =&gt; 'No result found'}
     /&gt;
</code></pre>
<p>To simulate that I am using these piece of code
Here wrapper is the class component that I am mounting.</p>
<pre><code>wrapper.find('Select#test-dropdown').find('input[id=&quot;testsInput&quot;]').simulate('change', { target: { value: 'Test 1 title' } }),
// wrapper.find('input[id=&quot;testsInput&quot;]').simulate('change', { target: { value: 'Test 1 title' } }),    
//If I use this it will select second value in the array
wrapper.find('input[id=&quot;testsInput&quot;]').simulate('keyDown', arrowDown),
// wrapper.find('input[id=&quot;test-dropdown&quot;]').simulate('keyDown', arrowDown),
// wrapper.find('input[id=&quot;test-dropdown&quot;]').simulate('keyDown', arrowDown),
wrapper.find('input[id=&quot;testsInput&quot;]').simulate('keyDown', tabButton)
</code></pre>
<p>I also looked into this issue from the <a href=""https://github.com/JedWatson/react-select/issues/1357"" rel=""nofollow noreferrer"">react-select</a> but no help.</p>
<p>Any idea how we can simulate search and select the option?</p>
",https://stackoverflow.com/questions/65611762/simulate-search-and-select-an-option-react-select,"['reactjs', 'jestjs', 'integration-testing', 'enzyme', 'react-select']",234,False,1,0
Significant text aggregation empty buckets,"<p>I've got a significant text query, and I'm having issues with some integration testing where it always returns an empty array for a test case of 3 documents, with a shared term in a text field:</p>
<pre><code>{
   &quot;query&quot;:{
      &quot;bool&quot;:{
         &quot;filter&quot;:[
            {
               &quot;exists&quot;:{
                  &quot;field&quot;:&quot;title&quot;
               }
            },
            {
               &quot;term&quot;:{
                  &quot;type&quot;:&quot;ITEM&quot;
               }
            }
         ]
      }
   },
   &quot;aggregations&quot;:{
      &quot;search-text&quot;:{
         &quot;sampler&quot;:{
            &quot;shard_size&quot;:100
         },
         &quot;aggregations&quot;:{
            &quot;keywords&quot;:{
               &quot;significant_text&quot;:{
                  &quot;field&quot;:&quot;title&quot;,
                  &quot;min_doc_count&quot;:1
               }
            }
         }
      }
   }
}
</code></pre>
<p>The index has 3 test documents in it, and they're returned by the query, they have a title field, it's a <code>text</code> field, but the buckets are empty, even though it reports <code>&quot;doc_count&quot;:3</code> on the aggregation as a whole:</p>
<pre><code>{
   &quot;took&quot;:30,
   &quot;timed_out&quot;:false,
   &quot;_shards&quot;:{ ... },
   &quot;hits&quot;:{
      &quot;total&quot;:{
         &quot;value&quot;:3,
         &quot;relation&quot;:&quot;eq&quot;
      },
      &quot;max_score&quot;:0,
      &quot;hits&quot;:[
         {
            ...
            &quot;_source&quot;:{
               &quot;title&quot;:&quot;Item1&quot;,
               &quot;type&quot;:&quot;ITEM&quot;
            }
         },
         {
            ...
            &quot;_source&quot;:{
               &quot;title&quot;:&quot;Item2&quot;,
               &quot;type&quot;:&quot;ITEM&quot;
            }
         },
         {
            ...
            &quot;_source&quot;:{
               &quot;title&quot;:&quot;Item 4&quot;,
               &quot;type&quot;:&quot;ITEM&quot;
            }
         }
      ]
   },
   &quot;aggregations&quot;:{
      &quot;search-text&quot;:{
         &quot;doc_count&quot;:3,
         &quot;keywords&quot;:{
            &quot;doc_count&quot;:3,
            &quot;bg_count&quot;:3,
            &quot;buckets&quot;:[]
         }
      }
   }
}
</code></pre>
<p>Anyone know why it's not actually picking up the term &quot;Item&quot;?</p>
",https://stackoverflow.com/questions/68305126/significant-text-aggregation-empty-buckets,['elasticsearch'],72,False,0,0
Mock IRequestClient&lt;&gt; during Integration Testing using MassTransit,"<p>I'm trying to do integration testing against a MediatR Command whose handler depends on an IRequestClient injected into its constructor.</p>
<pre><code>    public class SayHelloCommand : IRequest&lt;string&gt;
    {
    }

    public class SayHelloCommandHandler : IRequestHandler&lt;SayHelloCommand, string&gt;
    {
        private readonly IRequestClient&lt;IGetProfileMessageResult&gt; _profileClient;

        public SayHelloCommandHandler(IRequestClient&lt;IGetProfileMessageResult&gt; profileClient)
        {
            _profileClient = profileClient;
        }
        public async Task&lt;string&gt; Handle(SayHelloCommand request, CancellationToken cancellationToken)
        {
            var profile = (await _profileClient.GetResponse&lt;IGetProfileMessageResult&gt;(new {ProfileId = 1})).Message;

            return $&quot;Hello {profile.FirstName}&quot;;
        }
    }
</code></pre>
<p>I've setup my test suite to use the InMemoryMassTransit but whenever I run my test it times out when it reaches the call using the IRequestClient&lt;&gt;. I've also tried to moq the IRequestClient to return a default response like this -</p>
<pre><code>
        [Test]
        public async Task ShouldSayHello()
        {
          
          
            var mockRequestClient = new Mock&lt;IRequestClient&lt;IGetProfileMessageResult&gt;&gt;();
            mockRequestClient.Setup(x =&gt; x.GetResponse&lt;IGetProfileMessageResult&gt;(It.IsAny&lt;Object&gt;(), default, default)
            .Result.Message).Returns(new GetProfileMessageResult
            {
                FirstName = &quot;John&quot;
            });

            serviceCollection.Add(new ServiceDescriptor(typeof(IRequestClient&lt;IGetProfileMessageResult&gt;), mockRequestClient.Object));

            var result = await SendAsync(command);

            result.Status.Should().BeFalse();
            result.Message.Should().Contain(&quot;John&quot;);
        }
            

</code></pre>
<p>but this still times out.</p>
<p>Is there a way I can set up the InMemoryMassTransit to return a default response when the requestclient is called?</p>
",https://stackoverflow.com/questions/70389744/mock-irequestclient-during-integration-testing-using-masstransit,"['.net-core', 'nunit', 'moq', 'masstransit']",632,False,0,1
How to fix AttributeKey leading to IllegalArgumentException in Netty 4,"<p>I am porting a Netty 3 application to Netty 4. The Netty 3 application uses <code>Attachement</code> to attach objects to the context.</p>
<p>Reading <a href=""https://netty.io/wiki/new-and-noteworthy-in-4.0.html"" rel=""nofollow noreferrer"">New and noteworthy in 4.0</a> I see Attachment has been removed and replaced with AttributeKey/AttributeMap.</p>
<p>The problem is this works when I run the application, but under integration testing, I get the error:</p>
<pre><code>Caused by: java.lang.IllegalArgumentException: 'attr_key' is already in use
</code></pre>
<p>Where <code>attr_key</code> is defined in a shareable Handler has follows:</p>
<pre><code>private final AttributeKey&lt;Object&gt; ATTR_KEY = AttributeKey.newInstance(&quot;attr_key&quot;);
</code></pre>
<p>and then used somewhere else in the same handler class as follows:</p>
<pre><code>channel.attr(ATTR_KEY).set(new Object())
</code></pre>
<p>Any ideas or thoughts on the recommended way to use AttributeKey/AttributeMap to prevent this error? Thanks!</p>
",https://stackoverflow.com/questions/66102669/how-to-fix-attributekey-leading-to-illegalargumentexception-in-netty-4,"['netty', 'netty4']",176,True,1,1
Is there any way to perform Integration testing on API rate limiting?,"<p>I have been trying to add Integration testing for API rate limiting. I am using Xunit with Asp.NetCore.</p>
<p>Right now, I have rate limited my api calls to <strong>x calls per minute</strong>. In my Integration test, I try to run <strong>x+1 number</strong> of api calls and check for <strong>429 error status code</strong>. However, I see that my INT test waits for a minute and <strong>retry the (x+1)th</strong> call and report it as success. (I use Fiddler to check this)</p>
<pre><code>public async Task GetRateLimited()
{
    for (int i = 0; i &lt; x; i++)
    {
        var response = await client.GetApi();
    }
    Func&lt;Task&gt; action = async () =&gt; await client.GetApi();
    MyException exception = await Assert.ThrowsAsync&lt;MyException&gt;(action);
    exception.Response.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
}
</code></pre>
<p>Is there any way to check for the HttpStatusCode 429 requests?</p>
<p>Thanks,</p>
<p>Manisha</p>
",https://stackoverflow.com/questions/68472684/is-there-any-way-to-perform-integration-testing-on-api-rate-limiting,"['asp.net-core', 'integration-testing', 'xunit', 'rate-limiting']",210,False,0,0
How to test an AWS Lambda that returns nothing?,"<p>I have been asked to do some basic integration testing on a lambda which will basically just cal the lambda and verify everything went smoothly. The only issue is, the lambda I am trying to test is invoked by AWS Config as a custom rule. It doesn't return anything. The logic inside the handler is calling EC2 describe instances, doing a check to see if it is considered compliant/non-compliant, and doing a put_evalutions to add the results to aws config. How would you test that when it returns nothing?</p>
",https://stackoverflow.com/questions/68348825/how-to-test-an-aws-lambda-that-returns-nothing,"['amazon-web-services', 'amazon-ec2', 'aws-lambda', 'aws-config']",82,True,-1,1
Having problems trying to test functionality that contains autowired SprngBoot with junit 5,"<p>I want to test some functinality, a service with a repo that is autowired in. I dont want to mock the autowired, this is more a integration test for debugging.</p>
<p>My test is as follow</p>
<pre><code>@SpringBootConfiguration
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class ThrottleRateServiceTest {
    
    ThrottleRateService service = null;
    
    @BeforeEach
    public void setUp() {
        service = new ThrottleRateServiceImpl();
    }
    
    @Test
    public void testThrottoling() {
        service.isAllowed(&quot;test&quot;);
    }
}
</code></pre>
<p>The code is very simple</p>
<pre><code>@Service
public class ThrottleRateServiceImpl implements ThrottleRateService {
    
    private final Logger logger = LogManager.getLogger(ThrottleRateServiceImpl.class);
    
    @Autowired
    ThrottleRateRepository throttleRateRepository;
</code></pre>
<p>The problem is that throttleRateRepository is always null.</p>
<p>I have managed to test this sort of code before. With Junit 4  with</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class) 
</code></pre>
<p>Which autowired all the beans.
Its been a while since I did this sort of integration testing, and its all changed with Junit 5.
Thanks or any hep.</p>
",https://stackoverflow.com/questions/70138922/having-problems-trying-to-test-functionality-that-contains-autowired-sprngboot-w,"['java', 'spring', 'spring-boot', 'junit', 'junit5']",73,True,0,2
Wiremock - sometimes it throws &quot;Software caused connection abort: recv failed&quot;,"<p>I encountered a very strange situation when using Spring and Wiremock for integration testing: suddenly, one specific test started failing intermittently. A snippet of the error below:</p>
<pre><code>org.springframework.web.client.ResourceAccessException: I/O error on POST request for &quot;http://localhost:10314/my/endpoint&quot;: Software caused connection abort: recv failed; nested exception is java.net.SocketException: Software caused connection abort: recv failed
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:785) ~[spring-web-5.3.7.jar:5.3.7]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711) ~[spring-web-5.3.7.jar:5.3.7]
    at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:468) ~[spring-web-5.3.7.jar:5.3.7]
... more logs here ...
</code></pre>
<p><strong>The context</strong> is as follows:
I have added a new test that uses wiremock to stub responses:</p>
<pre><code>wireMockServer.stubFor(WireMock.post(&quot;/my/endpoint&quot;)
    .withRequestBody(containing(aJsonRequestBodyHere))
    .willReturn(aResponse()
            .withBody(aJsonResponseHere)
            .withStatus(HttpStatus.OK.value())
            .withHeader(HttpHeader.CONTENT_TYPE.toString(), CONTENT_TYPE_APPLICATION_JSON)));
</code></pre>
<p>The call to this stub endpoint is made as follows:</p>
<pre><code>given()
    .when()
    .get(&quot;my/endpoint&quot;)
    .then()
    .body(containsString(theExpectedJsonResponse)))
    .statusCode(200);
</code></pre>
<p><strong>The strange part</strong>:</p>
<ul>
<li>the same test runs without any problems on my local machine - if run alone</li>
<li>when running all the tests on my machine, sometimes, the same test fails, sometimes does not</li>
<li>only this test is failing each time; no other test fails</li>
<li>when tests are run on Jenkins, it fails 100%</li>
</ul>
",https://stackoverflow.com/questions/68929051/wiremock-sometimes-it-throws-software-caused-connection-abort-recv-failed,"['spring', 'integration-testing', 'wiremock']",2535,True,7,4
Using ChoETL to print CSV file returns values to Console as &quot;dynamic&quot;,"<p>Hi I am very new to C# and have to turn in a module for integration testing tomorrow. I was trying an easy and expidient way to read CSV files and stumbled on ChoETL:
<a href=""https://www.codeproject.com/Articles/1145337/Cinchoo-ETL-CSV-Reader?msg=5847644#xx5847644xx"" rel=""nofollow noreferrer"">https://www.codeproject.com/Articles/1145337/Cinchoo-ETL-CSV-Reader?msg=5847644#xx5847644xx</a></p>
<p>Following their first example, I tried to run the code:</p>
<pre><code>using ChoETL;
using System;

foreach (dynamic rec in new ChoCSVReader(&quot;Emp.csv&quot;)
    .WithFirstLineHeader())
{            
    Console.WriteLine($&quot;Id: {rec.Id}&quot;);
    Console.WriteLine($&quot;Name: {rec.Name}&quot;);
}
</code></pre>
<p>When I run it, I get the ouput:</p>
<pre><code>Id: 1
Name: dynamic
Id: 2
Name: dynamic
Id: 3
Name: dynamic
</code></pre>
<p>Instead of:</p>
<pre><code>Id: 1
Name: Tom
Id: 2
Name: Carl
Id: 3
Name: Mark
</code></pre>
<p>WHy is this? And what is rec being turned to at runtime? I don't know anythnig about dynamic types</p>
<p>I ran this on a Console project on NetCore 5.0 on VS2019</p>
",https://stackoverflow.com/questions/70283802/using-choetl-to-print-csv-file-returns-values-to-console-as-dynamic,"['c#', '.net-core', 'choetl']",352,False,1,1
How to prevent snakemake from stopping after failed test suite?,"<p>I am attempting to automate integration testing with snakemake (I need the output from some of the files so this seemed like a good tool). However when I need to run two test suites in pytest, the workflow stops if a single test in either suite fails. So for example I have:</p>
<pre><code>rule run_tests:
    run:
        commands = [
            &quot;pytest test_that_should_fail&quot;,
            &quot;pytest test_that_should_succeed&quot;
        ]
        for c in commands:
            shell(c)
</code></pre>
<p>And I need the output of the test that should fail for the latter test. Is there a way to prevent snakemake from stopping after running &quot;pytest test_that_should_fail&quot; ? Additionally snakemake stops without any sort of error message just a generic: &quot;Error in rule run_tests: jobid: 0&quot;</p>
",https://stackoverflow.com/questions/67393279/how-to-prevent-snakemake-from-stopping-after-failed-test-suite,"['python', 'pytest', 'snakemake']",106,True,1,2
Jest integration test Express REST API with Mongoose,"<p>everybody. I'm new to unit/integration testing and I'm having trouble with testing one of my API routes which involves file system operations and Mongoose model method calls. I need to be able mock mongoose model method as well as router's post method. Let me share you my router's post method.</p>
<p>documents.js</p>
<pre><code>const { User } = require('../models/user');
const { Document } = require('../models/document');
const isValidObjectId = require('./../helpers/isValidObjectId');
const createError = require('./../helpers/createError');
const path = require('path');
const fs = require('fs');
const auth = require('./../middlewares/auth');
const uploadFile = require('./../middlewares/uploadFile');
const express = require('express');
const router = express.Router();

.
.
.
router.post('/mine', [auth, uploadFile], async (req, res) =&gt; {
    const user = await User.findById(req.user._id);

    user.leftDiskSpace(function(err, leftSpace) {
        if(err) {
            return res.status(400).send(createError(err.message, 400));
        } else {
            if(leftSpace &lt; 0) {
                fs.access(req.file.path, (err) =&gt; {
                    if(err) {
                        res.status(403).send(createError('Your plan\'s disk space is exceeded.', 403));
                    } else {
                        fs.unlink(req.file.path, (err) =&gt; {
                            if(err) res.status(500).send('Silinmek istenen doküman diskten silinemedi.');
                            else res.status(403).send(createError('Your plan\'s disk space is exceeded.', 403));
                        });
                    }
                });
            } else {
                let document = new Document({
                    filename: req.file.filename,
                    path: `/uploads/${req.user.username}/${req.file.filename}`,
                    size: req.file.size
                });
        
                document.save()
                    .then((savedDocument) =&gt; {
                        user.documents.push(savedDocument._id);
                        user.save()
                            .then(() =&gt; res.send(savedDocument));
                    });
            }
        }
    });
});
.
.
.

module.exports = router;
</code></pre>
<p>documents.test.js</p>
<pre><code>const request = require('supertest');
const { Document } = require('../../../models/document');
const { User } = require('../../../models/user');
const mongoose = require('mongoose');
const fs = require('fs');
const path = require('path');
const config = require('config');

let server;

describe('/api/documents', () =&gt; {
    beforeEach(() =&gt; { server = require('../../../bin/www'); });
    afterEach(async () =&gt; {
        let pathToTestFolder = path.join(process.cwd(), config.get('diskStorage.destination'), 'user');
        
        await fs.promises.access(pathToTestFolder)
            .then(() =&gt; fs.promises.rm(pathToTestFolder, { recursive: true }))
            .catch((err) =&gt; { return; });

        await User.deleteMany({});
        await Document.deleteMany({});

        server.close();
    });

    .
    .
    .

    describe('POST /mine', () =&gt; {
        let user;
        let token;
        let file;

        const exec = async () =&gt; {
            return await request(server)
                .post('/api/documents/mine')
                .set('x-auth-token', token)
                .attach('document', file);
        }

        beforeEach(async () =&gt; {
            user = new User({
                username: 'user',
                password: '1234'
            });
            user = await user.save();

            user.leftDiskSpace(function(err, size) { console.log(size); });

            token = user.generateAuthToken();

            file = path.join(process.cwd(), 'tests', 'integration', 'files', 'test.json');
        });

        .
        .
        .

        it('should return 400 if an error occurs during calculation of authorized user\'s left disk space', async () =&gt; {
            jest.mock('../../../routes/documents');
            let documentsRouter = require('../../../routes/documents');
            
            let mockReq = {};
            let mockRes = {}

            let mockPostRouter = jest.fn();
            mockPostRouter.mockImplementation((path, callback) =&gt; {
                if('path' === '/mine') callback(mockReq, mockRes);
            });

            documentsRouter.post = mockPostRouter;
            
            let error = new Error('Something went wrong...');

            const res = await exec();

            console.log(res.body);

            expect(res.status).toBe(400);
            expect(res.body.error).toHaveProperty('message', 'Something went wrong...');
        });
        .
        .
        .
    });
});
</code></pre>
<p>What I want to do is, I need to be able call a mock <code>user.leftDiskSpace(function(err, leftSpace))</code> user model method inside <code>router.post('/mine', ...)</code> route handler. I need to be able to get inside the if and else brances by callback function of <code>user.leftDiskSpace()</code>. How can I do that?</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/67562696/jest-integration-test-express-rest-api-with-mongoose,"['express', 'testing', 'mongoose', 'jestjs', 'supertest']",143,False,1,0
How to do integration testing with spring and junit by scanning classpath instead of manually specifying classes to autowire?,"<p>I'm trying to do some sort of integration testing (not really full testing, only it's not  really unit testing either) on a service :</p>
<pre><code>package foo;


@Component
public class FooService {}
</code></pre>
<p>And the corresponding test :</p>
<pre><code>package foo;

@SpringBootTest
public FooTest {
   @Autowired FooService fooService;
}
</code></pre>
<p>Only when I try to test it says</p>
<pre><code>No qualifying bean of type 'foo.FooService' available
</code></pre>
<p>I could add the class to <code>@SpringBootTest</code> like this :</p>
<pre><code>@SpringBootTest(classes = {FooService.class})
</code></pre>
<p>But I don't want to manually select the classes I want to test. My application is much larger than the MWE, and I want to test without having to specify each class I am testing and their respective dependencies.</p>
<p>Is there anyway to tell spring to scan and autowire dependencies like it would outside of tests ?</p>
",https://stackoverflow.com/questions/69741747/how-to-do-integration-testing-with-spring-and-junit-by-scanning-classpath-instea,"['java', 'spring', 'testing']",98,True,0,1
Flutter Integration test: I can&#39;t target some of my widgets - Getter not found,"<p>I am learning about integration testing in flutter and I'm running into a problem.</p>
<p>My app contains a sign-in button widget and my test starts with pumping it.</p>
<p>However, I can't seem to target it.</p>
<p>Every attempt results in the following error:</p>
<pre><code>integration_test/doctor_integration_test.dart:21:24: Error: Getter not found: 'SignInPage'.
    expect(find.byType(SignInPage), findsOneWidget);
                       ^^^^^^^^^^
                                                                        
                                                                        
FAILURE: Build failed with an exception.
</code></pre>
<p>The SignInPage is called within:</p>
<pre><code>MaterialApp _buildMaterialApp(BuildContext context) {
    return MaterialApp(
      title: 'Skinopathy: Doctor',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      routes: {
        '/': (context) {
          return BlocListener&lt;AppBloc, AppState&gt;(
            listener: (context, state) {
              if (state is AppAuthenticated) {
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(
                    builder: (_) =&gt; WelcomePage(),
                  ),
                );
              } else if (state is AppUnauthenticated) {
                Navigator.pushReplacementNamed(context, '/sign_in');
              } else if (state is AppOutdated) {
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(
                    builder: (_) =&gt; OutdatedVersionPage(),
                  ),
                );
              }
            },
            child: Center(
              child: SplashPage(),
            ),
          );
        },
        '/sign_in': (context) {
          return SignInPage();
        },
</code></pre>
<p>My presumption is that the integration takes place before the SignInPage is loaded.</p>
<p>_buildMaterialApp is also a child of Widget _buildRootLevelWidgets(BuildContext context)</p>
<p>How do I properly target SignInPage for testing?</p>
<p>Is there anything else I'm doing wrong?</p>
<p>Please note: I did NOT build this app; I'm just here to test it.</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/66839874/flutter-integration-test-i-cant-target-some-of-my-widgets-getter-not-found,"['flutter', 'dart', 'testing', 'integration-testing']",413,True,0,1
Getting test coverage of GraphQL resolve function,"<p>I'm using <code>mocha</code> <code>chai</code> and <code>supertest</code> to test a new graphql endpoint set up on our Node/Express server.</p>
<p>I have all the tests running and passing accordingly but when I run the following script:</p>
<pre><code>    &quot;test-coverage&quot;: &quot;nyc mocha tests/ --recursive&quot;,

</code></pre>
<p>it is not counting the tests for <code>users</code> resolve function in the code coverage.</p>
<p>My graphql query endpoint looks as shown below:</p>
<pre><code>const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: () =&gt; ({
        users: {
            type: new GraphQLList(UserType),
            args: {
                searchByName: { type: GraphQLString },
                queryNearbyUsers: { type: GraphQLBoolean },
                skip: { type: GraphQLInt },
                limit: { type: GraphQLInt }
            },
            async resolve(parent, args, req) {
                const { searchByName, queryNearbyUsers, skip = 0, limit = 20 } = args
                
                // No search criteria was specified so just return an error
                if(!searchByName &amp;&amp; !queryNearbyUsers) 
                    throw new Error('NO_SEARCH_CRITERIA_SPECIFIED')

                ...
            }
        },
    ...
})

</code></pre>
<p>An example of one of my tests:</p>
<pre><code>    it('should throw an error (NO_SEARCH_CRITERIA_SPECIFIED) when no params supplied', function(done) {
        request.post('spikeql')
        .set({ Authorization: `Bearer ${token}`})
        .send({ query: '{ users { _id firstName lastName displayName rpr distanceAway avatar { styles { thumb_square }}}}'})
        .expect(200) // TODO: Setup GraphQL to match approproate HTTP res codes
        .end((err, res) =&gt; {
            if(err) return done(err)
            let errors = res.body.errors
            expect(errors).to.be.an('array')

            // Check to make sure error was sent properly
            expect(errors[0]).to.have.property('message', 'NO_SEARCH_CRITERIA_SPECIFIED')
            expect(errors[0].message).to.be.a('string')
            done()
        })
    })
</code></pre>
<p>I perform 3 other tests with different inputs for the <code>GET_USERS</code> query.  All of them pass.  It just doesn't get tracked in coverage report.</p>
<p>New to graphql and unit/integration testing so any help is appreciated.  Can supply additional info if needed.</p>
",https://stackoverflow.com/questions/65650330/getting-test-coverage-of-graphql-resolve-function,"['graphql', 'mocha.js', 'integration-testing', 'graphql-js', 'supertest']",563,False,0,0
Integration Test for a static method in Java,"<p>I have the following method and I am trying to test it in my Integration Test:</p>
<pre><code>public List&lt;CountryCodeDTO&gt; getAllCountryCodes() {
        List&lt;CountryCodeDTO&gt; countryCodes = new ArrayList&lt;&gt;();

        for (String country : Locale.getISOCountries()) {
            Locale locale = new Locale(&quot;&quot;, country);
            CountryCodeDTO countryCodeDTO = new CountryCodeDTO();
            countryCodeDTO.setCountryCode(country);
            countryCodeDTO.setName(locale.getDisplayCountry());
            countryCodes.add(countryCodeDTO);
        }
        return countryCodes;
    }
</code></pre>
<p>As a beginner for Integration Testing, I have really no idea about how I should test it. On the other hand, I have found something e.g. PowerMock, but I think it is for Unit Test rather than Integration Test. So, how should I test this method?</p>
<p>Please note that it seems to be a unit test, testing only this method, but as as result, we also test the other methods e.g. save, find, delete, etc. in Integration Tests. Any help would be appreciated.</p>
",https://stackoverflow.com/questions/70103933/integration-test-for-a-static-method-in-java,"['java', 'spring', 'testing', 'integration-testing', 'powermockito']",117,False,0,0
Test containers not deleted from docker after JUnit 5 all class tests completed,"<p>I am using the test container for integration testing and end-to-end testing of the micronaut application.</p>
<p>Here is the configuration for the test container</p>
<pre><code>@Testcontainers
public abstract class TestContainerFixture {
    protected static final GenericContainer mongoDBContainer;
    protected static final Map&lt;String, Object&gt; properties;

    static {
        mongoDBContainer = new GenericContainer(DockerImageName.parse(&quot;mongo:4.0.10&quot;))
                .withExposedPorts(27017)
                .withReuse(true);
        mongoDBContainer.start();
        properties = Map.of(&quot;mongodb.uri&quot;,
                String.format(&quot;mongodb://%s:%s&quot;, mongoDBContainer.getContainerIpAddress(), mongoDBContainer.getMappedPort(27017)));
    }

    protected ApplicationContext applicationContext;
}
</code></pre>
<p>A class extending the test container</p>
<pre><code>public class DiscountUpdateListenerTest extends TestContainerFixture {
}
</code></pre>
<p>Since I am using <code>.withReuse(true);</code> to reuse the test container for all the other test class. If I disable the <code>.withReuse(false)</code> on each class when the integration test is running, the container is created which takes the longer time for the test to execute.</p>
<p>So, to reuse the same container I have used the feature <code>.withReuse(true)</code>. Since the container remain there for longer period of time. So I want to remove the container on each 1-2 hours</p>
",https://stackoverflow.com/questions/68907354/test-containers-not-deleted-from-docker-after-junit-5-all-class-tests-completed,"['java', 'junit', 'micronaut', 'testcontainers', 'testcontainers-junit5']",2230,True,1,1
Component testing classes that use OptaPlanner,"<p>I have a component that, amongst other things, makes use of OptaPlanner. We use junit for component/integration testing and I am having trouble with bean creation when running tests.</p>
<p>When running my test I get the following error...</p>
<pre><code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.optaplanner.core.api.solver.SolverManager&lt;com.company.uk.product.aepe.service.optaplanner.EngagementSolution, java.util.UUID&gt;' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1714)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1270)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1224)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
</code></pre>
<p>I use optaplanner-spring-boot-starter which normally created a SolveManager bean which is @Autowired'd into my classes, but not when run as a test.</p>
<p>My pom dependencies (sanitized for security reasons)....</p>
<pre><code>&lt;dependencies&gt;
  &lt;!-- Actuator Dependencies START --&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;de.codecentric&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-admin-starter-client&lt;/artifactId&gt;
  &lt;/dependency&gt;
  &lt;!-- Actuator Dependencies END --&gt;

  &lt;!-- Spring --&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter&lt;/artifactId&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.springframework.kafka&lt;/groupId&gt;
    &lt;artifactId&gt;spring-kafka&lt;/artifactId&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.optaplanner&lt;/groupId&gt;
    &lt;artifactId&gt;optaplanner-spring-boot-starter&lt;/artifactId&gt;
  &lt;/dependency&gt;

  &lt;dependency&gt;
    &lt;groupId&gt;org.apache.camel&lt;/groupId&gt;
    &lt;artifactId&gt;camel-spring-boot-starter&lt;/artifactId&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.apache.camel&lt;/groupId&gt;
    &lt;artifactId&gt;camel-kafka&lt;/artifactId&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.apache.camel&lt;/groupId&gt;
    &lt;artifactId&gt;camel-jackson&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;scope&gt;provided&lt;/scope&gt;
  &lt;/dependency&gt;

  ...

  &lt;!-- Test Depemdencies --&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
    &lt;artifactId&gt;junit-jupiter&lt;/artifactId&gt;
    &lt;scope&gt;test&lt;/scope&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.mockito&lt;/groupId&gt;
    &lt;artifactId&gt;mockito-core&lt;/artifactId&gt;
    &lt;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;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-test&lt;/artifactId&gt;
    &lt;scope&gt;test&lt;/scope&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;com.github.database-rider&lt;/groupId&gt;
    &lt;artifactId&gt;rider-junit5&lt;/artifactId&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;scope&gt;test&lt;/scope&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.optaplanner&lt;/groupId&gt;
    &lt;artifactId&gt;optaplanner-test&lt;/artifactId&gt;
    &lt;scope&gt;test&lt;/scope&gt;
  &lt;/dependency&gt;

  &lt;!-- Required by Intellij to run Junit 5 tests --&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.junit.platform&lt;/groupId&gt;
    &lt;artifactId&gt;junit-platform-launcher&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.junit.vintage&lt;/groupId&gt;
    &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
    &lt;scope&gt;test&lt;/scope&gt;
  &lt;/dependency&gt;
&lt;/dependencies&gt;
</code></pre>
<p>This <a href=""https://stackoverflow.com/questions/61371336/optaplanner-solvermanager-bean-not-being-found-in-spring-application"">thread</a> suggests manually creating the SolverManager bean in a configuration class but also warn off doing this...</p>
<p>What is the 'best' way of ensuring thsi ben is available in my integration tests?</p>
",https://stackoverflow.com/questions/68438281/component-testing-classes-that-use-optaplanner,"['java', 'spring-boot', 'optaplanner']",102,False,1,1
Spring Boot scans Test configuration classes on start up,"<p>I have a Spring Boot App with the main class as below.</p>
<pre><code>@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer 
</code></pre>
<p>The project structure is</p>
<pre><code>App/
    src/main/java
    src/test/java
</code></pre>
<p>In the test package , I have a configuration class used for Integration testing and the class is marked as @TestConfiguration. I am noticing that this class is getting picked up on the server startup. I am using profile as dev on start up. Any idea why the test configuration classes are getting loaded on startup of the application. I need these classes to be scanned only during test phase.</p>
<p>This works well when i run java -jar command from command line, but fails during start up from STS eclipse.</p>
",https://stackoverflow.com/questions/70207235/spring-boot-scans-test-configuration-classes-on-start-up,"['spring', 'eclipse', 'spring-boot']",141,False,1,0
Flutter dependency error - Version Solving failed,"<p>I'm trying out integration testing for my app. When I am trying to add the integration_test dependency to my pubspec.yaml I'm getting this error:</p>
<blockquote>
<p>Because no versions of uuid match &gt;2.2.2 &lt;3.0.0 and uuid 2.2.2 depends on crypto ^2.0.0, uuid ^2.2.2 requires crypto ^2.0.0.
And because every version of integration_test depends on flutter_driver any from sdk which depends on crypto 3.0.1, uuid ^2.2.2 is incompatible with integration_test.
So, because flutter_firebase_login depends on both integration_test ^1.0.2+3 and uuid ^2.2.2, version solving failed.
pub get failed (1; So, because flutter_firebase_login depends on both integration_test ^1.0.2+3 and uuid ^2.2.2, version solving failed.)</p>
</blockquote>
<p>What should I do next to resolve this error?</p>
",https://stackoverflow.com/questions/68465013/flutter-dependency-error-version-solving-failed,"['android', 'firebase', 'flutter', 'flutter-dependencies', 'flutter-integration-test']",1853,True,1,1
Hot reload for Flutter integration test?,"<p>I have setted up Flutter Integration Testing on my project as defined here: <a href=""https://flutter.dev/docs/testing/integration-tests"" rel=""noreferrer"">https://flutter.dev/docs/testing/integration-tests</a></p>
<p>I used the following devDepencendies:</p>
<pre><code>integration_test: ^1.0.0
flutter_test:
  sdk: flutter
flutter_driver:
  sdk: flutter
</code></pre>
<p>The test driver is just a C&amp;P from project page:</p>
<pre><code>import 'package:integration_test/integration_test_driver.dart';

Future&lt;void&gt; main() =&gt; integrationDriver();
</code></pre>
<p>The final test:</p>
<pre><code>void main() {
    IntegrationTestWidgetsFlutterBinding.ensureInitialized();

    testWidgets('CPCSA-TC-016: Vehicle Card with no alert',
    (WidgetTester tester) async {
        app.main();
        // Execute test code. 
    });
}
</code></pre>
<p>Finally I run my tests with</p>
<p><code>flutter drive  --driver=test_driver/integration_test.dart --target=integration_test/test.dart </code></p>
<p>Which is basically fine, but it compiles at every execution and this is very time consuming. Is there a chance that I can run the integration test and have the same hot reload feature as I would have for regular development? How to achieve this?</p>
<p>Or is there any other workaround? I am thinking about writing the test code as unit/widget test first and just port it into integration tests once the execution is correct.</p>
",https://stackoverflow.com/questions/66642144/hot-reload-for-flutter-integration-test,"['flutter', 'integration-testing', 'hot-reload', 'flutterdriver', 'flutter-integration-test']",1560,True,5,1
Creating a non-ORACLE_MAINTAINED user in ORACLE XE 18 via JDBC,"<p>I want to create a user from JDBC (if possible) in an ORACLE Express database. That user can't have the <code>ORACLE_MAINTAINED</code> flag in the <code>DBA_USERS</code> view.</p>
<p>Trying <code>CREATE USER newuser IDENTIFIED BY xxx</code>, but it throws a <code>ORA-65096: invalid common user or role name</code>. To avoid it, I had to set the flag <code>ALTER SESSION SET &quot;_ORACLE_SCRIPT&quot;=TRUE</code>, as other posts recommend. But that way, it's marked as <code>ORACLE_MAINTAINED</code>.</p>
<p>I'm connecting to the <code>xe</code> default database.</p>
<h4>Context:</h4>
<p>I'm working with the Oracle Docker image; it's for integration testing purposes. The metadata queries the app uses exclude <code>ORACLE_MAINTAINED='Y'</code> users/tables, and I'm not able to list them (not working with data, just metadata). I could remove the WHERE from the queries, but I would prefer to avoid it, and keep the app queries untouched.</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/69349681/creating-a-non-oracle-maintained-user-in-oracle-xe-18-via-jdbc,"['sql', 'oracle', 'docker', 'oracle-xe', 'oracle18c']",200,False,0,0
Server side mocking of node using testcafe,"<p>my use case is to explore how could a server-side requests be mocked. I am successful in mocking client side request using requesthooks but with server side testcafe is not able to intercept the request.
Frontend is built using next.js, and at intial page load, getinitalprops prepares the page by using fetch (get request) which happens at server side(node) not browser, and testcafe is not able to intercept.</p>
<p>I want to introduce testcafe in my team for frontend dev &amp; their requirement is to resolve their pain of mocking server side requests before they start using testcafe for integration testing. Please suggest if this is possible with testcafe.</p>
",https://stackoverflow.com/questions/67495808/server-side-mocking-of-node-using-testcafe,"['javascript', 'next.js', 'ui-automation', 'e2e-testing', 'testcafe']",218,True,0,1
Trying to understand mocking google sign-in for Flutter,"<p>What I'm trying to do is test our sign-in widget for widget tests and later, integration testing and E2E testing.</p>
<p>So I have the following two mocks.  They both seem to require each other to work.</p>
<p>google_sign_in_mocks 0.2.1
<a href=""https://pub.dev/packages/google_sign_in_mocks"" rel=""nofollow noreferrer"">https://pub.dev/packages/google_sign_in_mocks</a></p>
<p>firebase_auth_mocks 0.8.1
<a href=""https://pub.dev/packages/firebase_auth_mocks"" rel=""nofollow noreferrer"">https://pub.dev/packages/firebase_auth_mocks</a></p>
<p>What I don't understand is <em>how</em> to use them.  I'm going through the docs and examples, and I don't get it.</p>
<p>For instance, I am looking at the <strong>google_sign_in_mocks</strong> example and I don't understand where <strong>MockGoogleSignIn</strong>, <strong>googleSignIn</strong> and <strong>.authentication</strong> comes from.</p>
<p>I'm reading additional docs like <a href=""https://firebase.flutter.dev/docs/auth/usage"" rel=""nofollow noreferrer"">https://firebase.flutter.dev/docs/auth/usage</a>, but it feels like things are spiraling out of control.</p>
<p>Can someone help explain some of this for me?</p>
",https://stackoverflow.com/questions/69214472/trying-to-understand-mocking-google-sign-in-for-flutter,"['firebase', 'flutter', 'testing', 'mocking', 'google-signin']",379,False,3,0
How to do integration test with chai for internal and nock for external api call,"<p>I have an app for <a href=""https://api.slack.com/interactivity/handling"" rel=""nofollow noreferrer"">Slack Interactivity Handling</a>, what I'd like to do is just to receive webhook from the slack button and update the message via Slack API.</p>
<p>I use express on my server, and core <code>https</code> module for my API call, here's my <code>server.js</code></p>
<pre class=""lang-js prettyprint-override""><code>const https = require('https')
const express = require('express')
const app = express()

app.use(express.json())
app.post('/slack/actions', (req, res) =&gt; {
  const payload = JSON.parse(JSON.stringify(req.body.payload))
  const { status, message } = process(payload)

  res.status(status).json({ 'message': message })
})

function process(payload) =&gt; {
  const action = payload.actions.value
  if (action == 'ack') {
    return ack(payload)
  } else {
    return { status: 400, message: 'Action invalid' }
  }
}

function ack(payload) =&gt; {
  const userId = payload.user.id
  const updatedMessage = {
    type: 'section',
    text: { type: 'mrkdwn', text: `Approved by &lt;@${userId}&gt;` }
  }

  const token = payload.token
  const channel = payload.container.channel_id
  const messageId = payload.container.message_ts
  const message = payload.message.blocks
  message.splice(-1, 1, updatedMessage)

  api('https://slack.com/api/chat.update', 'POST', {
    token: token,
    channel: channel,
    ts: messageId,
    blocks: message
  })

  return { status: 200, message: 'Package received' }
}

function api(){
  const opts = {
    uri: url,
    method: method,
    headers: { 'Content-type': 'application/json' },
    json: data
  }
  const req = https.request(opts, res =&gt; {
    console.log(`statusCode: ${res.statusCode}`)
    console.log(res.body)
  })
  req.on('error', error =&gt; {
    console.error(`Error: ${error}`)
  })
  req.end()
}
</code></pre>
<p>I don't have a problem with the App, but I'd like to do integration testing to test success &amp; failed slack API calls.</p>
<p>Here's my <code>server.spec.js</code></p>
<pre class=""lang-js prettyprint-override""><code>const app = require('../server')
const chai = require('chai')
const chaiHttp = require('chai-http')
const nock = require('nock')

chai.use(chaiHttp)
chai.should()
describe('Slack App', () =&gt; {
  describe(&quot;POST /slack/actions&quot;, () =&gt; {
    it(&quot;should update message on ack&quot;, (done) =&gt; {
      const blocks = [
        { &quot;type&quot;: &quot;section&quot;, &quot;text&quot;: { &quot;type&quot;: &quot;mrkdwn&quot;, &quot;text&quot;: &quot;Title&quot;, } },
        { &quot;type&quot;: &quot;section&quot;, &quot;text&quot;: { &quot;type&quot;: &quot;mrkdwn&quot;, &quot;text&quot;: &quot;Info&quot; } },
        { &quot;type&quot;: &quot;actions&quot;, &quot;elements&quot;: [{
          &quot;type&quot;: &quot;button&quot;,
          &quot;text&quot;: { &quot;type&quot;: &quot;plain_text&quot;, &quot;text&quot;: &quot;Approve&quot;, },
          &quot;value&quot;: &quot;ack&quot;
        }]
      }]
      const data = {
        payload: {
          token: 'token',
          container: { channel_id: 'CH4NN3L', message_ts: '1626196341.000900' },
          message: { blocks: blocks },
          actions: { value: 'ack' },
          user: { id: 'US3R1D' }
        }
      }
      const expectedBlocks = [
        { &quot;type&quot;: &quot;section&quot;, &quot;text&quot;: { &quot;type&quot;: &quot;mrkdwn&quot;, &quot;text&quot;: &quot;Title&quot;, } },
        { &quot;type&quot;: &quot;section&quot;, &quot;text&quot;: { &quot;type&quot;: &quot;mrkdwn&quot;, &quot;text&quot;: &quot;Info&quot; } },
        { type: 'section', text: { type: 'mrkdwn', text: 'Approved by &lt;@US3R1D&gt;' } }
      ]
      const expectedParams = { token: 'token', channel: 'CH4NN3L', ts: '1626196341.000900', blocks: expectedBlocks }
      const expectedNock = nock('https://slack.com/api',
        { reqheaders: { 'Content-type': 'application/json' } }
      )
        .post('/chat.update', expectedParams)
        .reply(200, {})

      chai.request(app)
          .post('/slack/actions')
          .set('content-type', 'application/json')
          .send(data)
          .end((err, res) =&gt; {
            expectedNock.isDone().should.be.true
            res.should.have.status(200)
            res.body.should.be.a('object')
            res.body.should.include({ message: 'Package received' })
            done()
          })
    })
  })
})
</code></pre>
<p>It seems the test still calls the real API, because there's an error log
<code>Error: Error: connect ECONNREFUSED 127.0.0.1:443</code></p>
<p>Also, the nock interceptor doesn't seem to intercept the <code>https.request</code> call as the test failed with <code>Uncaught AssertionError: expected false to be true</code></p>
<p>Is <code>nock</code> the correct lib to test this? Also is this the correct way to test this?</p>
",https://stackoverflow.com/questions/68373359/how-to-do-integration-test-with-chai-for-internal-and-nock-for-external-api-call,"['node.js', 'mocha.js', 'integration-testing', 'chai', 'nock']",195,False,1,0
"code: &quot;auth/argument-error&quot;, message: &quot;reCAPTCHA container is either not found or already contains inner elements!&quot;, a: null Angular","<p>I am trying to do sms/phone validation of my angular website through fire base until now i have tried the code below</p>
<pre><code>firebase.auth().settings.appVerificationDisabledForTesting = true;

var phoneNumber = &quot;+16505554567&quot;;
var testVerificationCode = &quot;123456&quot;;

// This will render a fake reCAPTCHA as appVerificationDisabledForTesting is true.
// This will resolve after rendering without app verification.
var appVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
// signInWithPhoneNumber will call appVerifier.verify() which will resolve with a fake
// reCAPTCHA response.
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
    .then(function (confirmationResult) {
      // confirmationResult can resolve with the fictional testVerificationCode above.
      return confirmationResult.confirm(testVerificationCode)
    }).catch(func`enter code here`tion (error) {
      // Error; SMS not sent
      // ...
    });
</code></pre>
<p>The above code is mentioned in firebase documentation
<a href=""https://firebase.google.com/docs/auth/web/phone-auth#integration-testing"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/auth/web/phone-auth#integration-testing</a>
I have setup the config file for firebase and initialized firebase app and my code in template file is</p>
<pre><code>&lt;div id=&quot;recaptcha-container&quot;&gt;&lt;/div&gt;
</code></pre>
<p>i want to test my sms service
My firebase version is &quot;firebase&quot;: &quot;^8.8.1&quot;,
when i run the code above i get this error</p>
<blockquote>
<p>t {code: &quot;auth/argument-error&quot;, message: &quot;reCAPTCHA container is
either not found or already contains inner elements!&quot;, a: null}</p>
</blockquote>
<p>I want to test my verification without CAPTCHA
All help is appreciated</p>
",https://stackoverflow.com/questions/68624742/code-auth-argument-error-message-recaptcha-container-is-either-not-found-o,"['angularjs', 'firebase']",344,False,1,0
How to use datasource from testcontainer in JEE entity manager,"<p>In a project we are not using spring (wher exist gazillions of information about testcontainers) but a rather old jboss version 6.4.0.EAP with hibernate, which we cannot change. The testing framework is junit4 and to some extent arquillian.</p>
<p>I try to make integration testing better and want to use testcontainers at least for the database test setup. I know how to start a testcontainer (in that case mysqlcontainer) and how to run the existing liquibase scripts.</p>
<p>What I am stuck with is:
How to use the Datasource, which I can obtain here from my started container</p>
<pre><code>public DataSource getDataSource(MySQLContainer&lt;?&gt; mySQLContainer) {
    MysqlDataSource ds = new MysqlDataSource();
    ds.setUser(mySQLContainer.getUsername());
    ds.setPassword(mySQLContainer.getPassword());
    ds.setURL(mySQLContainer.getJdbcUrl());
    return ds;
}
</code></pre>
<p>to create an entity manager which then should be injected into the existing Dao?
The Dao in the application is defined like</p>
<pre><code>@ApplicationScoped
public class MyDao {

    @Inject
    private EntityManager entityManager;

    protected EntityManager getEM() {
        return entityManager;
    }
}
</code></pre>
",https://stackoverflow.com/questions/66274150/how-to-use-datasource-from-testcontainer-in-jee-entity-manager,"['java', 'jboss', 'java-ee-6', 'entitymanager', 'testcontainers']",778,False,0,1
"MockMvc perform, array response assertion fail","<p>I am implementing integration tests for Spring Boot. One of my endpoint gives back all the users, even the deleted ones. Here deleted means the deleted boolean attribute is set to true on AppUser Entity (~soft delete).
The endpoint works perfectly, I have manual tested with Postman (you can see below the response). The code:</p>
<pre><code>    @Test
    void testGetAllAppUsers_whenAuthorizedOnlyActiveFalse_gotDeletedUser() throws Exception {
        String token = jwtProvider.generateToken(TestUtils.ACCOUNT_MANAGER_USERNAME);
        String url = &quot;/api/account/user&quot;;
        mvc.perform(get(url)
                    .header(&quot;Authorization&quot;, token)
                    .param(&quot;only-active&quot;, &quot;false&quot;))
                .andExpect(status().isOk())
                .andExpect(jsonPath(&quot;$[*].deleted&quot;).value(Matchers.arrayContaining(true)));
    }
</code></pre>
<p>the response:</p>
<pre><code>...
             Body = [{&quot;id&quot;:7,&quot;username&quot;:&quot;ablabadmin@account.com&quot;,&quot;fullName&quot;:&quot;Alpha Beta Lab Admin&quot;,&quot;deleted&quot;:false,&quot;labsAsUser&quot;:[],&quot;labsAsAdmin&quot;:[],&quot;roles&quot;:[],&quot;managedLabs&quot;:[]},{&quot;id&quot;:11,&quot;username&quot;:&quot;ablabdeleteduser@account.com&quot;,&quot;fullName&quot;:&quot;Alpha Beta Lab Deleted User&quot;,&quot;deleted&quot;:true,&quot;labsAsUser&quot;:[],&quot;labsAsAdmin&quot;:[],&quot;roles&quot;:[],&quot;managedLabs&quot;:[]},{&quot;id&quot;:4,&quot;username&quot;:&quot;ablabman@account.com&quot;,&quot;fullName&quot;:&quot;Alpha Beta Lab Manager&quot;,&quot;deleted&quot;:false,&quot;labsAsUser&quot;:[],&quot;labsAsAdmin&quot;:[],&quot;roles&quot;:[],&quot;managedLabs&quot;:[{&quot;id&quot;:1,&quot;key&quot;:&quot;alab&quot;,&quot;name&quot;:&quot;Alpha Lab&quot;,&quot;deleted&quot;:false,&quot;createdAt&quot;:&quot;2021-06-09&quot;,&quot;updatedAt&quot;:null,&quot;labManagerUsernames&quot;:[&quot;alabman@account.com&quot;,&quot;ablabman@account.com&quot;]},{&quot;id&quot;:2,&quot;key&quot;:&quot;blab&quot;,&quot;name&quot;:&quot;Beta Lab&quot;,&quot;deleted&quot;:false,&quot;createdAt&quot;:&quot;2021-06-09&quot;,&quot;updatedAt&quot;:null,&quot;labManagerUsernames&quot;:[&quot;blabman@account.com&quot;,&quot;ablabman@account.com&quot;]}]},{&quot;id&quot;:10,&quot;username&quot;:&quot;ablabuser@account.com&quot;,&quot;fullName&quot;:&quot;Alpha Beta Lab User&quot;,&quot;deleted&quot;:false,&quot;labsAsUser&quot;:[],&quot;labsAsAdmin&quot;:[],&quot;roles&quot;:[],&quot;managedLabs&quot;:[]},{&quot;id&quot;:5,&quot;username&quot;:&quot;alabadmin@account.com&quot;,&quot;fullName&quot;:&quot;Alpha Lab Admin&quot;,&quot;deleted&quot;:false,&quot;labsAsUser&quot;:[],&quot;labsAsAdmin&quot;:[],&quot;roles&quot;:[],&quot;managedLabs&quot;:[]},{&quot;id&quot;:2,&quot;username&quot;:&quot;alabman@account.com&quot;,&quot;fullName&quot;:&quot;Alpha Lab Manager&quot;,&quot;deleted&quot;:false,&quot;labsAsUser&quot;:[],&quot;labsAsAdmin&quot;:[],&quot;roles&quot;:[],&quot;managedLabs&quot;:[{&quot;id&quot;:1,&quot;key&quot;:&quot;alab&quot;,&quot;name&quot;:&quot;Alpha Lab&quot;,&quot;deleted&quot;:false,&quot;createdAt&quot;:&quot;2021-06-09&quot;,&quot;updatedAt&quot;:null,&quot;labManagerUsernames&quot;:[&quot;alabman@account.com&quot;,&quot;ablabman@account.com&quot;]}]},{&quot;id&quot;:8,&quot;username&quot;:&quot;alabuser@account.com&quot;,&quot;fullName&quot;:&quot;Alpha Lab User&quot;,&quot;deleted&quot;:false,&quot;labsAsUser&quot;:[],&quot;labsAsAdmin&quot;:[],&quot;roles&quot;:[],&quot;managedLabs&quot;:[]},{&quot;id&quot;:1,&quot;username&quot;:&quot;aman@account.com&quot;,&quot;fullName&quot;:&quot;Account Manager&quot;,&quot;deleted&quot;:false,&quot;labsAsUser&quot;:[],&quot;labsAsAdmin&quot;:[],&quot;roles&quot;:[{&quot;id&quot;:1,&quot;role&quot;:&quot;ACCOUNT_MANAGER&quot;}],&quot;managedLabs&quot;:[]},{&quot;id&quot;:6,&quot;username&quot;:&quot;blabadmin@account.com&quot;,&quot;fullName&quot;:&quot;Beta Lab Admin&quot;,&quot;deleted&quot;:false,&quot;labsAsUser&quot;:[],&quot;labsAsAdmin&quot;:[],&quot;roles&quot;:[],&quot;managedLabs&quot;:[]},{&quot;id&quot;:3,&quot;username&quot;:&quot;blabman@account.com&quot;,&quot;fullName&quot;:&quot;Beta Lab Manager&quot;,&quot;deleted&quot;:false,&quot;labsAsUser&quot;:[],&quot;labsAsAdmin&quot;:[],&quot;roles&quot;:[],&quot;managedLabs&quot;:[{&quot;id&quot;:2,&quot;key&quot;:&quot;blab&quot;,&quot;name&quot;:&quot;Beta Lab&quot;,&quot;deleted&quot;:false,&quot;createdAt&quot;:&quot;2021-06-09&quot;,&quot;updatedAt&quot;:null,&quot;labManagerUsernames&quot;:[&quot;blabman@account.com&quot;,&quot;ablabman@account.com&quot;]}]},{&quot;id&quot;:9,&quot;username&quot;:&quot;blabuser@account.com&quot;,&quot;fullName&quot;:&quot;Beta Lab User&quot;,&quot;deleted&quot;:false,&quot;labsAsUser&quot;:[],&quot;labsAsAdmin&quot;:[],&quot;roles&quot;:[],&quot;managedLabs&quot;:[]}]
    Forwarded URL = null
   Redirected URL = null
          Cookies = []


java.lang.AssertionError: JSON path &quot;$[*].deleted&quot;
Expected: [&lt;true&gt;] 
     but: was a net.minidev.json.JSONArray (&lt;[false,true,false,false,false,false,false,false,false,false,false]&gt;)
Expected :[&lt;true&gt;] 
Actual   :a net.minidev.json.JSONArray (&lt;[false,true,false,false,false,false,false,false,false,false,false]&gt;)
...
</code></pre>
<p>I have tried out many other arguments: <code>&quot;true&quot;</code>, <code>false</code> I have tried out <code>contains</code> method, and I ave tried out with <code>&quot;$[*].username&quot;</code> regex with an existing username, but every time I got AssertionError.
Can you please help me? There is definitely something I am missing. Also any advice is welcomed, since I am relatively new in Spring integration testing. Thanks in advance!</p>
",https://stackoverflow.com/questions/67909773/mockmvc-perform-array-response-assertion-fail,"['spring-boot', 'integration-testing', 'spring-boot-test', 'hamcrest', 'mockmvc']",288,False,0,1
How to access dockerized app under test in gitlab CI,"<p>I have <code>testng</code> project with selenium for integration testing of frontend app in <code>vuejs</code> and <code>springboot</code> backend. So in order to run tests I need first to bring up all dependent projects:</p>
<ul>
<li>springboot and mongodb</li>
<li>vuejs frrontend app</li>
</ul>
<p>Each project is in its own repo.
So I have created docker images of springboot and frontend app and will put it up in <code>gitlab container registry</code>.
Then in the testeng project plan to use docker-compose in <code>.gitlab-ci.yml</code>. Here is <code>docker-compose.yml</code> for testng project:</p>
<pre><code>version: '3.7'
services:
  frontendapp:
    image: demo.app-frontend-selenium
    container_name: frontend-app-selenium
    depends_on:
      - demoapi
    ports:
      - 8080:80
  demoapi:
    image: demo.app-backend-selenium
    container_name: demo-api-selenium
    depends_on:
      - mongodb
    environment:
      - SPRING_PROFILES_ACTIVE=prod
      - SCOUNT_API_ENDPOINTS_WEB_CORS_OPTIONS_ALLOWEDORIGINS=*
      - SPRING_DATA_MONGODB_HOST=mongodb
      - SPRING_DATA_MONGODB_DATABASE=demo-api-selenium
      - KEYCLOAK_AUTH-SERVER-URL=https://my-keycloak-url/auth
    ports:
      - 8082:80
  mongodb:
    image: mongo:4-bionic
    container_name: mongodb-selenium
    environment:
      MONGO_INITDB_DATABASE: demo-api-selenium
    ports:
      - 27017:27017
    volumes:
      - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
</code></pre>
<p>After running docker-compose in gitlab-ci.yml what will be url of frontend app in order to execute tests?
When I do it locally I am using following urls for testing:</p>
<ul>
<li>frontend app: http://localhost:8080</li>
<li>api: http://localhost:8082</li>
</ul>
<p>But in case when running on gitlab ci what will be url to access frontend and api?</p>
",https://stackoverflow.com/questions/69942553/how-to-access-dockerized-app-under-test-in-gitlab-ci,"['docker-compose', 'gitlab', 'devops', 'gitlab-ci']",403,True,8,1
Missing Webpack Loader Running Cypress test with React,"<p>I'm trying to use cypress for integration testing on a React project. However, I'm getting the following error:</p>
<blockquote>
<p>Error: Webpack Compilation Error
./node_modules/react-pro-sidebar/dist/css/styles.css 1:0
Module parse failed: Unexpected character '@' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See <a href=""https://webpack.js.org/concepts#loaders"" rel=""nofollow noreferrer"">https://webpack.js.org/concepts#loaders</a></p>
</blockquote>
<p>As the error suggests, I'm using the react-pro-sidebar package.</p>
<p>The first lines of the .css file of the package that is causing the error,</p>
<pre><code>&gt; @keyframes swing {
|   0%,
|   30%,
</code></pre>
<p>I've tried installing the css and scss webpack loader but it still failed.</p>
<p>Here's my webpack.config.js file,</p>
<pre><code>const {resolve} = require('path');

module.exports = {
  entry: [
    './md5.js'
  ],
  output: {
    path: resolve('./dist'),
    filename: 'md5.min.js',
    libraryTarget: &quot;var&quot;,
    library: &quot;MD5&quot;
  }
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: &quot;babel-loader&quot;
        }
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader'],
      },
    ]
  }
};
</code></pre>
<p>The code that triggers the error,</p>
<pre><code>import React from 'react';

describe('example to-do app', () =&gt; {
    beforeEach(() =&gt; {
        cy.visit('http://localhost:3000')
    })
    
    it(&quot;containsMain&quot;,()=&gt;{
        cy.contains(&quot;.main&quot;)
    })
})
</code></pre>
<p>The error also happens if I just try to load the page as well.</p>
",https://stackoverflow.com/questions/70305179/missing-webpack-loader-running-cypress-test-with-react,"['reactjs', 'webpack', 'cypress']",612,False,0,0
Access Docker container env variables from Gitlab pipeline,"<p>We are performing integration testing on a few containerized interconnected apps within a gitlab CI/CD pipeline.</p>
<p>Here is our integration stage in the .gitlab-ci.yml</p>
<pre class=""lang-yml prettyprint-override""><code>run-integration:
  image:
    name: cypress/included:8.3.1
    entrypoint: [&quot;&quot;]
  stage: test-integration
  before_script:
    - apt-get -y install make docker.io
    - service docker start
  script:
    - make run-integration
</code></pre>
<p>The containers have already been generated, so you may be wondering &quot;why add docker.io?&quot; The answer is that we want our integration testing report to include the git commit SHAs of the versions of the applications being tested. Each of the apps is being run in a docker container, and each container has the app's commit SHA saved as an environmental variable.</p>
<p>So the plan is that, within the <code>make run-integration</code> recipe, we'll use a <code>docker exec</code> command to run <code>printenv</code> within the container and get our SHA. Here is what that looks like in our Makefile:</p>
<pre class=""lang-make prettyprint-override""><code>run-integration:
    echo &quot;Starting run-integration!&quot;
    npm install
    npx cypress run; \
    exit_status=$$?; \
    export GIT_SHA=$$(docker exec &lt;CONTAINER-NAME&gt; printenv GIT_COMMIT_SHA); \
    node create-integration-test-report.js; \ # turns cypress results into an html report
                                              # and prints the local variable GIT_SHA onto the report
    exit $$exit_status

</code></pre>
<p>This works like a dream when I spin up the containers locally and use the <code>make run-integration</code> recipe locally, but in the pipeline it fails. Presently, this is my console error:</p>
<p><code>Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?</code></p>
<p>It's not so much that this one error is inscrutable (it's certainly been <a href=""https://stackoverflow.com/questions/44678725/cannot-connect-to-the-docker-daemon-at-unix-var-run-docker-sock-is-the-docker"">satisfactorily addressed</a> elsewhere, even if the solution is not working for me in the pipeline), but the amount of hassle required just for me to run the <code>docker exec</code> command is making me question the whole approach. If possible I'd like to not go as far down the rabbit hole as applying <code>sudo</code> or <code>systemctl</code> just to check on a value to print onto a report. I'm also not crazy about having to essentially install Docker onto the cypress image just to get this value. I have a few gitlab stages where I'm using <code>apk</code> or <code>apt-get</code> to make commands available (e.g. <code>apk add make</code> on multiple stages), and I feel a little weird about it.</p>
<p>The ultimate goal is to get the containerized app's git SHA onto the report. Is there a more direct way I'm missing?</p>
",https://stackoverflow.com/questions/70469628/access-docker-container-env-variables-from-gitlab-pipeline,"['docker', 'gitlab', 'integration-testing', 'gitlab-ci']",229,False,1,0
WebApplicationFactory and release pipeline,"<p>I am new to WebApplicationFactory use and want to know</p>
<ol>
<li>what is the use of this WebApplicationFactory class for integration tests. as my understanding, it is useful only for mocking external services (this is what we do in unit tests).</li>
</ol>
<p>Should we use WebApplicationFactory for simple web api integration testing?</p>
<ol start=""2"">
<li>what happens in release pipelines?
when i run integration tests (written using WebApplicationFactory) open the web api automatically and uses overrided appsettings set in a custom WebApplicationFactory class.
so when i publish the tests code on azure and creates release pipeline stage for integration tests. does the above test code (custom WebApplicationFactory ) override the actual app dll's appsetting. ( i mean does it start the app and use test appsetting logic)</li>
</ol>
",https://stackoverflow.com/questions/69211904/webapplicationfactory-and-release-pipeline,['integration-testing'],146,False,-1,1
Mock a function twice with Jest,"<p>So, I was testing a react component (it's actually an integration testing) and I have this:</p>
<pre><code>const Component = ({ children }) =&gt; {
  const [file, setFile] = React.useState({ name: null });
  const [slugConfig, setSlugConfig] = React.useState({ slug: '', error: null });

  const handleSubmit = jest.fn();

  const childrenWithProps = React.Children.map(children, child =&gt; {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, {
        handleSubmit,
        slugConfig,
        file,
        setFile,
        setSlugConfig,
      });
    }
    return child;
  });

  return &lt;div&gt;{childrenWithProps}&lt;/div&gt;;
};
</code></pre>
<p>Which is a mock to serve that Form. The Form component uploads a file, zip file, and has some validations when it's not .zip|.rar it will show an error.</p>
<p>So, problems is:
<strong>I have to test if it is a zip and a rar. However the file transformer returns only the name property (which is what I have to test)</strong></p>
<pre><code>module.exports = { name: 'file.ext' };
</code></pre>
<p>I mocked it:</p>
<pre><code>jest.mock('../../../../helpers/file-transformer', () =&gt; {
  return { name: 'file.zip' };
});
</code></pre>
<p>But I have to mock it to test it with another extension. How would I be able to do that?</p>
<ul>
<li>I can't spy, 'cause it is not a function;</li>
<li>Even if it was a function when testing jest will return this: <code>{ process: [Function: process] }</code></li>
</ul>
",https://stackoverflow.com/questions/68596105/mock-a-function-twice-with-jest,"['javascript', 'reactjs', 'jestjs']",100,False,0,0
Testcontainer doesn’t work with Kotlin and Quarkus - Exception in monitor thread while connecting to server mongo:27017,"<p>I am trying to create a simple todo application using <strong>Quarkus</strong>, <strong>Kotlin</strong>, <strong>MongoDB</strong> and <strong>TestContainers</strong>. I am using testcontainers to test my integration with mongodb. Unfortunately my test is not working like I expected. Here is my test case, I am not sure what goes wrong. I can see from the logs that the test container for mongodb is started and I am setting the replicaSetUrl in to the property.</p>
<pre><code>@QuarkusTest
class TodoResourceIT {

    @Container
    private val mongoDbContainer: MongoDBContainer = MongoDBContainer(&quot;mongo:4.2&quot;).withExposedPorts(27017)

    init {
        mongoDbContainer.start()
        System.setProperty(&quot;quarkus.mongodb.connection-string&quot;, mongoDbContainer.replicaSetUrl)
    }
    @Test
    fun shouldReturn200OK() {
        given().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
            .body(Todo(&quot;1&quot;, &quot;Find&quot;, &quot;Find the letter F&quot;))
            .`when`().post(&quot;/api/todos&quot;).then().statusCode(200)
    }
}
</code></pre>
<p>Here is my complete source code: <a href=""https://github.com/faskan/todo-kotlin-quarkus"" rel=""nofollow noreferrer"">https://github.com/faskan/todo-kotlin-quarkus</a></p>
<p>I have see a similar thread <a href=""https://stackoverflow.com/questions/61447252/integration-testing-with-testcontainers-quarkus-mongodb"">Integration testing with Testcontainers + Quarkus + MongoDB</a>. But the solution works only in Java. Here is my sample implementation using Java which works perfectly fine. <a href=""https://github.com/faskan/todo-java-quarkus"" rel=""nofollow noreferrer"">https://github.com/faskan/todo-java-quarkus</a></p>
<p>The problem I'm facing now is with Kotlin.</p>
<p>Stacktrace:</p>
<pre><code>INFO  [org.mon.dri.cluster] (cluster-ClusterId{value='60d34ff2ffb00164d8f60cbc', description='null'}-mongo:27017) Exception in monitor thread while connecting to server mongo:27017: com.mongodb.MongoSocketException: mongo
    at com.mongodb.ServerAddress.getSocketAddresses(ServerAddress.java:211)
    at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:75)
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65)
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:143)
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188)
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144)
    at java.base/java.lang.Thread.run(Thread.java:831)
Caused by: java.net.UnknownHostException: mongo
    at java.base/java.net.InetAddress$CachedAddresses.get(InetAddress.java:800)
    at java.base/java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:886)
    at java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1507)
    at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1366)
    at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1300)
    at com.mongodb.ServerAddress.getSocketAddresses(ServerAddress.java:203)
</code></pre>
",https://stackoverflow.com/questions/68102915/testcontainer-doesn-t-work-with-kotlin-and-quarkus-exception-in-monitor-thread,"['mongodb', 'kotlin', 'quarkus', 'testcontainers']",618,True,0,1
Error when running springboot with Cucmber and Serenity,"<p>I am trying to test my spring boot application using serenity-cucumber.</p>
<p>To do this , I have my entry point:</p>
<pre><code>package integration.com.foo.proj;

import io.cucumber.junit.CucumberOptions;
import net.serenitybdd.cucumber.CucumberWithSerenity;
import org.junit.runner.RunWith;

@RunWith(CucumberWithSerenity.class)
@CucumberOptions(features = &quot;src/test/resources&quot;)
public class CucumberIntegrationTest {
}
</code></pre>
<p>Then my Baseclass to be used by step defs,</p>
<pre><code>package integration.com.foo.proj;

import com.foo.proj.Application;
import io.cucumber.spring.CucumberContextConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

@CucumberContextConfiguration
@SpringBootTest(classes = Application.class)
@ActiveProfiles(&quot;sit&quot;)
public class SpringIntegrationTest {


}
</code></pre>
<p>And , one of my step defs is running some dummy tests at this point to work as glue.</p>
<pre><code>package integration.com.foo.proj;

import io.cucumber.java.en.And;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.springframework.beans.factory.annotation.Value;

public class StepDefs extends SpringIntegrationTest {

  @Value(&quot;${config.value}&quot;)
  private String configValue;

  @When(&quot;^the client calls /version$&quot;)
  public void the_client_issues_GET_version() throws Throwable {
    String s = configValue;
  }
  @Then(&quot;^the client receives status code of (\\d+)$&quot;)
  public void the_client_receives_status_code_of(int statusCode) throws Throwable {
    String s = configValue;
  }
  @And(&quot;^the client receives server version (.+)$&quot;)
  public void the_client_receives_server_version_body(String version) throws Throwable {
    String s = configValue;
  }
}
</code></pre>
<p>My feature class:</p>
<pre><code>Feature: the version can be retrieved
        Scenario: client makes call to GET /version
            When the client calls /version
            Then the client receives status code of 200
            And the client receives server version 1.0
</code></pre>
<p>I have imported the following dependencies, (have also tried with testCompile):</p>
<pre><code>testImplementation 'io.cucumber:cucumber-java:6.10.4'
testImplementation 'io.cucumber:cucumber-junit:6.10.4'
testImplementation 'io.cucumber:cucumber-spring:6.10.4'

testImplementation 'net.serenity-bdd:serenity-core:2.4.49'
testImplementation 'net.serenity-bdd:serenity-spring:2.4.49'
testImplementation 'net.serenity-bdd:serenity-junit:2.4.49'
testImplementation 'net.serenity-bdd:serenity-cucumber5:2.2.6'
</code></pre>
<p>When I am running the test , getting following error.</p>
<pre><code>Exception in thread &quot;main&quot; java.lang.NoSuchMethodError: io.cucumber.core.options.CommandlineOptionsParser: method &lt;init&gt;()V not found
    at net.serenitybdd.cucumber.cli.Main.run(Main.java:24)
    at net.serenitybdd.cucumber.cli.Main.main(Main.java:19)
</code></pre>
<p>During initial search , came across this <a href=""https://stackoverflow.com/questions/40992750/cant-run-cucumber-test-java-lang-nosuchmethoderror-cucumber-runtime-runtime/53497019"">post</a> whic mentioned to import <code>cucumber-java</code> and <code>cucumber-junit</code> in one of the answers , but does not work.</p>
<p>Is this due to the depency?</p>
<p>I also followed the post from serenity-bdd, but unable to get this working.<br />
<a href=""https://serenity-bdd.github.io/theserenitybook/latest/cucumber.html#_working_with_cucumber_4"" rel=""nofollow noreferrer"">Getting started with Cucumber and Serenity</a><br />
<a href=""https://serenity-bdd.github.io/theserenitybook/latest/spring.html"" rel=""nofollow noreferrer"">Integration testing Spring</a></p>
",https://stackoverflow.com/questions/68479587/error-when-running-springboot-with-cucmber-and-serenity,"['java', 'spring-boot', 'cucumber', 'serenity-bdd', 'cucumber-serenity']",677,True,0,1
How do I restrict pipelines to specific branches without using triggers?,"<p>How can I restrict on-demand (i.e. not triggered) pipelines in Azure DevOps so that they only run on specific branches?</p>
<p>For instance, I have a pipeline (using the newer YAML syntax) that should only run on the <code>master</code> branch, as it is used to push code through to production, and can only be run by certain developers (we handle a lot of PII data, so our audit controls are fairly demanding). I have another pipeline that should run on any branch <em>except</em> <code>master</code>, as it is used to push code through to integration/testing environments, and can be run by anyone.</p>
<p>If I specified a trigger, I can tell it only to fire on certain branches; but if I set <code>trigger: none</code> in my YAML then I can't apply those restrictions. Any ideas?</p>
",https://stackoverflow.com/questions/69444811/how-do-i-restrict-pipelines-to-specific-branches-without-using-triggers,['azure-devops'],3230,True,4,2
ASP.NET Core TestHost Integration Testing &#39;System.ArgumentNullException : String reference not set to an instance of a String.&#39;,"<p>I am implemeting integration testing using xunit and</p>
<pre><code>&lt;PackageReference Include=&quot;Microsoft.AspNetCore.TestHost&quot; Version=&quot;2.0.0&quot; /&gt;
</code></pre>
<p>following this tutorial:
<a href=""https://dotnetcorecentral.com/blog/asp-net-core-web-api-integration-testing-with-xunit/"" rel=""nofollow noreferrer"">https://dotnetcorecentral.com/blog/asp-net-core-web-api-integration-testing-with-xunit/</a></p>
<p>When I run my test I get this message</p>
<blockquote>
<p>String reference not set to an instance of a String</p>
<p>IntegrationTests.Categories.TestAdd:<br />
Outcome: Failed<br />
Error Message:<br />
System.ArgumentNullException : String reference not set to an instance of a String.</p>
<p>Parameter name: s</p>
<p>Stack Trace:</p>
<p>at System.Text.Encoding.GetBytes(String s)<br />
at Dopshop.Startup.ConfigureServices(IServiceCollection services) in /Users/josueaceves/Desktop/dopshop/Startup.cs:line 114<br />
--- End of stack trace from previous location where exception was   thrown ---<br />
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)<br />
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()<br />
at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()<br />
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()<br />
at Microsoft.AspNetCore.TestHost.TestServer..ctor(IWebHostBuilder builder, IFeatureCollection featureCollection)<br />
at IntegrationTests.TestClientProvider..ctor() in /Users/josueaceves/Desktop/dopshop/IntegrationTests/TestClientProvider.cs:line 17<br />
at IntegrationTests.Categories.TestAdd() in /Users/josueaceves/Desktop/dopshop/IntegrationTests/Categories.cs:line 31<br />
--- End of stack trace from previous location where exception was thrown ---</p>
<p>IntegrationTests.Categories.TestGetAll:<br />
Outcome: Failed<br />
Error Message:<br />
System.ArgumentNullException : String reference not set to an instance of a String.</p>
<p>Parameter name: s</p>
<p>Stack Trace:</p>
<p>at System.Text.Encoding.GetBytes(String s)<br />
at Dopshop.Startup.ConfigureServices(IServiceCollection services) in /Users/josueaceves/Desktop/dopshop/Startup.cs:line 114<br />
--- End of stack trace from previous location where exception was thrown ---<br />
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)<br />
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()<br />
at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()<br />
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()<br />
at Microsoft.AspNetCore.TestHost.TestServer..ctor(IWebHostBuilder builder, IFeatureCollection featureCollection)<br />
at IntegrationTests.TestClientProvider..ctor() in /Users/josueaceves/Desktop/dopshop/IntegrationTests/TestClientProvider.cs:line 17<br />
at IntegrationTests.Categories.TestGetAll() in /Users/josueaceves/Desktop/dopshop/IntegrationTests/Categories.cs:line 19<br />
--- End of stack trace from previous location where exception was thrown ---</p>
<p>Total tests: 2. Passed: 0. Failed: 2. Skipped: 0</p>
</blockquote>
<p>this is at the startup file line 114:</p>
<pre><code>TokenValidationParameters validationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                    .GetBytes(this.Configuration.GetSection(&quot;AppSettings:Token&quot;).Value)),
                ValidateIssuer = false,
                ValidateAudience = false
            };

</code></pre>
<p>I have my <code>ClientTestProvider</code>:</p>
<pre><code>using System;
using System.Net.Http;
using Dopshop;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;

namespace IntegrationTests
{
    public class TestClientProvider
    {
        private TestServer server;
        public HttpClient Client { get; private set; }

        public TestClientProvider()
        {

            server = new TestServer(new WebHostBuilder().UseStartup&lt;Startup&gt;());

            Client =  server.CreateClient();
        }
    }
}
</code></pre>
<p>And my two integration tests</p>
<pre><code>using System.Net;
using System.Threading.Tasks;
using Contracts.v1;
using Xunit;
using FluentAssertions;
using System.Net.Http;
using Newtonsoft.Json;
using System.Text;
using Dopshop.Models;

namespace IntegrationTests
{
    public class Categories
    {
        [Fact]
        public async Task TestGetAll()
        {
            using (var client = new TestClientProvider().Client)
            {
                var response = await client.GetAsync(ApiRoutes.Categories.GetAll);
                response.EnsureSuccessStatusCode();

                response.StatusCode.Should().Be(HttpStatusCode.OK);
            }
        }

        [Fact]
        public async Task TestAdd()
        {
            using (var client = new TestClientProvider().Client)
            {
                var response = await client.PostAsync(ApiRoutes.Categories.Add
                    , new StringContent(
                        JsonConvert.SerializeObject(new Category(){Name = &quot;nike Shoes&quot;, Description = &quot;shoe category&quot;, Sequence = 2, ShopId = 3}), 
                        Encoding.UTF8, 
                        &quot;application/json&quot;));

                response.EnsureSuccessStatusCode();

                response.StatusCode.Should().Be(HttpStatusCode.OK);
            }
        }
    }
} 
</code></pre>
<p>Does anyone have an idea what's going on? I'm new to testing in .NET Core. If anyone could point me in the right direction it would be highly appreciated.</p>
<pre><code>&lt;PackageReference Include=&quot;FluentValidation.AspNetCore&quot; Version=&quot;9.1.1&quot;/&gt;
&lt;PackageReference Include=&quot;Microsoft.AspNetCore.App&quot;/&gt;
&lt;PackageReference Include=&quot;Pomelo.EntityFrameworkCore.MySql&quot; Version=&quot;2.1.1&quot;/&gt;
&lt;PackageReference Include=&quot;AutoMapper.Extensions.Microsoft.DependencyInjection&quot; Version=&quot;7.0.0&quot;/&gt;
&lt;PackageReference Include=&quot;Swashbuckle.AspNetCore&quot; Version=&quot;5.4.0&quot;/&gt;
&lt;PackageReference Include=&quot;CloudinaryDotNet&quot; Version=&quot;1.11.0&quot;/&gt;
&lt;PackageReference Include=&quot;xunit&quot; Version=&quot;2.4.0&quot;/&gt;
&lt;PackageReference Include=&quot;xunit.runner.visualstudio&quot; Version=&quot;2.4.0&quot;/&gt;
&lt;PackageReference Include=&quot;Moq&quot; Version=&quot;4.14.5&quot;/&gt;
&lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;16.7.1&quot;/&gt;
&lt;PackageReference Include=&quot;SendGrid&quot; Version=&quot;9.21.0&quot;/&gt;
&lt;PackageReference Include=&quot;Microsoft.AspNetCore.TestHost&quot; Version=&quot;2.0.0&quot; /&gt;
&lt;PackageReference Include=&quot;FluentAssertions&quot; Version=&quot;5.10.3&quot; /&gt; 
</code></pre>
<p>this is the startup file</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Authorization;
using AutoMapper;
using Data;
using Filters;
using FluentValidation.AspNetCore;
using Dopshop.Models;
using Dopshop.Services.Email;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Repositories.Implementations;
using Repositories.Interfaces;
using Services.Email;
using Services.Photos;
using Settings;
using Microsoft.AspNetCore.Http;
using static Contracts.v1.Validation.Validators;
using Newtonsoft.Json.Linq;
using System.Net;
using Services.Authentication;

namespace Dopshop
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext&lt;DopshopContext&gt;(x =&gt; x.UseMySql(Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));
            
            services.AddMvc(options =&gt; {
                options.Filters.Add&lt;ValidationFilter&gt;();
            })
                .AddJsonOptions(options =&gt; {
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddFluentValidation(fv =&gt; fv.RegisterValidatorsFromAssemblyContaining&lt;CreateShopValidator&gt;());;
            
            services.Configure&lt;ApiBehaviorOptions&gt;(options =&gt;
            {
                options.SuppressModelStateInvalidFilter = true;
            });
            
            services.AddCors(options =&gt; {
                options.AddPolicy(name: &quot;ProductionPolicy&quot;,
                    builder =&gt; {
                        builder.WithOrigins(&quot;https://hustlr.azurewebsites.net&quot;,
                                            &quot;https://hustlr.cards&quot;, 
                                            &quot;https://hustlr-39c77.web.app&quot;, 
                                            &quot;https://hustlr-39c77.firebaseapp.com&quot;)
                                            .WithMethods(&quot;*&quot;)
                                            .WithHeaders(&quot;*&quot;);
                    });
            });

            services.AddSwaggerGen(option =&gt; {

                option.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo{ Title  = &quot;Dopshop API&quot;, Version = &quot;v1&quot;});

                option.AddSecurityDefinition(&quot;Bearer&quot;, new OpenApiSecurityScheme
                {
                    Description = &quot;JWT Authorization header using the bearer scheme&quot;,
                    Name = &quot;Authorization&quot;,
                    In = Microsoft.OpenApi.Models.ParameterLocation.Header,
                    Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
                    Scheme = &quot;Bearer&quot;
                });
                
                option.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = &quot;Bearer&quot;
                            },
                            Scheme = &quot;oauth2&quot;,
                            Name = &quot;Bearer&quot;,
                            In = ParameterLocation.Header,

                        },
                        new List&lt;string&gt;()
                    }
                });
                
                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $&quot;{Assembly.GetExecutingAssembly().GetName().Name}.xml&quot;;
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                option.IncludeXmlComments(xmlPath);
                });

            TokenValidationParameters validationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                    .GetBytes(this.Configuration.GetSection(&quot;AppSettings:Token&quot;).Value)),
                ValidateIssuer = false,
                ValidateAudience = false
            };

            services.AddAuthentication(options =&gt; 
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =&gt; {
                    options.SaveToken = true;
                    options.TokenValidationParameters = validationParameters;
                    options.Events = new JwtBearerEvents();
                    options.Events.OnChallenge = context =&gt;
                    {
                        // Skip the default logic.
                        context.HandleResponse();

                        var payload = new JObject
                        {
                            [&quot;code&quot;] = 401,
                            [&quot;message&quot;] = &quot;Invalid JWT Token&quot;
                        };

                        context.Response.ContentType = &quot;application/json&quot;;
                        context.Response.StatusCode = 401;

                        return context.Response.WriteAsync(payload.ToString());
                    };
            });

            services.AddSingleton&lt;TokenValidationParameters&gt;(validationParameters);

            services.Configure&lt;CloudinarySettings&gt;(Configuration.GetSection(&quot;CloudinarySettings&quot;));
            services.Configure&lt;SendGridAPISettings&gt;(Configuration.GetSection(&quot;SendGridSettings&quot;));
            
            services.AddAutoMapper(typeof(Startup).Assembly);

            services.AddTransient&lt;IShopRepository, ShopRepository&gt;();
            services.AddTransient&lt;IAuthRepository, AuthRepository&gt;();
            services.AddTransient&lt;IUserRepository, UserRepository&gt;();
            services.AddTransient&lt;IProductRepository, ProductRepository&gt;();
            services.AddTransient&lt;ICategoryRepository, CategoryRepository&gt;();
            services.AddTransient&lt;IProductCategoryRepository, ProductCategoryRepository&gt;();
            services.AddTransient&lt;IPhotoRepository, PhotoRepository&gt;();
            services.AddTransient&lt;IProductPhotosRepository, ProductPhotosRepository&gt;();
            services.AddTransient&lt;IReviewsRepository, ReviewsRepository&gt;();
            services.AddTransient&lt;ICategoryRepository, CategoryRepository&gt;();
            services.AddTransient&lt;IGenericRepository&lt;ReviewPhoto&gt;, GenericRepository&lt;ReviewPhoto&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;ShopTheme&gt;, GenericRepository&lt;ShopTheme&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;Currency&gt;, GenericRepository&lt;Currency&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;Industry&gt;, GenericRepository&lt;Industry&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;ShopLocation&gt;, GenericRepository&lt;ShopLocation&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;ShopPaymentMethod&gt;, GenericRepository&lt;ShopPaymentMethod&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;PaymentMethodType&gt;, GenericRepository&lt;PaymentMethodType&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;SocialLink&gt;, GenericRepository&lt;SocialLink&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;LinkType&gt;, GenericRepository&lt;LinkType&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;Category&gt;, GenericRepository&lt;Category&gt;&gt;();
            services.AddTransient&lt;IGenericRepository&lt;ProductCategory&gt;, GenericRepository&lt;ProductCategory&gt;&gt;();
            services.AddTransient&lt;IProductOptionRepository, ProductOptionRepository&gt;();
            services.AddTransient&lt;IProductOptionValueRepository, ProductOptionValueRepository&gt;();
            services.AddTransient&lt;IProductQuestionRepository, ProductQuestionRepository&gt;();
            services.AddTransient&lt;IProductVariationRepository, ProductVariationRepository&gt;();
            services.AddTransient&lt;IProductOptionValueVariationRepository, ProductOptionValueVariationRepository&gt;();
            services.AddTransient&lt;IRefreshTokenRepository, RefreshTokenRepository&gt;();
            services.AddTransient&lt;ISocialLinkRepository, ShopSocialLinkRepository&gt;();
            services.AddTransient&lt;IShopPaymentMethodsRepository, ShopPaymentMethodsRepository&gt;();
            services.AddTransient&lt;IReviewSentimentRepository, ReviewSentimentRepository&gt;();
            services.AddTransient&lt;IPasswordRecoveryRepository, PasswordRecoveryRepository&gt;();
            services.AddTransient&lt;IEmailService, SendGridEmailSender&gt;();
            services.AddTransient&lt;IPhotosService, CloudinaryPhotosService&gt;();
            services.AddTransient&lt;IAuthorizationHandlers, AuthorizationHandlers&gt;();
            services.AddTransient&lt;IAuthTokenGenerator, AuthTokenGenerator&gt;();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseCors(x =&gt; x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
                app.UseSwagger();
                app.UseSwaggerUI(c =&gt; { 
                    c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;Hustlr API V1&quot;);
                    c.RoutePrefix = string.Empty;
                });

                app.UseDefaultFiles();
                app.UseStaticFiles();
            }
            else
            {
                app.UseCors(&quot;ProductionPolicy&quot;);
                app.UseHsts();
                //app.UseHttpsRedirection();
            }

            app.UseStatusCodePages(context =&gt; {
                var request = context.HttpContext.Request;
                var response = context.HttpContext.Response;
                response.ContentType = &quot;application/json&quot;;
                if (response.StatusCode == (int)HttpStatusCode.Unauthorized)
                {
                    var payload = new JObject
                    {
                        [&quot;code&quot;] = 401,
                        [&quot;message&quot;] = &quot;Unauthorized&quot;
                    };
                    response.WriteAsync(payload.ToString());
                }

                return Task.CompletedTask;
            });
            
            app.UseAuthentication();
            app.UseMvc();
        }
    }
}
</code></pre>
<p>this is my Program.cs file</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Data;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Dopshop
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var db = scope.ServiceProvider.GetService&lt;DopshopContext&gt;();
                db.Database.Migrate();
            }

            host.Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =&gt;
            WebHost.CreateDefaultBuilder(args)
                .UseStartup&lt;Startup&gt;()
                .UseUrls(&quot;http://*:5000&quot;);
    }
}
</code></pre>
",https://stackoverflow.com/questions/68029542/asp-net-core-testhost-integration-testing-system-argumentnullexception-string,"['c#', 'asp.net', 'asp.net-core', 'integration-testing', 'xunit.net']",872,True,0,1
How to test aws S3 in mocha,"<p>This is my first Mocha/Chai attempt at testing. What would be the best way to do integration testing in mocha with aws S3. I try to mock aws S3 using aws-sdk-mock and sinon but I really don't know how and where to mock this?</p>
<p>Here is my code:</p>
<pre><code>// documentController

var aws = require('aws-sdk');
aws.config.update({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: 'ap-southeast-1'
});
var s3 = new aws.S3({apiVersion: '2006-03-01'});

function deleteObject(key) {
    s3.deleteObject({
        'Bucket': 'delete-bucket',
        'Key': key,
    }, function(err, data) {
        return
    })
};

create: function(req, res) {
   sails.async.auto(req, {
        getDocumentContent: ['teamPrefDoc', 'getDocument', function (results, cb) {
                var docKey = (
                    results.getDocument &amp;&amp; results.getDocument.key
                ) ? results.getDocument.key : '';
                var bucket = 'individual-docs';
                if (!docKey || !bucket) {
                    return res.badRequest(&quot;Document doesn't have a key&quot;);
                }
                var params = {
                    Bucket: bucket,
                    Key: docKey
                };
                var tempDocStream = fs.createWriteStream(tempFileName + '.doc');
                var s3Stream = s3.getObject(params).createReadStream();
                s3Stream.pipe(tempDocStream).on('close', function() {
                    tempDocStream.close();
                    return cb(null, true);
                }).on('error', function(err) {
                    sails.log(err);
                    return cb(null, false);
                });
            }],
       'savePdfToS3': ['convertToPdfLocally', function (results, cb) {
                if (!results.convertToPdfLocally) {
                    return cb(null, false)
                }
                var s3Key = results.documentDoc.key + '/pdf';
                fs.readFile(tempFileName + '.pdf', (err, pdfBuffer) =&gt; {
                    if (err) { return cb(err); }
                    s3.putObject({
                        'Bucket': results.getDocumentContent,
                        'Key': s3Key,
                        'Body': pdfBuffer,
                        'ContentType': 'application/pdf'
                    }, function(err, data) {
                        if (err) { return cb(err); }
                        Documents.update({
                            id: id
                        }, {
                            pdf_key: s3Key
                        }).exec(function(err, updatedDocs) {
                            if (err) {
                                sails.log(&quot;Couldn't write pdf url to document&quot;, err);
                                return cb(err);
                            }
                            return cb(null, updatedDocs[0]);
                        });
                    })
                });
            }],
   }
}
</code></pre>
<p>I have an API that runs create function which runs some database queries and saves the doc to s3. So, I want to test this API but I don't know how to mock s3.getObject and s3.putObject.</p>
<p>Here is my test file that run setup and teardown connection</p>
<pre><code>// bootstrap.test.js

var sinon = require('sinon')
var AWSMock = require('aws-sdk-mock')

before(async () =&gt; {
     const getObjectStub = AWS.S3.prototype.getObject = sinon.stub();
     var s3 = new Aws.S3();
     AWSMock.mock('S3', 'getObject', function(parmas,callback){
         console.log(&quot;Callback received for getObject&quot;);
         callback(null,'Success');
     });
     AWSMock.mock('S3', 'deleteObject', function(param,callback){
       callback(null,{'s3deleteMarker': true 
         ,'s3DeleteVersionId': 'VERSION ID' 
         ,'s3DeletedImageSourceUid': 'SOURCE' 
         ,'s3DeletedKey': 'KEY'});
     });
</code></pre>
<p>Here is my test code:</p>
<pre><code>// document.test.js

describe('document controller', () =&gt; {
        it('should upload a doc', done =&gt; {
            defaultDocument.resourceId = caseIds[0],
            request(sails.hooks.http.app)
            .post(`${apiVersion}/new/documents?app=test`)
            .set('Authorization', `Bearer ${process.env.ACCESS_TOKEN}`)
            .field(defaultDocument)
            .attach('document0', 'some_pdf.pdf')
            .expect(200)
            .end((err, res)=&gt; {
                if(err) {
                    return done(err)
                }
                console.log(res.body)
                done()
            })
        })
    })
</code></pre>
<p>I am fairly new to unit tests, so I am happy for any direction you can point me in :-)</p>
<p>Thank you very much!</p>
",https://stackoverflow.com/questions/68311544/how-to-test-aws-s3-in-mocha,"['amazon-s3', 'mocha.js', 'chai', 'sinon', 'aws-sdk-mock']",782,False,1,1
Flutter Integration testing failed for multiple test cases in a single file,"<p>I have a simple login page with email and password text field. A button to login and another to sign up. I tried to write integration testing for the Sign in page.</p>
<pre><code>void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  testWidgets('''could type email and password in text filed''',
      (WidgetTester tester) async {
    await app.main();
    await tester.pumpAndSettle();

    final textFieldEmail = find.byType(InputTextWidget).first;
    final textFieldPassword = find.byType(InputTextWidget).last;

    await tester.enterText(textFieldEmail, &quot;asis.adh@gmail.com&quot;);
    await tester.pumpAndSettle();

    expect(find.text(&quot;asis.adh@gmail.com&quot;), findsOneWidget);
  });

testWidgets(
      'should redirect to Sign Up Page when create an account is tapped',
      (WidgetTester tester) async {
    await app.main();
    await tester.pumpAndSettle();

    final createAnAccount = find.text(&quot;Create an account&quot;);
    await tester.tap(createAnAccount);

    await tester.pumpAndSettle();

    expect(find.byType(SignupPage), findsOneWidget);
    expect(find.byType(LoginPage), findsNothing);
  });
}
</code></pre>
<p>When I execute the test case, it fails with the following error:</p>
<blockquote>
<p>The following ArgumentError was thrown running a test: Invalid
argument(s): Object/factory with  type AmenitiesProvider is already
registered inside GetIt.</p>
</blockquote>
<p>Here is my <code>main.dart</code> file</p>
<pre><code>Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  configureInjection(Environment.prod);

  /// for registering the factory.
  await Future.delayed(const Duration(seconds: 2));
  runApp(RoopaApp());
}
</code></pre>
<p>I tried with a <code>main_test.dart</code> and adding <code>configureInjection(Environment.test)</code> but nothing changes. I am not sure how to fix the error. Is there a way to clean the <code>app</code> or destroy it before going to new test case. If I combine the both testcase into one then it works without any problem.</p>
<p>Here is <code>configureInjection</code></p>
<pre><code>@injectableInit
void configureInjection(String environment) {
  $initGetIt(getIt, environment: environment);
}
</code></pre>
<p>I am using get_it and injection package for dependency injection.</p>
<p>Here is the auto generated initGetIt</p>
<pre><code>GetIt $initGetIt(
  GetIt get, {
  String environment,
  EnvironmentFilter environmentFilter,
}) {
  final gh = GetItHelper(get, environment, environmentFilter);
  final httpClientInjectableModule = _$HttpClientInjectableModule();
  final flutterStorageModule = _$FlutterStorageModule();
  gh.lazySingleton&lt;AmenitiesProvider&gt;(() =&gt; AmenitiesProvider());
  gh.factory&lt;Client&gt;(() =&gt; httpClientInjectableModule.client);
  gh.lazySingleton&lt;FileProvider&gt;(() =&gt; FileProvider());
  gh.lazySingleton&lt;FlutterSecureStorage&gt;(
      () =&gt; flutterStorageModule.secureStorate);
  gh.factory&lt;ProfilePageBloc&gt;(() =&gt; ProfilePageBloc());
  gh.factory&lt;SplashScreenBloc&gt;(() =&gt; SplashScreenBloc());
  gh.lazySingleton&lt;AuthLocalDataSourceProtocol&gt;(
      () =&gt; AuthLocalDataSource(secureStorage: get&lt;FlutterSecureStorage&gt;()));
  gh.lazySingleton&lt;AuthRemoteDataSourceProtocol&gt;(
      () =&gt; AuthRemoteDataSource(client: get&lt;Client&gt;()));
  return get;
}
</code></pre>
",https://stackoverflow.com/questions/66228575/flutter-integration-testing-failed-for-multiple-test-cases-in-a-single-file,"['flutter', 'dependency-injection', 'integration-testing', 'testcase', 'widget-test-flutter']",1471,True,1,2
How to perform integration tests for an Angular-based application in production?,"<p>I am trying to add integration testing to my Angular 10 based application and everything seems to be working properly locally. I just define the tests in files with the spec.ts extension and run using ng test. The question is how can I run these tests in production? I use GitLab CI to dockerize application and to run in production using nginx on Kubernetes. So when I access my pod there is built production version and of course ng test does not work. I just need to run tests mainly related to my Angular service with some example requests like POST, GET, DELETE etc. to other components to check whether the whole system is working properly with Angular portal. Do you have any ideas how can I solve this?</p>
",https://stackoverflow.com/questions/69086987/how-to-perform-integration-tests-for-an-angular-based-application-in-production,"['angular', 'typescript', 'testing', 'jasmine', 'integration-testing']",79,False,-1,1
Powershell or CMD - I want to run two commands at the same time without waiting for the first command to finish,"<p>I would like to run two commands (it doesn't matter if it's in powershell or cmd). The commands are as follows. I try to run both at the same time but because chromedriver needs to be running - it hangs forever and never reaches the second command.</p>
<ul>
<li>chromedriver --port=4444</li>
<li>flutter drive --target=test_driver/app.dart --browser-name=chrome --release --no-headless</li>
</ul>
<p>I am following the documentation here (towards the bottom of the page)
<a href=""https://flutter.dev/docs/cookbook/testing/integration/introduction"" rel=""nofollow noreferrer"">Flutter integration testing</a> (but this isn't really that important for my question - just an FYI on what I was doing)</p>
<p>I keep googling for &quot;how to run two commands&quot; but the answers I usually get are to use &quot;&amp;&quot; or &quot;&amp;&amp;&quot; but in my case this doesn't work as chromedriver will just stay open whilst it executes.</p>
<p>Thanks,</p>
<p>Michael Smith</p>
",https://stackoverflow.com/questions/68825272/powershell-or-cmd-i-want-to-run-two-commands-at-the-same-time-without-waiting,"['flutter', 'powershell', 'cmd', 'flutter-test', 'flutter-integration-test']",248,True,0,1
Calling functions and variables in same package but different files with build tags,"<p>I'm setting up some integration testing, which I'm doing in a separate test package to my src code. This is done to prevent circular dependencies. Unit tests are not stored here, they are stored alongside the files they are testing.</p>
<p>My golang project hierarchy looks like:</p>
<p>cmd
public
...
testing/
main_test.go
database_test.go</p>
<p>in main_test.go, I plan to initialise the connections to external dependencies, such as my test database.</p>
<pre><code>package tests

type Database struct {
...
}
var DB Database

func TestMain(m *testing.M){
 SetUpDatabase()
 exitCode := m.Run()
 os.Exit(exitCode)
}
</code></pre>
<p>database_integration_test.go</p>
<pre><code>func Test(t *testing.T) {

    tests := []struct {
        title string
        run   func(t *testing.T)
    }{
        {&quot;should make query&quot;, testQuery},

    }
    for _, test := range tests {
        t.Run(test.title, func(t *testing.T) {
            test.run(t)
        })
    }
}

func testQuery(t *testing.T) {

    var r result.Result
    err := DB.database.DoQuery(&quot;&quot;).Decode(&amp;r)

    if err != nil {
        t.Errorf(err.Error())
        t.Fatal()
    }
}
</code></pre>
<p>This setup works when I run it, however, I would like to add build tags to these files, or the type: <code>// +build integration</code>
However, as soon as I use the build tag, the database_integration_test.go file cannot see the initalised Database type. How can I stop this? Also as a side note, should I change the name of main_test.go. I only called it that due to main being the standrd entry point.</p>
",https://stackoverflow.com/questions/67061534/calling-functions-and-variables-in-same-package-but-different-files-with-build-t,"['go', 'build', 'integration-testing']",500,True,3,2
How to perform integration testing on AWS Step Function,"<p>I have a REST API in API Gateway with lambda proxy integration. The Lambda will invoke a Step Function workflow asynchronously and will return an ID in the payload. These AWS resources are deployed and managed by AWS CDK.</p>
<p>My question is, is there a proper way to perform integration test? There are two approaches I have in mind:</p>
<ol>
<li>Call the REST API endpoint, and make assertions on side effects. But since the workflow is executed asynchronously, the test needs to continuously poll until side effects become visible.</li>
<li>According to this blog <a href=""https://www.10printiamcool.com/step-function-integration-testing-with-cdk"" rel=""nofollow noreferrer"">https://www.10printiamcool.com/step-function-integration-testing-with-cdk</a>, it seems like we can use CDK to deploy a test stack with mocking the dependent resources (e.g Lambda). But this sounds more of like unit test.</li>
</ol>
<p>I am not sure if there are any better options. Any thoughts?</p>
",https://stackoverflow.com/questions/70376822/how-to-perform-integration-testing-on-aws-step-function,"['amazon-web-services', 'integration-testing', 'aws-step-functions']",1090,True,0,1
Junit 5 functional testing the Micronaut Messaging-Driven Application,"<p>I have a Rabbit MQ Micronaut Messaging-Driven application. The application only contains the Consumer side, Producer side is on another REST API application.</p>
<p>Now I want to perform JUnit 5 testing with the consumer side only. Trying to get the best idea to test the Messaging-Driven application that contains only the Rabbit MQ Listener</p>
<pre><code>@RabbitListener
public record CategoryListener(IRepository repository) {

@Queue(ConstantValues.ADD_CATEGORY)
    public CategoryViewModel Create(CategoryViewModel model) {
        LOG.info(String.format(&quot;Listener --&gt; Adding the product to the product collection&quot;));
        Category category = new Category(model.name(), model.description());
        return Single.fromPublisher(this.repository.getCollection(ConstantValues.PRODUCT_CATEGORY_COLLECTION_NAME, Category.class)
                .insertOne(category)).map(success-&gt;{
            return new CategoryViewModel(
                    success.getInsertedId().asObjectId().getValue().toString(),
                    category.getName(),
                    category.getDescription());
        }).blockingGet();
    }
}
</code></pre>
<p>After some research, I found that we can use <code>Testcontainers</code> for integration testing, In my case, the Producer and receiver are on a different server. So do I need to create <code>RabbitClient</code> for each <code>RabbitListener</code> in the test environment or is there any way to mock <code>RabbitClient</code></p>
<pre><code>@MicronautTest
@Testcontainers
public class CategoryListenerTest {

    @Container
    private static final RabbitMQContainer RABBIT_MQ_CONTAINER = new RabbitMQContainer(&quot;rabbitmq&quot;)
            .withExposedPorts(5672, 15672);

    @Test
    @DisplayName(&quot;Rabbit MQ container should be running&quot;)
    void rabbitMqContainerShouldBeRunning() {
        Assertions.assertTrue(RABBIT_MQ_CONTAINER.isRunning());
    }
}
</code></pre>
<p>What is the best way to perform functional tests of Micronaut Messaging-Driven Application? In this question, I have a PRODUCER on another application. So I can't inject a PRODUCER client. How can I test this function on the LISTENER side?</p>
",https://stackoverflow.com/questions/65557767/junit-5-functional-testing-the-micronaut-messaging-driven-application,"['java', 'junit', 'junit5', 'micronaut', 'micronaut-test']",342,True,0,1
How to strip exports during build for GAS process? Need to use exports in local unit testing with Jest,"<p>Trying to use Jest for local unit &amp; integration testing. I already have some npm scripts to build the GAS-compatible code and upload it with clasp so that's not an issue.</p>
<p>The problem is seemingly simple but I can't figure out the best way to handle removing the exports that Jest requires to work.</p>
<p>For example say I start with a super simple script like this in my <strong>sum.js</strong> file:</p>
<pre><code>function sum(a, b) {
  return a + b
}
</code></pre>
<p>If I want to add a test to that function I add <code>module.exports = sum</code> which will result in a <strong>sum.js</strong> file like this:</p>
<pre><code>function sum(a, b) {
  return a + b
}
module.exports = sum
</code></pre>
<p>And then write my tests in a <strong>sum.test.js</strong> file, something like this:</p>
<pre><code>import { add } from &quot;./index.js&quot;

test('adds 1 + 2 to equal 3', () =&gt; {
  expect(add(1, 2)).toBe(3);
});
</code></pre>
<p>The problem is <code>module.exports = sum</code> and <code>export { sum }</code> create an exception in Google Apps Scripts (won't even upload with clasp), so I just want an easy way to remove all exports during the build process that's not a super hacky solution.</p>
",https://stackoverflow.com/questions/65605083/how-to-strip-exports-during-build-for-gas-process-need-to-use-exports-in-local,"['unit-testing', 'testing', 'google-apps-script', 'jestjs', 'automated-tests']",62,False,0,1
Unable to create JDBC connection to Test Container for DB2,"<p>I am using a Test Container for integration testing that needs a database. I have done this the MSSQL before it and worked fine but this is the first time I tried to use it with DB2.</p>
<pre><code>    &lt;dependency&gt;
        &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;
        &lt;artifactId&gt;db2&lt;/artifactId&gt;
        &lt;version&gt;1.15.0&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
</code></pre>
<p>I have the setup like this:</p>
<pre><code>@BeforeClass
public static void setUpClass() {
    db2Container = new Db2Container(&quot;ibmcom/db2&quot;)
            .acceptLicense()
            .withDatabaseName(&quot;testDb2&quot;)
            .withUsername(&quot;username&quot;)
            .withPassword(&quot;password&quot;)
            .withInitScript(&quot;initDB2.sql&quot;);
    db2Container.start();

    System.setProperty(&quot;general.datasource.jbhdb2p.jdbc-url&quot;, db2Container.getJdbcUrl());
    System.setProperty(&quot;general.datasource.jbhdb2p.username&quot;, db2Container.getUsername());
    System.setProperty(&quot;general.datasource.jbhdb2p.password&quot;, db2Container.getPassword());
}
</code></pre>
<p>I have not done a test container with DB2 before so I am not sure of the desired logs but it seems fine up until it starts looping these 3 lines forever:</p>
<pre><code>10:10:18.569 [main] DEBUG org.testcontainers.shaded.com.github.dockerjava.core.command.AbstrDockerCmd - Cmd: 2331d2432c59900608324d8fe471d4e6fec3a6c337ebdf8bb0c532d361a07b66,false
10:10:18.570 [main] DEBUG org.testcontainers.shaded.com.github.dockerjava.core.exec.InspectContainerCmdExec - GET: DefaultWebTarget{path=[/containers/2331d2432c59900608324d8fe471d4e6fec3a6c337ebdf8bb0c532d361a07b66/json], queryParams={}}
10:10:18.578 [main] DEBUG 🐳 [ibmcom/db2:latest] - Trying to create JDBC connection using com.ibm.db2.jcc.DB2Driver to jdbc:db2://localhost:49193/testDb2 with properties: {password=password, user=username}
</code></pre>
<p>Here is the logs before the loop starts:</p>
<pre><code>10:08:19.692 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Previous setup has not been detected. Creating the users... 
10:08:19.692 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Creating users ...
10:08:19.837 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Creating instance ... 
10:08:20.906 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:20.907 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DB2 installation is being initialized.
10:08:23.322 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:23.322 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Total estimated time for all tasks to be performed: 309 second(s) 
10:08:23.322 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT:  Total number of tasks to be performed: 4 
10:08:23.337 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Estimated time 1 second(s) 
10:08:23.337 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Description: Setting default global profile registry variables 
10:08:23.337 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Task #1 start
10:08:23.359 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:23.359 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Task #1 end 
10:08:23.383 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Estimated time 5 second(s) 
10:08:23.383 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Description: Initializing instance list 
10:08:23.383 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Task #2 start
10:08:23.965 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:23.965 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Task #2 end 
10:08:23.979 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Estimated time 300 second(s) 
10:08:23.979 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Description: Configuring DB2 instances 
10:08:23.979 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Task #3 start
10:08:39.070 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Task #3 end 
10:08:39.070 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:39.091 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:39.091 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: The execution completed successfully.
10:08:39.091 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:39.091 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Task #4 end 
10:08:39.091 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Estimated time 3 second(s) 
10:08:39.091 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Description: Updating global profile registry 
10:08:39.091 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Task #4 start
10:08:40.739 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:40.739 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:40.739 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DBI1070I  Program db2icrt completed successfully.
10:08:40.739 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:40.739 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:40.739 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DBI1446I  The db2icrt command is running.
10:08:40.739 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: For more information see the DB2 installation log at &quot;/tmp/db2icrt.log.71&quot;.
10:08:40.910 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: SQL1032N  No start database manager command was issued.  SQLSTATE=57019
10:08:40.910 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 07/02/2021 14:08:41     0   0   SQL1032N  No start database manager command was issued.
10:08:43.018 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Cataloging existing databases
10:08:43.040 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Applying Db2 license ...
10:08:43.040 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDERR: ls: cannot access /database/data/sa/NODE0000: No such file or directory
10:08:43.113 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:43.113 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: LIC1402I  License added successfully.
10:08:43.113 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: LIC1426I  This product is now licensed for use as outlined in your License Agreement.  USE OF THE PRODUCT CONSTITUTES ACCEPTANCE OF THE TERMS OF THE IBM LICENSE AGREEMENT, LOCATED IN THE FOLLOWING DIRECTORY: &quot;/opt/ibm/db2/V11.5/license/en_US.iso88591&quot;
10:08:43.113 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:43.114 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:43.134 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Updating DBM CFG parameters ... 
10:08:43.134 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Saving the checksum of the current nodelock file ...
10:08:44.528 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DB20000I  The UPDATE DATABASE MANAGER CONFIGURATION command completed 
10:08:44.530 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: successfully.
10:08:45.636 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: successfully.
10:08:45.636 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DB20000I  The UPDATE DATABASE MANAGER CONFIGURATION command completed 
10:08:46.731 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: successfully.
10:08:46.732 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DB20000I  The UPDATE DATABASE MANAGER CONFIGURATION command completed 
10:08:46.752 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Remounting /database with suid... 
10:08:46.752 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: No Cgroup memory limit detected, instance memory will follow automatic tuning
10:08:51.381 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Code level is the same. No update/upgrade needed.
10:08:51.381 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Nothing appears in the Db2 directory. will skip update/upgrade.
10:08:51.440 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DB2 State : Operable
10:08:51.440 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:51.463 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 
10:08:51.463 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: Starting DB2...
10:08:51.463 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DB2 has not been started
10:08:53.379 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: SQL1063N  DB2START processing was successful.
10:08:53.379 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 07/02/2021 14:08:53     0   0   SQL1063N  DB2START processing was successful.
10:08:53.394 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Creating database testDb2 ... 
10:08:53.394 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) User chose to create testDb2 database
10:10:15.143 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DB20000I  The CREATE DATABASE command completed successfully.
10:10:16.771 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DB20000I  The ACTIVATE DATABASE command completed successfully.
10:10:16.782 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Instance and database will not be auto configured. AUTOCONFIG has been set to false. 
10:10:16.782 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Log archiving will not be configured as ARCHIVE_LOGS has been set to false. 
10:10:18.307 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Skipping TEXT_SEARCH setup for database testDb2 because TEXT_SEARCH is not configured for the instance ...
10:10:18.519 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: ssh-keygen: generating new host keys: RSA2 RSA DSA ECDSA ED96529 
10:10:18.534 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 2
10:10:18.534 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DATA #10: unsigned integer, 8 bytes
10:10:18.534 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 2
10:10:18.534 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DATA #9 : unsigned integer, 8 bytes
10:10:18.534 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 4
10:10:18.534 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DATA #8 : signed integer, 4 bytes
10:10:18.535 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 4
10:10:18.535 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DATA #7 : signed integer, 4 bytes
10:10:18.535 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: 8
10:10:18.535 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: DATA #6 : signed integer, 4 bytes
10:10:18.535 [main] DEBUG org.testcontainers.containers.output.WaitingConsumer - STDOUT: (*) Setup has completed.
10:10:18.537 [main] INFO 🐳 [ibmcom/db2:latest] - Container ibmcom/db2:latest started in PT2M2.3332179S
10:10:18.545 [main] INFO org.testcontainers.ext.ScriptUtils - Executing database script from initDB2.sql
</code></pre>
<p>I found a repository that had a DB2 integration test already written in it and tried to clone and run it on my machine. It gave the same logs as the one I tried to create. This makes me thing my issue may be a docker/IDE issue rather than a code issue.</p>
<p>Can anyone gather enough info from these logs to guide me in a direction? Thanks!</p>
",https://stackoverflow.com/questions/68226920/unable-to-create-jdbc-connection-to-test-container-for-db2,"['java', 'db2', 'integration-testing', 'testcontainers']",827,False,2,1
Mocking DAO object with MockMvc in Spring Boot,"<p>I am new to Integration testing. I have Spring Integration application for which I am writing test cases. here is how I am writing test case:
<strong>Activator:</strong></p>
<pre><code>@Service
public class ProdAppActivator { 
    @Autowired
    private ApplicantDAO applicantDAO;
    @Transactional
    public ApplicantDTO prodApp(ApplicantDTO applicant)
            throws TechnicalException, BusinessException {

        applicantDAO.updateApp(applicant);
        
        return application;
    }
}
</code></pre>
<p><strong>Test Class:</strong></p>
<pre><code>public class AcctImplTest extends AbstractTest {    
    @MockBean 
    private ApplicantDAO applicantDAO;

    @Override
    @Before
    public void setUp() {
        super.setUp();
    }

    @Test
    public void testProdApp() throws Exception {
        ProdAppRequest appRequest = getProdAppRequest();
        mvc.perform(post(&quot;/baseurl/applicant&quot;).headers(getHeaders()).accept(MediaType.APPLICATION_JSON)
                .content(mapToJson(appRequest)).contentType(MediaType.APPLICATION_JSON)).andDo(print())
                .andExpect(status().isOk());
    }
}
</code></pre>
<p><strong>AbstractTest:</strong></p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { &quot;classpath:group/deposit/svc/product-application-context-test.xml&quot; })
@WebMvcTest
//@IfProfileValue(name =&quot;profiles.active&quot;, value =&quot;Integration&quot;)
public abstract class AbstractTest {
    
    protected MockMvc mvc;

    @Autowired
    WebApplicationContext webApplicationContext;

    protected void setUp() {
        setCMD();
        mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();        
    }
}
</code></pre>
<p>I have 2 issues:</p>
<ol>
<li>This activator has a method with @Transactional annotation. I am not sure why but because of this annotation my test getting failed and giving error as:</li>
</ol>
<pre><code>java.lang.ClassLoader.loadClass(ClassLoader.java:424)
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
java.lang.ClassLoader.loadClass(ClassLoader.java:357)
org.springframework.orm.hibernate4.HibernateTransactionManager.isSameConnectionForEntireSession(HibernateTransactionManager.java:711)
org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:445)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:378)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:474)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:289)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
com.hsbc.group.depositproduct.us.svc.activators.RecordProdAppActivator$$EnhancerBySpringCGLIB$$d1f3f882.recordProdApp(&lt;generated&gt;)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
</code></pre>
<p>When I remove this annotation everything works fine. But I don't want to remove this annotation so can some please suggest how to write test here.</p>
<ol start=""2"">
<li>if I remove @Transactional annotation; I have used @MockBean to mock DAO object(Interface) and its mocking given object but when I try to return expected value for any DAO call its returning default value. Can some one please suggest how to mock DAO while using @MockBean. I have tried @SpyBean, and other possible ways but didn't get success.
Thanks in advance.</li>
</ol>
",https://stackoverflow.com/questions/67436370/mocking-dao-object-with-mockmvc-in-spring-boot,"['spring-boot', 'mockito', 'spring-integration', 'powermockito', 'mockmvc']",231,False,1,0
