title,body,link,tags,view_count,is_answered,score,answer_count
kubernetes integration testing,"<p>I have 3 microservices, where service A talks to service B and C, and C can talk to A.</p>
<p>I have set up a Jenkins pipeline, where unit tests get run as part of the CI build, however, I'm not sure how to test the container once deployed on the pod. Integration tests on our staging server? I have looked into creating a test container, and using that as a test runner, which can populate the database with data, and verify the results, and produce a report. Is this how it's done?</p>
",https://stackoverflow.com/questions/63143374/kubernetes-integration-testing,"['kubernetes', 'jenkins-pipeline', 'devops']",1496,True,1,1
Snowflake Integration Testing Implementation,"<p>I have a service(Java + Springboot) which uses PostgreSQL database, the service will be migrated to <strong>Snowflake</strong> (cloud-based data-warehousing) so I would like to know what is the best way to implement integration testing</p>

<p>I tried to find a <strong>snowflake docker image</strong> (docker hub) or a <strong>testcontainer</strong> but so far I have not found anything useful, any suggestions?</p>

<p><a href=""https://www.testcontainers.org/"" rel=""nofollow noreferrer"">https://www.testcontainers.org/</a></p>

<p><a href=""https://hub.docker.com/"" rel=""nofollow noreferrer"">https://hub.docker.com/</a></p>
",https://stackoverflow.com/questions/60419383/snowflake-integration-testing-implementation,"['java', 'spring-boot', 'integration-testing', 'snowflake-cloud-data-platform']",4339,False,4,2
Integration Testing Async controller,"<p>I am doing controller integration testing. A controller with a get mapping returns Flux.</p>

<pre><code>@Slf4j
@RequiredArgsConstructor
@RequestMapping(""journal"")
public class EntryController {

    private final SomeService someService;

    @GetMapping
    public Flux&lt;MyEntity&gt; getEntity(
            @RequestParam(required = false) String documentId,
            @RequestParam(required = false) String docNumber){
 return someService.getEntities( GetEntriesRequest.builder()
                         .documentId(documentId)
                         .docNumber(docNumber).build;
    }
    @PostMapping
    public MyEntity postNew(@RequestBody @Valid MyEntity entity) {
        return someService.save(entity);
    }

}
            .
</code></pre>

<p>Initially, I tried to test it like this. (method asJson remakes the Entity created by creatingEntity method in a Json format). I'm already tested a controller with a post mapping and it works right.</p>

<pre><code>    @Test
    void getEntriesByDocumentNumber() throws Exception {
        MvcResult mvcResult  = this.mockMvc.perform(post(""/journal"")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .content(asJson(creatingEntity())))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(status().isOk())
                .andReturn();
        String response = mvcResult.getResponse().getContentAsString();
        String documentIdFromResponse = 
       JsonPath.parse(response).read(""$.documentId"");

        this.mockMvc.perform(get(""/journal"")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .param(""documentId"", documentIdFromResponse))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(status().isOk());
</code></pre>

<p>I do not know how to process the response that I receive. The fact is that the response body is empty, but the method works, this can be seen in the async result. I did not find how to get the asinc result. And I can’t use JsonPath, because the body is empty.</p>

<pre><code>      HTTP Method = GET
      Request URI = /journal
       Parameters = {documentId=[1590067372983-9ce4f563-520d-42ff-bd31-5b78befaf4b1]}
          Headers = [Content-Type:""application/json;charset=UTF-8"", Accept:""application/json""]
             Body = null
    Session Attrs = {}

Async:
    Async started = true
     Async result = [MyEntity(documentId=1590067372983-9ce4f563-520d-42ff-bd31-5b78befaf4b1, documentNumber=100)]

Resolved Exception:
             Type = null

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

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = []
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = [] 
</code></pre>

<p>I try to use WebTestClient, But this code does not work. It's falling with <strong>No bean named 'webHandler' available</strong></p>

<pre class=""lang-java prettyprint-override""><code>@SpringBootTest
@AutoConfigureMockMvc
class ApplicationTests {
@Autowired
    private MockMvc mockMvc;

    WebTestClient webTestClient;

    @BeforeEach
    void setUp(ApplicationContext context) {
        webTestClient = WebTestClient.bindToApplicationContext(context).build();
    }
    @Test
    void getEntityTest() throws Exception {
        MvcResult mvcResult  = this.mockMvc.perform(post(""/journal"")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .content(asJson(creatingEntity())))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(status().isOk())
                .andReturn();
        String response = mvcResult.getResponse().getContentAsString();
        String documentIdFromResponse = JsonPath.parse(response).read(""$.documentId"");

        webTestClient.get()
                .uri(""journal/"")
                .accept(MediaType.APPLICATION_JSON)
                .exchange()
                .expectStatus().isOk()
                .expectBody()
                .jsonPath(""$[0].documentId"").isEqualTo(documentIdFromResponse);
    }
}
</code></pre>

<p>I'm already find this. But I don't know how to use it</p>

<pre><code>@Bean
    public WebHandler webHandler() {
        //implement your bean initialization here
    }
</code></pre>
",https://stackoverflow.com/questions/62133585/integration-testing-async-controller,"['java', 'spring', 'spring-mvc', 'asynchronous', 'integration-testing']",291,False,2,0
Integration testing flink job,"<p>I've written a small flink application. I has some input, and enriches it with data from an external source. It's an <code>RichAsyncFunction</code> and within the <code>open</code> method I construct a http client to be used for the enrichment.</p>

<p>Now I want to write an integration test for my job. But since the http client is created within the open method I have no means to provide it, and mock it in my integration test. I've tried to refactor it providing it within the constructor, but I'm always getting serialisation errors.</p>

<p>This is the example I'm working from:
<a href=""https://ci.apache.org/projects/flink/flink-docs-release-1.10/dev/stream/operators/asyncio.html"" rel=""nofollow noreferrer"">https://ci.apache.org/projects/flink/flink-docs-release-1.10/dev/stream/operators/asyncio.html</a></p>

<p>Thanks in advance :)</p>
",https://stackoverflow.com/questions/62127443/integration-testing-flink-job,"['apache-flink', 'flink-streaming']",570,True,3,2
Integration testing Blazor apps,"<p>With Razor Pages, we had the TestServer class which we would use to write <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1"" rel=""nofollow noreferrer"">Integration tests in ASP.NET Core</a>.</p>

<p>How would one go about testing a <a href=""https://learn.microsoft.com/en-us/aspnet/core/blazor/hosting-models?view=aspnetcore-3.1#blazor-server"" rel=""nofollow noreferrer"">Blazor Server</a> app? When I say integration testing, I mean testing the whole app: sending a request to the TestServer which runs the app, getting an HTML page back, and checking its contents.</p>

<p>Is this possible with Blazor Server? If not, what is the recommended approach for integration testing Blazor Server apps?</p>
",https://stackoverflow.com/questions/62267112/integration-testing-blazor-apps,['blazor-server-side'],1837,True,1,2
Integration Testing With @DataJpaTest,"<p>I have this test in my project:</p>
<pre><code>@DataJpaTest
@SpringBootTest
@TestPropertySource(locations = &quot;classpath:local-configuration.properties&quot;)
public class CanPixaRepositoryTest  {

    @Autowired
    private CanPixaRepository canPixaRepository;

    public void setUp() throws Exception {
    }

    @Test
    public void testAll() {
        canPixaRepository].getAvui(&quot;fqs&quot;);
    }
}
</code></pre>
<p>local-configuration.properties:</p>
<pre><code>spring.datasource.url=jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
</code></pre>
<p>but when I run the test, canPixaRepositoryRepository is null</p>
",https://stackoverflow.com/questions/64441989/integration-testing-with-datajpatest,"['spring-boot', 'jpa', 'junit', 'spring-data-jpa', 'spring-data']",1575,True,1,2
Integration Testing with Authentication,"<p>I am building a service currently in which the authentication is managed by way of a session token. A user enters their email address, and if their email address is valid they are emailed a token is validated and emailed to them. From that email, they can then click a link to 'log in'.</p>
<p>The problem I have is with my e2e tests, I can test the 'login' function no problems but all other API endpoints then need to use a session token. The only way I can get at the session token is via email, which doesn't seem practical.</p>
<p>The only other thought I have had is using some kind of master token that never expires, but that feels wrong from a security perspective.</p>
<p>Any thoughts?</p>
",https://stackoverflow.com/questions/65432044/integration-testing-with-authentication,"['authentication', 'integration-testing']",63,False,0,0
Integration testing involving rabbitmq,"<p>I need help on how to write integration testing involving the rabbitMQ message broker.</p>

<p>This is the overall system architecture</p>

<p>Service(Producer) --> Message Borker(Environment 1) --> Controllers(Our Application) --> Message Broker(Environment 2) --> Consumer Devices</p>

<p>I am planning to place my integration testing programs at the service level wherein I will mimic a message to be sent to a Message broker. Later I will listen for the response and assert it.</p>

<p>Though its an asynchronous system, testing synchronous way seems to be an easy approach.</p>

<p>Is there any better approach to do the integration testing for my application flow. Could you please give me pointers for integration testing. </p>

<p>Thanks
Bala.</p>
",https://stackoverflow.com/questions/60076615/integration-testing-involving-rabbitmq,"['java', 'spring', 'rabbitmq']",768,False,0,1
Integration testing with Testcontainers + Quarkus + MongoDB,"<p>Trying out testcontainers for integration testing. I am testing rest api endpoint. Here is the technology stack - 
quarkus, RESTEasy and mongodb-client</p>

<p>I am able to see MongoDB container is started successfully but getting exception. Exception: ""com.mongodb.MongoSocketOpenException: Exception opening socket""</p>

<pre><code>2020-04-26 15:13:18,330 INFO  [org.tes.doc.DockerClientProviderStrategy] (main) Loaded org.testcontainers.dockerclient.UnixSocketClientProviderStrategy from ~/.testcontainers.properties, will try it first
2020-04-26 15:13:19,109 INFO  [org.tes.doc.UnixSocketClientProviderStrategy] (main) Accessing docker with local Unix socket
2020-04-26 15:13:19,109 INFO  [org.tes.doc.DockerClientProviderStrategy] (main) Found Docker environment with local Unix socket (unix:///var/run/docker.sock)
2020-04-26 15:13:19,258 INFO  [org.tes.DockerClientFactory] (main) Docker host IP address is localhost
2020-04-26 15:13:19,305 INFO  [org.tes.DockerClientFactory] (main) Connected to docker: 
  Server Version: 19.03.8
  API Version: 1.40
  Operating System: Docker Desktop
  Total Memory: 3940 MB
2020-04-26 15:13:19,524 INFO  [org.tes.uti.RegistryAuthLocator] (main) Credential helper/store (docker-credential-desktop) does not have credentials for quay.io
2020-04-26 15:13:20,106 INFO  [org.tes.DockerClientFactory] (main) Ryuk started - will monitor and terminate Testcontainers containers on JVM exit
2020-04-26 15:13:20,107 INFO  [org.tes.DockerClientFactory] (main) Checking the system...
2020-04-26 15:13:20,107 INFO  [org.tes.DockerClientFactory] (main) ✔︎ Docker server version should be at least 1.6.0
2020-04-26 15:13:20,230 INFO  [org.tes.DockerClientFactory] (main) ✔︎ Docker environment should have more than 2GB free disk space
2020-04-26 15:13:20,291 INFO  [🐳 .2]] (main) Creating container for image: mongo:4.2
2020-04-26 15:13:20,420 INFO  [🐳 .2]] (main) Starting container with ID: d8d142bcdef8e2ebe9c09f171845deffcda503d47aa4893cd44e72d7067f0cdd
2020-04-26 15:13:20,756 INFO  [🐳 .2]] (main) Container mongo:4.2 is starting: d8d142bcdef8e2ebe9c09f171845deffcda503d47aa4893cd44e72d7067f0cdd
2020-04-26 15:13:22,035 INFO  [🐳 .2]] (main) Container mongo:4.2 started in PT3.721S
2020-04-26 15:13:24,390 INFO  [org.mon.dri.cluster] (main) Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2020-04-26 15:13:24,453 INFO  [org.mon.dri.cluster] (main) Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2020-04-26 15:13:24,453 INFO  [org.mon.dri.cluster] (cluster-ClusterId{value='5ea5dd542fb66c613dc74629', description='null'}-127.0.0.1:27017) Exception in monitor thread while connecting to server 127.0.0.1:27017: com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.internal.connection.SocketChannelStream.open(SocketChannelStream.java:63)
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:126)
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:714)
    at sun.nio.ch.SocketAdaptor.connect(SocketAdaptor.java:122)
    at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:64)
    at com.mongodb.internal.connection.SocketChannelStream.initializeSocketChannel(SocketChannelStream.java:72)
    at com.mongodb.internal.connection.SocketChannelStream.open(SocketChannelStream.java:60)
    ... 3 more

</code></pre>

<p>If I use docker run then my test case works properly.</p>

<pre><code>docker run -p 27017:27017 --name mongodb mongo:4.2
</code></pre>

<p>using testcontainer as mentioned @ <a href=""https://www.testcontainers.org/quickstart/junit_5_quickstart/"" rel=""noreferrer"">https://www.testcontainers.org/quickstart/junit_5_quickstart/</a></p>

<pre><code>@Container
    static GenericContainer mongodb = new GenericContainer&lt;&gt;(""mongo:4.2"").withExposedPorts(27017);
</code></pre>
",https://stackoverflow.com/questions/61447252/integration-testing-with-testcontainers-quarkus-mongodb,"['mongodb', 'docker', 'quarkus', 'testcontainers']",5906,True,10,5
Integration testing on Shiny apps,"<p>I'm trying to use integration testing on this shiny app, but after reading up on it, I'm not sure what I'm doing wrong. I keep getting this error: Error in isModuleServer(app) : object 'session' not found
I'm also getting this error: Error: object 'output' not found</p>
<p>Any help is appreciated.</p>
<pre><code>library(shiny)
displayColoredBox&lt;- function(color, riskMessage){
  sidebarPanel(style=sprintf(&quot;background-color: %s; width: 300px; height: 300px;&quot;, color),
               h3(sprintf(&quot;%s&quot;, riskMessage)) )  }
shinyApp(
  ui = fluidPage(
    
    div(
      id = &quot;form&quot;,
      sliderInput(&quot;count1&quot;, &quot;First Slider Input&quot;, value=0, min=0, max=5000),
      sliderInput(&quot;count2&quot;, &quot;Second Slider Input&quot;, value=0, min=0, max=5000),
      uiOutput(&quot;coloredBox&quot;)
    )),
  
  server &lt;- function(input, output) {
    
    output$coloredBox&lt;-renderUI({
      req(input$count1)
      req(input$count2)
      
      count1 &lt;- input$count1;
      count2 &lt;- input$count2;
      
      likelihood &lt;- (count1*count2)/5000000
      
      
      if (likelihood&gt;1) {
        color=&quot;red&quot;
        riskMessage=&quot;Extreme risk!&quot;
        
      } else if (likelihood&gt;.65){
        color=&quot;orange&quot;
        riskMessage=&quot;Very high risk!&quot;
      }
      else if (likelihood&gt;.35){
        color=&quot;yellow&quot;
        riskMessage=&quot;High risk!&quot;
      }
      else if (likelihood&gt;.10){
        color=&quot;blue&quot;
        riskMessage=&quot;Moderate risk!&quot;
      } else {
        color=&quot;green&quot;
        riskMessage=&quot;Low risk!&quot;
      }
      
      displayColoredBox(color, riskMessage)
      
    })
  }
)

testServer({
  session$setInputs(count1 = 1500)
  session$setInputs(count2 = 2500)
  
  stopifnot(output$likelihood == 0.75)
  stopifnot(output$riskMessage == &quot;Very high risk!&quot;)
  stopifnot(output$color == &quot;orange&quot;)
  
})
</code></pre>
",https://stackoverflow.com/questions/63575035/integration-testing-on-shiny-apps,"['r', 'shiny', 'shiny-server', 'shinyapps', 'shiny-reactivity']",300,True,2,1
LocalStackContainer integration testing a lambda,"<p>Is there a way we can (integration) test a Lambda for AWS using testcontainers &amp; the following LocalStackContainer:</p>
<pre><code>new LocalStackContainer(DockerImageName.parse('localstack/localstack:0.11.6'))
    .withServices(LocalStackContainer.Service.LAMBDA)
</code></pre>
<p>Specifically, how do I &quot;upload&quot; the Lambda to the locally running service, so that I can then trigger &amp; test it?</p>
",https://stackoverflow.com/questions/64589023/localstackcontainer-integration-testing-a-lambda,"['java', 'aws-lambda', 'spock', 'testcontainers', 'localstack']",3707,True,1,2
Flink - Integration Testing Table API?,"<p>I have built a very small and straight forward Flink app which consumes events from Kafka (json) deserialize them to a Java object and then create two Table and uses the Table API to to some simple operation and finally join the two table and write the result back to a Kafka</p>

<p>What are the best practices to test such code? How do I go about to write Integration Test that verify that the code written with Table API produces the right result?</p>

<p>(Using Flink 1.8.3)</p>
",https://stackoverflow.com/questions/61823861/flink-integration-testing-table-api,"['unit-testing', 'integration-testing', 'apache-flink']",304,True,1,1
Scala Akka framework Integration testing,"<p>I am trying to write a simple integration test for a scala application that uses the AKKA framework.</p>
<p>I want to</p>
<ol>
<li>have the application start on my local host</li>
<li>write test cases that hit the application directly</li>
</ol>
<p>I have done similar things things using springboottest but i can't seem to find anything remotely similar to this. I have been trying to read up on testkit routes and what not but it seems more like a unit test then it is a full application integration testing.</p>
<p>Any pointers or recommendations on what I am looking for would be great.</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/64937814/scala-akka-framework-integration-testing,"['scala', 'akka', 'integration-testing']",176,False,0,2
Cypress integration testing with amazon cognito,"<p>I am trying to create an e2e testing for our client app which uses amazon cognito for login. I am trying to follow the aws documentation on logging in. I am getting a network error. I am not sure if this is the right way. I am getting a network error because probably it's passing thru our VPN. How should I resolve this using the aws library? Below is the sample code I used which I got from AWS documentation.</p>
<pre><code>var authenticationData = {
        Username : 'username',
        Password : 'password',
    };
    var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
    var poolData = { UserPoolId : 'us-east-1_ExaMPle',
        ClientId : '1example23456789'
    };
    var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
    var userData = {
        Username : 'username',
        Pool : userPool
    };
    var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function (result) {
            var accessToken = result.getAccessToken().getJwtToken();

            /* Use the idToken for Logins Map when Federating User Pools with identity pools or when passing through an Authorization Header to an API Gateway Authorizer */
            var idToken = result.idToken.jwtToken;
        },

        onFailure: function(err) {
            alert(err);
        },

});
</code></pre>
",https://stackoverflow.com/questions/62717370/cypress-integration-testing-with-amazon-cognito,"['amazon-cognito', 'cypress']",2537,True,5,2
ASP.NET Core 3 mock authorization during integration testing,"<p>I am using ASP.NET core to build an API, and I am trying to upgrade from .NET core 2.2 to .NET core 3.1.</p>

<p>I am using the <code>[Authorize]</code> attribute to secure the API endpoints and I want to bypass it during integration tests.</p>

<p>I have managed to to create a custom AuthenticationHandler that authenticates a fake user, and an authorization handler that authorizes anybody (including anonymous users).</p>

<p>My problem is that the user injected in the Authentication handler is not propagated to the Authorization handler and the filter <code>DenyAnonymousAuthorizationRequirement</code> fails
because the User in the context is null.</p>

<p>Has anyone dealt with something similar? </p>

<p>By the way, the class <code>DenyAnonymousAuthorizationRequirement</code> is a Microsoft class, I copied the code as it appeared in the IDE just for the post here.</p>

<p>My custom AuthenticationHandler:</p>

<pre><code>  public class TestAuthHandler : AuthenticationHandler&lt;AuthenticationSchemeOptions&gt;
  {
        public TestAuthHandler(IOptionsMonitor&lt;AuthenticationSchemeOptions&gt; options,
                               ILoggerFactory logger,
                               UrlEncoder encoder,
                               ISystemClock clock)
            : base(options, logger, encoder, clock) { }

        protected override Task&lt;AuthenticateResult&gt; HandleAuthenticateAsync()
        {
            ClaimsPrincipal fakeUser = FakeUserUtil.FakeUser();
            var ticket = new AuthenticationTicket(fakeUser, ""Test"");
            var result = AuthenticateResult.Success(ticket);
            return Task.FromResult(result);
        }
  }
</code></pre>

<p>The AuthorizationRequirement:</p>

<pre><code>public class DenyAnonymousAuthorizationRequirement : AuthorizationHandler&lt;DenyAnonymousAuthorizationRequirement&gt;, IAuthorizationRequirement
    {

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DenyAnonymousAuthorizationRequirement requirement)
        {
            var user = context.User;
            var userIsAnonymous =
                user?.Identity == null ||
                !user.Identities.Any(i =&gt; i.IsAuthenticated);
            if (!userIsAnonymous)
            {
                context.Succeed(requirement);
            }
            return Task.CompletedTask;
        }
    }
</code></pre>

<p>The code in the ConfigureServices method that uses the above classes:</p>

<pre><code> public void ConfigureServices(IServiceCollection services)
 {

            services.AddAuthentication(""Test"")
                    .AddScheme&lt;AuthenticationSchemeOptions, TestAuthHandler&gt;(""Test"", null);
            services.AddAuthorization(configure =&gt;
            {
                var builder = new AuthorizationPolicyBuilder(new List&lt;string&gt; {""Test""}.ToArray())
                    .AddRequirements(new DenyAnonymousAuthorizationRequirement());
                configure.DefaultPolicy = builder.Build();
            });
            services.AddControllers()
                    .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
                    .AddNewtonsoftJson(options =&gt;
                                           options.SerializerSettings.ReferenceLoopHandling =
                                               ReferenceLoopHandling.Ignore);

}
</code></pre>
",https://stackoverflow.com/questions/59577491/asp-net-core-3-mock-authorization-during-integration-testing,"['c#', 'asp.net', 'integration-testing']",21257,True,17,2
Mule Flow only for Integration Testing,"<p>I have got the Mule 4 application which is driven by Scheduler to schedule every 30 minutes. I have added http listener under the file test-listener.xml just for invoking it for building the integration testing.</p>
<p>I want the test-listener.xml to be deployed only into non-production environment. How can I achieve it in Mule 4.3.0 Runtime</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/65069092/mule-flow-only-for-integration-testing,['mule'],313,True,2,1
Integration testing a .NET Core 3 Worker,"<p>ASP.NET Core has <code>WebApplicationFactory&lt;T&gt;</code> that can be used to start up a test host for integration test purposes. </p>

<p>Is there an equivalent for a non ASP.NET Core project? I'm thinking of the "".NET Core Worker Service Template"" for example. It doesn't have any references to ASP.NET Core, but it uses the generic host.</p>

<p>For example, I have a project like this one, hosted as a windows service. I would like to create integration tests as easily for this as I do for ASP.NET Core projects (where I can reuse DI from the Startup file, so I don't need to set that up in the test.</p>

<pre><code>public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =&gt;
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, builder) =&gt;
            {
                builder.AddAppSettings(context.HostingEnvironment.EnvironmentName);
            })
            .ConfigureServices((hostContext, services) =&gt;
            {
                // Loads of configuration (DI, Logging, Messaging, etc) removed for brevity
                // ...
            })
            .UseWindowsService();
}
</code></pre>

<p>In this case the service listens for messages (using Masstransit) so there is no <code>HostedService</code> setup. But there might be as well in other cases.</p>
",https://stackoverflow.com/questions/60889150/integration-testing-a-net-core-3-worker,"['c#', '.net', '.net-core', 'asp.net-core-3.1', '.net-core-3.1']",1720,True,8,1
Spark+Hive integration testing with Docker,"<p>I have Spark+Hive job that is working fine.</p>
<p>I'm trying to configure the environment for local development and integration testing:</p>
<ol>
<li>Docker <a href=""https://github.com/big-data-europe/docker-hive"" rel=""nofollow noreferrer"">images</a> to bootstrap Hive Server, metastore, etc</li>
<li>Docker <a href=""https://github.com/gettyimages/docker-spark/blob/master/Dockerfile"" rel=""nofollow noreferrer"">image</a> with Spark environment/local cluster</li>
</ol>
<p>Now I have docker-compose for #1 that runs the entire environment (including Hive metastore) and I can connect to this metastore with beeline tool.</p>
<p>I can run my spark with docker run using the image from #2 and it is running.</p>
<p>The problem I have is related to Hive configuration. Whenever the job is trying to read the table within SparkContext it fails with:</p>
<pre><code>[Error] [JvmBridge] java.lang.NoSuchFieldError: HIVE_STATS_JDBC_TIMEOUT
</code></pre>
<p>Hadoop: 2.7.3
Spark: 2.4.5
hive-metastore jar: 2.1.1</p>
<p>Spark submit params (/var/lib is the correct path):</p>
<pre><code>--conf spark.sql.hive.metastore.version=2.1.1 --conf spark.sql.hive.metastore.jars=/var/lib/*
</code></pre>
<p>hive-site.xml (added to Hive and Spark config folders)</p>
<pre><code>&lt;configuration&gt;
    &lt;property&gt;&lt;name&gt;hive.metastore.warehouse.dir&lt;/name&gt;&lt;value&gt;hdfs://localhost:50075&lt;/value&gt;&lt;/property&gt;
    &lt;property&gt;&lt;name&gt;hive.metastore.uris&lt;/name&gt;&lt;value&gt;thrift://localhost:9083&lt;/value&gt;&lt;/property&gt;
    &lt;property&gt;&lt;name&gt;spark.sql.uris&lt;/name&gt;&lt;value&gt;thrift://localhost:9083&lt;/value&gt;&lt;/property&gt;
    &lt;property&gt;&lt;name&gt;hive.exec.dynamic.partition.mode&lt;/name&gt;&lt;value&gt;nonstrict&lt;/value&gt;&lt;/property&gt;
    &lt;property&gt;&lt;name&gt;hive.exec.dynamic.partition&lt;/name&gt;&lt;value&gt;true&lt;/value&gt;&lt;/property&gt;
&lt;/configuration&gt;
</code></pre>
<p>How to demystify this error?</p>
",https://stackoverflow.com/questions/64125123/sparkhive-integration-testing-with-docker,"['docker', 'apache-spark', 'hadoop', 'hive']",1147,False,1,0
Integration testing calls with simulated delays,"<p>I'm testing an asp.net Core 2.2 WebApi backend which uses EF Core for data persistance.</p>

<p>The solution is arquitected using CLEAN arquitecture with a repository/service pattern making every component individually testable.</p>

<p>My integration tests (using XUnit and EF Core in-memory database) need to test the following cases:</p>

<ol>
<li>User makes a request and instantly makes another identical request.</li>
<li>User makes a request and 15 seconds later, makes another identical request.</li>
<li>User makes a request and 30 seconds later, makes another identical request.</li>
</ol>

<p>Each of these cases have about 5 variants each. Right now, I'm using a <code>Thread.Sleep(x)</code> call in between each of the calls to simulate this delay. This, of course, means that my integration tests take <em>ages</em> to complete. The delays are used in order for the repository layer to save a <code>DateTime.UtcNow</code> value when each of the calls is made; the value of which is used by the Service layer to perform some business-logic decisions.</p>

<p>What I'm wondering, is whether there is a way of 'simulating' these delays using the testing framework, removing the need for the tests to actually wait this time, and <em>tricking</em> the repository layer into using a <code>DateTime.UtcNow</code> value which is incremented by <code>x</code>. </p>

<p>Thanks you!</p>
",https://stackoverflow.com/questions/61083952/integration-testing-calls-with-simulated-delays,"['c#', '.net-core', 'integration-testing', 'asp.net-core-webapi', 'xunit']",430,True,1,1
Integration Testing Rest Controllers assertEquals fails,"<p>The response im getting from the serve is blank and I am not sure as to why. I've provided what i've worked through so far. Im following a tutorial, the goal is just to rest the rest controller by comparing my expected string to the actual string. Thanks so much for any help.</p>
<p>Here is my application</p>
<pre><code>package com.books.gallo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication()
public class BooksRestApplication {

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

}

</code></pre>
<p>Here is the controller</p>
<pre><code>
package com.books.gallo.resource.impl;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.books.gallo.domain.Book;
import com.books.gallo.resource.Resource;
import com.books.gallo.service.BookService;


@RestController
@RequestMapping(&quot;/books&quot;)
public class BookResourceImpl implements Resource&lt;Book&gt; {

    @Autowired
    private BookService bookService;


    @GetMapping(&quot;/testing&quot;)
    public String test(){
        return String.format(&quot;test has run&quot;);
    }

    
    @Override
    public ResponseEntity&lt;Collection&lt;Book&gt;&gt; findAll(){
        return new ResponseEntity&lt;&gt;(bookService.findAll(), HttpStatus.OK);
        
    }
    
    @Override
    public ResponseEntity&lt;Book&gt; findById(Long id){
        return new ResponseEntity&lt;&gt;(bookService.findById(id), HttpStatus.OK);
        
    }
    @Override
    public ResponseEntity&lt;Book&gt; save(Book book){
        return new ResponseEntity&lt;&gt;(bookService.save(book), HttpStatus.CREATED);
        
    }
    @Override
    public ResponseEntity&lt;Book&gt; update(Book book){
        return new ResponseEntity&lt;&gt;(bookService.update(book), HttpStatus.OK);
        
    }
    @Override
    public ResponseEntity&lt;Book&gt; deleteById(Long id){
        return new ResponseEntity&lt;&gt;(bookService.deleteById(id), HttpStatus.OK);
        
    }
    

}

</code></pre>
<p>Here is my test</p>
<pre><code>package com.books.gallo.resource.impl;

import com.books.gallo.service.impl.BookServiceImpl;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

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

@ExtendWith(SpringExtension.class)
@WebMvcTest(BookResourceImpl.class)
@ContextConfiguration(classes = {BookServiceImpl.class})
class IntegrationBookResourceImplTest {

    @Autowired
    private MockMvc mvc;

    @Test
    void test1() throws Exception {
        RequestBuilder request = MockMvcRequestBuilders.get(&quot;/books/testing&quot;);
        MvcResult result = mvc.perform(request).andReturn();
        assertEquals(&quot;test has run&quot;, result.getResponse().getContentAsString());
    }
}
</code></pre>
<pre><code>
This is the error


MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /books/testing
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

org.opentest4j.AssertionFailedError: 
Expected :test has run
Actual   :

Update after removal of @ContextConfiguration(classes = {BookServiceImpl.class})

[See Error Image below][1]


  [1]: https://i.stack.imgur.com/8pKR8.png
</code></pre>
",https://stackoverflow.com/questions/64937181/integration-testing-rest-controllers-assertequals-fails,"['java', 'spring-boot', 'spring-mvc', 'integration-testing']",222,True,0,1
Automated Integration Testing between two API&#39;s,"<p>My solution consists of four main components:</p>

<ul>
<li><strong>MVC UI</strong> - Calls Web API 1 (out of scope for this question)</li>
<li><strong>Web API 1</strong> - Calls Web API 2 and handles the response</li>
<li><strong>Web API 2</strong> - Calls database and handles the response</li>
<li><strong>Database</strong> - Stores data (out of scope for this question)</li>
</ul>

<p>I'm looking into how to set up automation tests to verify the integration between these components. It seems fairly straight forward to test the integration between <strong>Web API 2</strong> and <strong>Database</strong>, following guides such as <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1"" rel=""nofollow noreferrer"">this</a> or <a href=""https://adatis.co.uk/sql-server-database-integration-testing-using-nunit/"" rel=""nofollow noreferrer"">this</a>, however I'm not sure how to go about verifying the integration between my two APIs. </p>

<p>How can I set up automated integration tests to verify the integration between <strong>Web API 1</strong> and <strong>Web API 2</strong>?</p>
",https://stackoverflow.com/questions/60634315/automated-integration-testing-between-two-apis,"['asp.net-core', 'integration-testing']",169,False,0,1
Spring Integration Testing Oracle Native SQL,"<p>I have a legacy application that has recently been ported from Struts to Spring MVC. The data layer is written with native Oracle SQL. I'd like to introduce some integration testing but would like to avoid using an actual Oracle database for obvious reasons. Is there an in-memory DB that can deal with Oracle native SQL? Is this just a dream? Am I just going to end up with Oracle XE in a VM?</p>
",https://stackoverflow.com/questions/60352905/spring-integration-testing-oracle-native-sql,"['spring', 'oracle', 'testing', 'integration', 'in-memory-database']",456,True,0,2
Unit / Integration testing a tk application,"<p>I am trying to find any suitable software preferably open source to do tdd and bdd testing in a tk application.</p>
<p>If you have any suggestion, I would be very grateful.</p>
<p>Regards,
Panos</p>
",https://stackoverflow.com/questions/62515919/unit-integration-testing-a-tk-application,"['unit-testing', 'tcl', 'integration-testing', 'tk-toolkit']",43,False,0,1
JUnit End to End Integration Testing,"<p>I am doing an End To End integration testing with JUnit and Spring (not Boot). I would like to test from a POST request all the way to the db. Here is my test:</p>

<pre><code>@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy({
    @ContextConfiguration(classes = TestConfig.class),
    @ContextConfiguration(classes = OrderHdrController.class)
})
@ActiveProfiles(""Test"")
public class FilterActivityTest4 {

    MockMvc mockMvc;
    @Autowired
    private WebApplicationContext wac;
    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).dispatchOptions(true).build();
    }

    @Test
    public void testActivity() {

        OrderSearchDto orderSearchDto = new OrderSearchDto();
        OrderSearchPanelDto orderSearchPanelDto = new OrderSearchPanelDto();
        orderSearchPanelDto.setActivityTypes(Arrays.asList(""TAKEOVER"",""DELIVERY""));
        orderSearchDto.setOrderSearchPanelDto(orderSearchPanelDto);

        try {
            MvcResult result = this.mockMvc.perform(post(""/orders/getOrderList"")
                    .content(asJsonString(orderSearchDto))).andDo(MockMvcResultHandlers.print())
                    .andExpect(status().isOk())
                    .andReturn();
            String content = result.getResponse().getContentAsString();
            System.out.print(content);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static String asJsonString(final Object obj) {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            final String jsonContent = mapper.writeValueAsString(obj);
            return jsonContent;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }  
}
</code></pre>

<p>And here is my TestConfig.class:</p>

<pre><code>    @Autowired
    private OrderManager orderManager;

    @Bean
    public OrderManager OrderManager() {
        return orderManager;
    }
</code></pre>

<p>And in my OrderHdr controller class:</p>

<pre><code>@Controller
@RequestMapping(""/orders"")
public class OrderHdrController {
    @Autowired
    private OrderManager orderManager;

    @RequestMapping(value = ""/getOrderList"", method = RequestMethod.POST)
    @ResponseBody
    public Map&lt;String, Object&gt; getOrderTables(OrderSearchDto orderSearchDto) {
         ...
         orderHdrTables = orderManager.findAllOrders(orderSearchDto);
         ...
    }
}
</code></pre>

<p>But my orderManager object is null in my controller, causing a Null Pointer Exception when I run the test. </p>

<p>Question is: How to I instantiate the orderManager object? Is it by ""Autowired""?</p>

<p>Please help. Thanks.</p>
",https://stackoverflow.com/questions/59572437/junit-end-to-end-integration-testing,"['java', 'spring', 'junit']",517,False,0,2
Spring Integration Testing of Outbound Http Enpoint,"<p>I am new to the Spring Integration project, now I need to create a flow with Java DSL and test it.
I came up with these flows. First one should run by cron and invoke second one, which invokes HTTP endpoint and translates XML response to POJO:</p>
<pre><code>  @Bean
  IntegrationFlow pollerFlow() {
    return IntegrationFlows
        .from(() -&gt; new GenericMessage&lt;&gt;(&quot;&quot;),
            e -&gt; e.poller(p -&gt; p.cron(this.cron)))
        .channel(&quot;pollingChannel&quot;)
        .get();
  }

  @Bean
  IntegrationFlow flow(HttpMessageHandlerSpec bulkEndpoint) {
    return IntegrationFlows
        .from(&quot;pollingChannel&quot;)
        .enrichHeaders(authorizationHeaderEnricher(user, password))
        .handle(bulkEndpoint)
        .transform(xmlTransformer())
        .channel(&quot;httpResponseChannel&quot;)
        .get();
  }

  @Bean
  HttpMessageHandlerSpec bulkEndpoint() {
    return Http
        .outboundGateway(uri)
        .httpMethod(HttpMethod.POST)
        .expectedResponseType(String.class)
        .errorHandler(new DefaultResponseErrorHandler());
  }
</code></pre>
<p>Now I want to test flow and mock HTTP call, but struggling to mock HTTP handler, I tried to do it like that:</p>
<pre><code>@ExtendWith(SpringExtension.class)
@SpringIntegrationTest(noAutoStartup = {&quot;pollerFlow&quot;})
@ContextConfiguration(classes = FlowConfiguration.class)
public class FlowTests {

  @Autowired
  private MockIntegrationContext mockIntegrationContext;
  @Autowired
  public DirectChannel httpResponseChannel;
  @Autowired
  public DirectChannel pollingChannel;

  @Test
  void test() {
    final MockMessageHandler mockHandler = MockIntegration.mockMessageHandler()
        .handleNextAndReply(message -&gt; new GenericMessage&lt;&gt;(xml, message.getHeaders()));
    mockIntegrationContext.substituteMessageHandlerFor(&quot;bulkEndpoint&quot;, mockHandler);
    httpResponseChannel.subscribe(message -&gt; {
      assertThat(message.getPayload(), is(notNullValue()));
      assertThat(message.getPayload(), instanceOf(PartsSalesOpenRootElement.class));
    });

    pollingChannel.send(new GenericMessage&lt;&gt;(&quot;&quot;));
  }
}
</code></pre>
<p>But I am always getting an error, that on line:</p>
<blockquote>
<p>mockIntegrationContext.substituteMessageHandlerFor(&quot;bulkEndpoint&quot;, mockHandler);</p>
</blockquote>
<pre><code>org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'bulkEndpoint' is expected to be of type 'org.springframework.integration.endpoint.IntegrationConsumer' but was actually of type 'org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler'
</code></pre>
<p>Am I doing something wrong here? I am assuming I have a problem with IntegrationFlow itself, or maybe my testing approach is a problem.</p>
",https://stackoverflow.com/questions/65306758/spring-integration-testing-of-outbound-http-enpoint,"['java', 'spring', 'spring-integration', 'spring-integration-dsl', 'spring-integration-http']",452,True,3,1
Flutter integration testing and Gitlab CI/CD,"<p>I'm trying to setup CI/CD for my Flutter app using Fastlane and GitLab based on <a href=""https://medium.com/appditto/automate-your-flutter-workflow-using-gitlab-ci-cd-and-fastlane-5872e758165a"" rel=""nofollow noreferrer"">this tutorial</a>, however I'm having some difficulty automating Flutter integration tests using Flutter driver. The problem I'm encountering is that when all tests are completed successfully, application instance keeps being alive (as in, there's no exit code), which means no further script in Gitlab stage is executed. For example, when tests fail, the message I receive is:</p>
<pre><code>Unhandled exception:
Dummy exception to set exit code.
Stopping application instance.
Driver tests failed: 255 
</code></pre>
<p>I receive exit code 255, which I assume Gitlab Runner will recognise as fail and stop further stages (build and deploy) from being executed?</p>
<p>However if tests pass all I get is:
<code> 00:05 +3: All tests passed!</code>, and application seems to be still running.</p>
<p>I am using <code>tearDownAll</code> function but it doesn't seem to help:</p>
<pre><code>tearDownAll(() async {
      if (driver != null){
        await driver.close();
      }
    }); 
</code></pre>
<p>Adding <code>exit(0)</code> or <code>exit(255)</code> in <code>tearDownAll</code> does close instance correctly, however I have now way of reading if tests passed/failed so I could set exit code as 0/255. Has anyone dealt with integration testing and GitLab CI/CD before or has encountered a similar issue with Flutter Driver?</p>
",https://stackoverflow.com/questions/64122374/flutter-integration-testing-and-gitlab-ci-cd,"['flutter', 'gitlab', 'gitlab-ci', 'flutter-test', 'flutterdriver']",1606,True,2,1
Setting up ngrx/data for integration testing,"<p>I am trying to set up an integration test which will grab some data from a backend API service using ngrx/data entities.</p>

<p>I have this StackBlitz set up: <a href=""https://stackblitz.com/edit/ngrxdata-testing-not-working-pxfmkb?file=src/main.ts"" rel=""nofollow noreferrer"">https://stackblitz.com/edit/ngrxdata-testing-not-working-pxfmkb?file=src/main.ts</a></p>

<p>It should run tests on startup - there are no expectations in my test cases, however I am looking in the console logs and expecting it to show the log in <code>ClientDataService</code> (<code>/src/app/data/client/client-data.service.ts</code>), that is:</p>

<p><code>console.log('never goes here :(');</code></p>

<p>In the integration test (data.integration.spec.ts) I am configuring the module, defining the Client entity type and including the <code>AppDataServiceModule</code> which in turn does this:</p>

<pre><code>import { NgModule } from '@angular/core';
import { ClientDataService } from './client/client-data.service';
import { EntityDataService, EntityDefinitionService } from '@ngrx/data';

@NgModule({
  providers: [
    ClientDataService,
  ],
})
export class AppDataServiceModule {
  constructor(
    entityDataService: EntityDataService,
    clientDataService: ClientDataService
  ) {
    entityDataService.registerService('Client', clientDataService);
  }
}
</code></pre>

<p>As you can see I am registering the data service as suggested by the ngrx docs, <a href=""https://ngrx.io/guide/data/entity-dataservice#a-custom-dataservice"" rel=""nofollow noreferrer"">here</a></p>

<p>I feel like I am pretty close but just need a nudge in the right direction to get it working!</p>
",https://stackoverflow.com/questions/61034426/setting-up-ngrx-data-for-integration-testing,"['javascript', 'angular', 'ngrx', 'ngrx-data']",358,True,2,1
Tool for Integration Testing Gnome-Shell Extensions?,"<p>Is there a tool for helping to automate integration tests for Gnome Shell extensions?</p>

<p>In web development, it's common to use tools like <a href=""https://en.wikipedia.org/wiki/Selenium_(software)"" rel=""nofollow noreferrer"">Selenium</a> to simulate a human interaction by programmatically interacting with a web browser and confirming functionality.</p>

<p>Is there anything similar for scripting interactions in Gnome and Gnome Shell?</p>

<p>I maintain an open source Gnome Shell extension, where most of the functionality is in the form of GUI elements exposed in the panel. Unfortunately, it's common for user-submitted bug fixes to contain regressions. A major pain point are new Gnome releases, which are frequent and often contain backwards incompatible changes whose effects can be subtle.</p>

<p>I currently have some minimal automated testing to confirm the installation process works, but it doesn't catch many feature bugs. All real testing has to be done manually, which is very tedious and time consuming, even though the nature of the tests isn't complicated. It's also difficult to test a new version of Gnome, as that requires installing it system wide, which often isn't practical.</p>

<p>To speed up development and reduce the workload of myself and other volunteer testers, I'd like to write some automated tests in something like Docker that install the extension in a specific version of Gnome, restart Gnome Shell, confirm the GUI elements are present, click a button, confirm a preference dialog appears, etc.</p>

<p>Is this possible?</p>
",https://stackoverflow.com/questions/60618135/tool-for-integration-testing-gnome-shell-extensions,"['automated-tests', 'integration-testing', 'ui-automation', 'gnome-shell', 'gnome-shell-extensions']",201,True,2,1
Integration Testing for manual Spring Security Login,"<p>I am trying to do an integration test for my manual Spring Security Login. Below is the test class:</p>
<pre><code>@RunWith(SpringRunner.class)
@ContextConfiguration
@WebAppConfiguration
@SpringBootTest
@DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD)
class UserIT {


    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private WebApplicationContext context;

    @Autowired
    private TestRestTemplate restTemplate;

    @LocalServerPort
    private int port;

    UserDTO userDTO = new UserDTO();
    String username = &quot;user&quot;;
    Authorities userAuthorities = new Authorities();
    Set&lt;Authorities&gt; grantedAuthorities = new HashSet&lt;&gt;();

    @BeforeEach
    void setup() {

        mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply(springSecurity())
                .build();

        userDTO.setUsername(username);
        userDTO.setPassword(username);

        userAuthorities.setUsername(username);
        userAuthorities.setAuthority(&quot;ROLE_USER&quot;);
        grantedAuthorities.add(userAuthorities);
        userDTO.setAuthorities(grantedAuthorities);


    }

    @Test
    void userLogin() throws Exception {

        mockMvc.perform(post(&quot;/user/register/&quot;)
                .contentType(&quot;application/json&quot;)
                .content(objectMapper.writeValueAsString(userDTO)))
                .andExpect(status().isOk());

        mockMvc.perform(post(&quot;/user/login/&quot;)
                .contentType(&quot;application/json&quot;)
                .content(objectMapper.writeValueAsString(userDTO)))
                .andExpect(status().isOk());

        Collection&lt;GrantedAuthority&gt; authorities = new HashSet&lt;&gt;();
        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(&quot;ROLE_USER&quot;);
        authorities.add(simpleGrantedAuthority);

        MvcResult mvcResult = mockMvc.perform(get(&quot;/user/authority/&quot;)
                .contentType(&quot;application/json&quot;))
                .andReturn();


        assertEquals(authorities, mvcResult.getResponse().getContentAsString());
    }

}
</code></pre>
<p>The issue is that <code>mvcResult.getResponse().getContentAsString()</code> returns a collection of ROLE_ANONYMOUS instead of ROLE_USER, since I am calling the login endpoint with a ROLE_USER authority user.</p>
<p>Below is my UserService class:</p>
<pre><code>@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;
    private final AuthenticationManager authenticationManager;

    public UserDetails loadUserByUsername(String username){
        Users user = userRepository.findByUsername(username);
        if (user == null)
            throw new UsernameNotFoundException(&quot;Username Not Found&quot;);

        UserDetails springUser =
                org.springframework.security.core.userdetails.User.builder()
                .authorities(this.getAuthorities(user))
                .username(username)
                .password(user.getPassword())
                .build();

        return springUser;
    }

    public Collection&lt;? extends GrantedAuthority&gt; getAuthoritiesFromContext(){
        Collection&lt;SimpleGrantedAuthority&gt; authorities = (Collection&lt;SimpleGrantedAuthority&gt;)
                SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        return authorities;
    }

    public Collection&lt;? extends GrantedAuthority&gt; getAuthorities(Users user){
        Collection&lt;SimpleGrantedAuthority&gt; authorities = new ArrayList&lt;&gt;();
        user.getAuthorities().forEach(authority -&gt;
                authorities.add(new SimpleGrantedAuthority(authority.getAuthority())));
        return authorities;
    }

    public Users saveUser(UserDTO userDTO){
        Users user = new Users(userDTO.getUsername(), userDTO.getPassword(),
                userDTO.getAuthorities());
        return userRepository.save(user);
    }

    public UserDetails login(UserDTO userDTO){
        UserDetails userDetails = this.loadUserByUsername(userDTO.getUsername());
        if(userDetails.getPassword().equals(userDTO.getPassword())){
            Authentication authentication =
                    new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDTO.getPassword(), userDetails.getAuthorities());

            authentication = authenticationManager.authenticate(authentication);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return userDetails;
        } else {
            throw new BadCredentialsException(&quot;Username and password do not match!&quot;);
        }
    }

}
</code></pre>
<p>When I try calling the endpoints through Postman it all works correctly, however in the test, somehow the SecurityContext gets lost and returns ROLE_ANONYMOUS instead of ROLE_USER. Am I missing some annotation in the test class, or is it just that I cannot do an integration test for my manual login?</p>
<p>Thanks in advance!!</p>
",https://stackoverflow.com/questions/64142047/integration-testing-for-manual-spring-security-login,"['spring-boot', 'spring-security', 'integration-testing', 'security-context']",124,False,1,0
Integration testing: verifty anything that gets passed,"<p>For my Asp.Net Core application, I am writing integration tests using nUnit framework with Moq.</p>
<p>I have services (Mega Services) that are working with multiple other services (Tiny Services).<br />
For instance I have a Mega Service called <strong>WorkflowService</strong> that calls two tiny services : <strong>StepService</strong> and <strong>HistoryService</strong>.</p>
<p>I am writing an integration test to make sure proper methods of <strong>StepService</strong> and <strong>Historyservice</strong> are always being called by <strong>WorkflowService</strong>.</p>
<p>The problem is that the data which <strong>WorkflowService</strong> passes to my tiny services needs calculation and typecasting. Those works are handled in separate Unit Tests (using Moq for simulation) and I do not want to repeat them again here. I just want to check if the tiny services' methods are called or not. Actually I do not care about the input data here.</p>
<p>As far as I know, when we use <code>Verify</code> method of a <code>Mock</code> object, we should pass the parameters as well.</p>
<p>Is there some workaround by which I can ask the <code>Verify</code> method just to check the method invocation and not the input data?</p>
<p>Somehow it should ignore the input, or just check the type (and not the object reference) so that I can pass any data to it without being concerned about the validity of the input.</p>
",https://stackoverflow.com/questions/63240749/integration-testing-verifty-anything-that-gets-passed,"['c#', 'asp.net-core', 'nunit', 'integration-testing', 'moq']",70,True,0,1
Integration testing user update controller with MockMvc,"<p>I am trying to test to see if the logic behind the user update controller is functioning correctly by creating some simple integration tests using MockMvc. </p>

<p>I am updating users credentials, for security reasons the password doesn't get returned in the response dto, this way I can limit the amount a password is exchanged from the client and the server.</p>

<p>The problem is, how do I test that the password was actually updated before the test is rolled back? </p>

<p>I tried manually performing a login before the test is finished, and if the login fails with the original credentials, the password was updated.</p>

<p>The simple part of the test is straight forward:</p>

<pre><code>@Test
  void WhenUserIsAdmin_UserCanUpdateAllFields() throws Exception {

    updatedUser.setPassword(""newPassword"");

    String jsonString = mapper.writeValueAsString(updatedUser);

    MockHttpServletRequestBuilder builder = TestRequestFactory.authorizationFactoryPUT(URI, ""admin"");
    mockMvc.perform(builder.contentType(MediaType.APPLICATION_JSON).content(jsonString))
        .andExpect(status().isOk())
        .andExpect(MockMvcResultMatchers.jsonPath(""$.firstName"").value(""admin2""))
        .andExpect(MockMvcResultMatchers.jsonPath(""$.surnamePaternal"").value(""admin2""))
        .andExpect(MockMvcResultMatchers.jsonPath(""$.surnameMaternal"").value(""admin2""))
        .andExpect(MockMvcResultMatchers.jsonPath(""$.roleName"").value(""User""))
        .andExpect(MockMvcResultMatchers.jsonPath(""$.roleType"").value(""ROLE_USER""))
        .andExpect(MockMvcResultMatchers.jsonPath(""$.created"").isNotEmpty());
  }
</code></pre>

<p>and the Factory looks like this</p>

<pre><code>public static MockHttpServletRequestBuilder authorizationFactoryPUT(String url, String user)
      throws JsonProcessingException {
    return MockMvcRequestBuilders.put(url)
        .header(HttpHeaders.AUTHORIZATION, doLogin(user, user));
  }

static String doLogin(String user, String pass) throws JsonProcessingException {
    LoginRequest loginRequest = new LoginRequest(user, pass);
    String resultAsJsonString = restTemplate.postForEntity(loginServer + ""/login"", loginRequest, String.class).getBody();
    LoginResponse loginResponse = mapper.readValue(Objects.requireNonNull(resultAsJsonString), LoginResponse.class);
    return loginResponse.getTokenType() + "" "" + loginResponse.getAccessToken();
  }
</code></pre>

<p>and inside of the same test I tried </p>

<pre><code>LoginRequest loginRequest = new LoginRequest(user, pass);
String resultAsJsonString = restTemplate.postForEntity(loginServer + ""/login"", loginRequest, String.class).getBody();
LoginResponse loginResponse = mapper.readValue(Objects.requireNonNull(resultAsJsonString), LoginResponse.class);
</code></pre>

<p>and if the response fails whilst mapping or the http response code is a 401. Then all is ok, but it seems like the data is never persisted to the database. </p>
",https://stackoverflow.com/questions/60657599/integration-testing-user-update-controller-with-mockmvc,"['spring', 'integration-testing', 'mockmvc']",563,True,0,1
Integration testing in .net core api 3.1,"<p>I am trying to implement integration testing for each API that i have developed in .Net core 3.1 and have followed   <a href=""https://learn.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/test-aspnet-core-services-web-apps"" rel=""nofollow noreferrer"">this link</a>      to create test cases for it.        </p>

<p>Please find the below test class that i have created for my API.</p>

<p><a href=""https://i.stack.imgur.com/V84Xg.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/V84Xg.png"" alt=""enter image description here""></a></p>

<p>But while executing i am getting error in this line <code>_server = new TestServer(new WebHostBuilder()
           .UseStartup&lt;Startup&gt;());</code>  which is as below :</p>

<p><a href=""https://i.stack.imgur.com/KDFhW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/KDFhW.png"" alt=""Error""></a></p>

<p>Am i missing anything here ?</p>
",https://stackoverflow.com/questions/61577778/integration-testing-in-net-core-api-3-1,"['.net', 'asp.net-core', '.net-core', 'integration-testing', 'asp.net-core-testhost']",220,True,0,1
Integration testing authenticated network requests with jest,"<p>I'm trying to set up some integration tests using Jest and React testing library, but I would like to use <a href=""https://github.com/Netflix/pollyjs"" rel=""nofollow noreferrer"">PollyJS</a> to record and replay actual network requests via my local dev server instead of mocking. The first step would be getting my network requests working against my local dev server.</p>

<p>This would be pretty simple with an endpoint that is meant to be publicly consumable, meaning one does not need to login to an account in order to get an authorized response. But I've been having trouble figuring out how I can make an endpoint that requires authentication.</p>

<p>Here's a example test where the <code>POST</code> request is made to my login endpoint that will set a cookie with an auth token.</p>

<p>The component <code>MyDataFetchingComponent</code> will do a request to an endpoint that will load data only if the user is authenticated. If it is successful, the component will render <code>'data loaded!</code>.</p>

<pre><code>import { MyDataFetchingComponent } from ""../MyDataFetchingComponent"";
import { render, waitForElementToBeRemoved } from ""@testing-library/react"";

test(""render"", async () =&gt; {
  await fetch(""http://localhost:3000/api/login"", {
    method: ""POST"",
    headers: {
      ""content-type"": ""application/json"",
    },
    body: JSON.stringify({
      username: ""myusername"",
      password: ""password"",
    }),
    credentials: ""omit"",
  });

  const { getByText } = render(&lt;MyDataFetchingComponent /&gt;);
  getByText(""loading"");
  await waitForElementToBeRemoved(() =&gt; getByText(""loading""));
  getByText(""data loaded!"");
});
</code></pre>

<p>I thought because jest uses jsdom as its test environment, that this would behave similarly to how it does in the browser, but it doesn't seem to be the case. The data fetching request gets back a 401 error I set up if the user isn't authenticated.</p>
",https://stackoverflow.com/questions/62240087/integration-testing-authenticated-network-requests-with-jest,"['reactjs', 'jestjs', 'react-testing-library', 'jsdom', 'pollyjs']",529,False,0,0
Azure continuous integration testing fails with System.OperationCanceledException error,"<p>I have this netcore 3.1 C# Web application that we setup a batch of integration tests. The tests pass when run locally, but a few keep failing when run on the CI server with the <code>System.OperationCanceledException</code> error.</p>
<p>Here is log for the CI testing environment:</p>
<pre><code>==============================================================================
Task         : Visual Studio Test
Description  : Run unit and functional tests (Selenium, Appium, Coded UI test, etc.) using the Visual Studio Test (VsTest) runner. Test frameworks that have a Visual Studio test adapter such as MsTest, xUnit, NUnit, Chutzpah (for JavaScript tests using QUnit, Mocha and Jasmine), etc. can be run. Tests can be distributed on multiple agents using this task (version 2).
Version      : 2.170.1
Author       : Microsoft Corporation
Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/test/vstest
==============================================================================
SystemVssConnection exists true
SystemVssConnection exists true
Running tests using vstest.console.exe runner.
======================================================
Test selector : Test assemblies
Test filter criteria : null
Search folder : Z:\a\1\s
Action when minimum tests threshold not met : donothing
Minimum tests expected to be run: 0
VisualStudio version selected for test execution : 16.0
Attempting to find vstest.console from a visual studio installation with version [15.0,17.0).
Run in parallel : true
Run in isolation : false
Path to custom adapters : null
Other console options : null
Code coverage enabled : false
Diagnostics enabled : true
SystemVssConnection exists true
Run the tests locally using vstest.console.exe
========================================================
Source filter: **\*Test.dll,**\*TestIntegration.dll,!**\*TestAdapter.dll,!**\obj\**,!**\submodules\**
SystemVssConnection exists true
[command]Z:\a\_tasks\VSTest_ef087383-ee5e-42c7-9a53-ab56c98420cc\2.170.1\Modules\DTAExecutionHost.exe --inputFile D:\a\_temp\input_eedfb280-073a-11eb-bdb8-5118fbbc2831.json
======================================================
##########################################################################
DtaExecutionHost version 18.170.30112.1.
Starting TestExecution Model...
Result Attachments will be stored in LogStore
Run Attachments will be stored in LogStore
Result Attachments will be stored in LogStore
Result Attachments will be stored in LogStore
Run Attachments will be stored in LogStore
Updated Run Settings:
&lt;RunSettings&gt;
  &lt;RunConfiguration&gt;
    &lt;MaxCpuCount&gt;0&lt;/MaxCpuCount&gt;
    &lt;BatchSize&gt;1000&lt;/BatchSize&gt;
    &lt;ResultsDirectory&gt;Z:\c\_temp\TestResults&lt;/ResultsDirectory&gt;
  &lt;/RunConfiguration&gt;
  &lt;DataCollectionRunSettings&gt;
    &lt;DataCollectors&gt;
      &lt;DataCollector friendlyName=&quot;blame&quot; enabled=&quot;True&quot;&gt;
        &lt;Configuration&gt;
          &lt;ResultsDirectory&gt;Z:\c\_temp\TestResults&lt;/ResultsDirectory&gt;
          &lt;CollectDump /&gt;
          &lt;CollectDump /&gt;
        &lt;/Configuration&gt;
      &lt;/DataCollector&gt;
    &lt;/DataCollectors&gt;
  &lt;/DataCollectionRunSettings&gt;
  &lt;LoggerRunSettings&gt;
    &lt;Loggers&gt;
      &lt;Logger friendlyName=&quot;blame&quot; enabled=&quot;True&quot; /&gt;
    &lt;/Loggers&gt;
  &lt;/LoggerRunSettings&gt;
&lt;/RunSettings&gt;
</code></pre>
<p>The raw log that shows the exception is as below:</p>
<pre><code>Error Message:
 System.OperationCanceledException : The operation was canceled.
Stack Trace:
   at System.Threading.CancellationToken.ThrowOperationCanceledException()
 at System.IO.Pipelines.Pipe.ReadAsync(CancellationToken token)
 at System.IO.Pipelines.Pipe.DefaultPipeReader.ReadAsync(CancellationToken cancellationToken)
 at Microsoft.AspNetCore.TestHost.ResponseBodyReaderStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
 at System.IO.Stream.CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
 at System.Net.Http.HttpContent.LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer)
 at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
</code></pre>
",https://stackoverflow.com/questions/64217935/azure-continuous-integration-testing-fails-with-system-operationcanceledexceptio,"['multithreading', 'continuous-integration', 'xunit']",205,False,2,0
DataBase Testing By using Autowire in Integration Testing,"<p>I am new to DataBase testing and I am trying to Connect the database by using tag @SpringBootTest in class level and by using Autowire, It is not creating instantiation getting always null</p>

<pre class=""lang-java prettyprint-override""><code>@SprintBootTest
 Class  Test{
@Autowire
     DatabaseService databaseService;

}

</code></pre>

<p>Can anyone suggest please? If any one did similar like this , can you please give me the instructions </p>
",https://stackoverflow.com/questions/59572795/database-testing-by-using-autowire-in-integration-testing,"['java', 'spring-boot', 'cucumber', 'integration-testing', 'autowired']",140,True,2,1
Express mongoDB Integration testing for private/secured routes,"<p>I am trying to run a integration test for one of the express routes in the application.</p>
<p>The routed is a protected route allows user to create supplier when user is authenticated.</p>
<p>I am trying to login user before making a request to the 'api/v1/supplier' (protected route) route but not able to login user before calling the Login API give 500 error back, the Login API is working as expected when tested separately.</p>
<p>Here is the test that I am trying. request help!</p>
<pre><code>process.env.NODE_ENV = 'development';

const expect = require('chai').expect;
const request = require('supertest');

const app = require('../../../app.js');
const conn = require('../../../db/index.js');

describe('POST /api/v1/supplier ', () =&gt; {
  let token = '';

  before(done =&gt; {
    conn
      .connect()
      .then(done())
      .catch(err =&gt; done(err));
  });

  after(done =&gt; {
    conn
      .close()
      .then(done())
      .catch(err =&gt; done(err));
  });

  it('Error, on unauthorized POST Supplier request', done =&gt; {
    request(app)
      .post('/api/v1/users/login')
      .send({ email: 'sgrmhdk00@gmail.com', password: '12345678' })
      .end(function(err, res) {
        token = res.body.token;
      });

    request(app)
      .post('/api/v1/supplier')
      .set('Authorization', 'Bearer' + token)
      .send({ supplierID: '1234567' })
      .then(res =&gt; {
        const body = res.body;
        expect(body).to.contain.property('status');
        expect(body).to.contain.property('error');
        done();
      })
      .catch(err =&gt; done(err));
  });
});

</code></pre>
<p>db/index.js</p>
<pre><code>const dotenv = require('dotenv');
const mongoose = require('mongoose');
const DB_URI = 'mongodb://localhost:27017/myapp';

function connect() {
  return new Promise((resolve, reject) =&gt; {
    dotenv.config({ path: './config.env' });
    const setDatabase = () =&gt; {
      if (process.env.NODE_ENV === 'development') {
        const DB = process.env.DATABASE;
        return DB;
      } else {
        const DB = process.env.DATABASE_PRODUCTION.replace(
          '&lt;PASSWORD&gt;',
          process.env.DATABASE_PASSWORD
        );
        return DB;
      }
    };

    const DB = setDatabase();

    mongoose
      .connect(DB, {
        useNewUrlParser: true,
        useCreateIndex: true,
        useFindAndModify: false
      })
      .then(() =&gt; console.log('DB connection successful!'));
  });
}

function close() {
  return mongoose.disconnect();
}

module.exports = { connect, close };

</code></pre>
",https://stackoverflow.com/questions/65428589/express-mongodb-integration-testing-for-private-secured-routes,"['mongodb', 'express', 'mocha.js', 'chai']",27,False,0,1
Integration testing for ChangeEmailAsync in .net core 3.1,"<p>I am trying to write Integration test case for change EmailID. </p>

<h2>cshtml.cs file</h2>

<pre><code>var token = await _userManager.GenerateChangeEmailTokenAsync(user, Input.Email);
var changeEmailResult = await _userManager.ChangeEmailAsync(user, Input.Email, token);

[Fact]
public async Task OnPostUpdateEmailAsync_WithValidInput_ShouldReturnSuccessMessage()
{
    await _client.LoginAsync(""test1@test.com"", TestData.AlicePassword);

    var response = await _client.SubmitAsync(""./OnPostUpdateEmailAsync"", new
        {
            Email = ""testemail@test.com"",
            Password_ChangeEmail = ""Password1""
        });

    response.AssertOnPage(""./ChangeEmailPassword/UpdateEmail"");
    response.EnsureSuccessStatusCode();

    var document = await response.GetDocument();
    document.QuerySelectorAll("".alert-success"")
        .AssertCount(1)
        .AssertHasTextEqual(
            $""The email address has been changed successfully."");
}

[Fact]
public async Task OnPostResetPasswordAsync_WithWrongConfirmPassword_ShouldReturnErrorMessage()
{
    await _client.LoginAsync(TestData.AliceEmail, TestData.AlicePassword);

    var response = await _client.SubmitAsync(""./ChangeEmailPassword/OnPostResetPasswordAsync"", new
        {
            OldPassword = ""OldPassword1"",
            Password = ""NewPassword1"",
            ConfirmPassword = ""NewPassword1""
        });

    response.AssertOnPage(""./ChangeEmailPassword/ResetPassword"");
    response.EnsureSuccessStatusCode();

    var document = await response.GetDocument();
    document.QuerySelectorAll("".alert-danger"")
        .AssertCount(1)
        .AssertHasTextEqual($""Error: The passwords do not match."");
    }
</code></pre>

<p>It is working fine but after executing this, all other test case is getting failed. As i can assume we are changing email id here but for others it still look for old email id. May be i am wrong here. Requesting you all, please help me in this.</p>
",https://stackoverflow.com/questions/61594190/integration-testing-for-changeemailasync-in-net-core-3-1,"['asp.net-mvc', '.net-core-3.1']",64,False,0,0
Controller integration testing with nestJS using different guards,"<p>I am trying to develop an application using NestJs as the backend framework. Currently I am writing some integration tests for the controllers.</p>
<p>This is my first project using typescript, I usually use Java/Spring but I wanted to learn and give nestJs a try.</p>
<p>I use different guards to access rest endpoints. In this case I have an <strong>AuthGuard</strong> and <strong>RolesGuard</strong></p>
<p>To make the rest endpoint work I just add something like this in the TestingModuleBuilder:</p>
<pre><code>        .overrideGuard(AuthGuard())
        .useValue({ canActivate: () =&gt; true })
</code></pre>
<p>The point is, is it possible to define or override this guards for each test to check that the request should fail if no guard or not allowed guard is defined?</p>
<p>My code for the test is the following one:</p>
<pre><code>describe('AuthController integration tests', () =&gt; {
let userRepository: Repository&lt;User&gt;
let roleRepository: Repository&lt;Role&gt;
let app: INestApplication
beforeAll(async () =&gt; {
    const module = await Test.createTestingModule({
        imports: [
            AuthModule,
            TypeOrmModule.forRoot(typeOrmConfigTest),
            PassportModule.register({ defaultStrategy: 'jwt' }),
            JwtModule.register({
                secret: jwtConfig.secret,
                signOptions: {
                    expiresIn: jwtConfig.expiresIn
                }
            })
        ]
    })
        .overrideGuard(AuthGuard())
        .useValue({ canActivate: () =&gt; true })
        .overrideGuard(RolesGuard)
        .useValue({ canActivate: () =&gt; true })
        .compile()
    app = module.createNestApplication()
    await app.init()

    userRepository = module.get('UserRepository')
    roleRepository = module.get('RoleRepository')

    const initializeDb = async () =&gt; {
        const roles = roleRepository.create([
            { name: RoleName.ADMIN },
            { name: RoleName.TEACHER },
            { name: RoleName.STUDENT }
        ])
        await roleRepository.save(roles)
    }

    await initializeDb()
})

afterAll(async () =&gt; {
    await roleRepository.query(`DELETE FROM roles;`)
    await app.close()
})

afterEach(async () =&gt; {
    await userRepository.query(`DELETE FROM users;`)
})

describe('users/roles (GET)', () =&gt; {
    it('should retrieve all available roles', async () =&gt; {
        const { body } = await request(app.getHttpServer())
            .get('/users/roles')
            .set('accept', 'application/json')
            .expect('Content-Type', /json/)
            .expect(200)

        expect(body).toEqual(
            expect.arrayContaining([
                {
                    id: expect.any(String),
                    name: RoleName.STUDENT
                },
                {
                    id: expect.any(String),
                    name: RoleName.TEACHER
                },
                {
                    id: expect.any(String),
                    name: RoleName.ADMIN
                }
            ])
        )
    })
})
</code></pre>
",https://stackoverflow.com/questions/64833176/controller-integration-testing-with-nestjs-using-different-guards,"['javascript', 'typescript', 'testing', 'jestjs', 'nestjs']",712,True,0,1
Integration testing in Grails 3.3.11 does not rollback,"<p>I am using Grails 3.3.11 and I have a problem with my integration tests. It happens that the tests are done, everything is fine, but the data is accumulating in the database. I've tried several things, like using the @Rollback annotation, but it's not happening. There is a lot of garbage in the database. Can you help me? What am I doing wrong. I can't stop the test of saving data in the database. I wanted the Rollback to be automatic.</p>
<pre><code>import org.springframework.test.annotation.Rollback

@Integration
@grails.transaction.Rollback
class CmbIdControllerSpec extends Specification {
    @Value('${local.server.port}')
    Integer serverPort
    String accessToken
    String baseUrl
    JSONObject documentPropertiesForTesting
    JSONObject documentForTesting
    String partTest
    String userTest
    String typeIdTest
    String documentIdTest
    def sessionFactory
    def controller

    void setup(){
        baseUrl = &quot;http://localhost:${serverPort}/cmbid/api/v1&quot;
        partTest = &quot;partTest&quot;
        accessToken = &quot;Bearer examplefXk&quot;
    }

    void &quot;Saving a new and valid document properties&quot;() {
        given:
            documentPropertiesForTesting = createNewTestDocumentProperties()
            typeIdTest = documentPropertiesForTesting.get(&quot;message&quot;).toString().substring(20,52)

        expect:
            documentPropertiesForTesting.get(&quot;status&quot;) == &quot;ok&quot;
            documentPropertiesForTesting.get(&quot;message&quot;).contains(&quot;properly saved!&quot;)

    }

@Rollback
def createNewTestDocumentProperties(){
    CloseableHttpClient httpClient = HttpClients.createDefault();
    def httpPost = setHttpPost(baseUrl + &quot;/parts/${partTest}/metas&quot;)

    JSONObject entireBody = new JSONObject()
    entireBody.accumulate(&quot;highlights&quot;,setHighlightsDP())
    entireBody.accumulate(&quot;screens&quot;, setScreensDP())
    entireBody.accumulate(&quot;photo&quot;, &quot;&quot;)
    entireBody.accumulate(&quot;style&quot;, setStyleDP())

    StringEntity jsonBody = new StringEntity(entireBody.toString())
    httpPost.setEntity(jsonBody)

    CloseableHttpResponse httpResponse = httpClient.execute(httpPost)
    JSONObject responseBody = new JSONObject(EntityUtils.toString(httpResponse.getEntity()))

    httpClient.close()

    return responseBody
}
</code></pre>
",https://stackoverflow.com/questions/64071871/integration-testing-in-grails-3-3-11-does-not-rollback,['grails'],82,False,0,1
do not create spring bean during integration testing,"<p>I have a Spring Config class which I want to have it loaded when the application is running.</p>
<pre><code>@Configuration
public class EventHubConfiguration {


    @Bean
    @ConfigurationProperties(...)
    public EventHubClient someClient(final String namespace,
                                     final String eventHubName,
                                     final String sasKeyName,
                                     final String sasKey) throws IOException, EventHubException {
        ConnectionStringBuilder connStr = new ConnectionStringBuilder()
                .setNamespaceName(namespace)
                .setEventHubName(eventHubName)
                .setSasKeyName(sasKeyName)
                .setSasKey(sasKey);
        return EventHubClient.createSync(connStr.toString(), Executors.newSingleThreadScheduledExecutor());
    }
}
</code></pre>
<p>But how can I prevent it from loading when my integration tests are running. For example when I do <code>mvn clean test</code> or as part of my build. I don't wish the eventhub client to be created during my integration testing.</p>
",https://stackoverflow.com/questions/64008070/do-not-create-spring-bean-during-integration-testing,"['java', 'spring', 'spring-boot']",242,False,-1,1
Integration testing an HTTP server with ZIO test suite,"<p>I am trying to figure out the idiom for writing an integration test for an Http4s app that supports two end points.
I'm starting the <code>Main</code> app class in a <code>ZManaged</code> by forking it on a new fiber and then doing interruptFork on release of the <code>ZManaged</code>.
I then convert this to a <code>ZLayer</code> and pass it via <code>provideCustomLayerShared()</code> on the whole <code>suite</code> that has multiple <code>testM</code>s .</p>
<ol>
<li>Am I on the right track here?</li>
<li>It doesn't behave as I expect it to :</li>
</ol>
<ul>
<li>Although the httpserver managed in the way mentioned is provided to the suite that encloses both the tests, it is released after the first test and thus the second test fails</li>
<li>The test suite never finishes and just hangs after executing both tests</li>
</ul>
<p>Apologies for the half baked nature of the code below.</p>
<pre><code>object MainTest extends DefaultRunnableSpec {

  def httpServer =
    ZManaged
      .make(Main.run(List()).fork)(fiber =&gt; {
        //fiber.join or Fiber.interrupt will not work here, hangs the test
        fiber.interruptFork.map(
          ex =&gt; println(s&quot;stopped with exitCode: $ex&quot;)
        )
      })
      .toLayer

  val clockDuration = 1.second

  //did the httpserver start listening on 8080?
  private def isLocalPortInUse(port: Int): ZIO[Clock, Throwable, Unit] = {
    IO.effect(new Socket(&quot;0.0.0.0&quot;, port).close()).retry(Schedule.exponential(clockDuration) &amp;&amp; Schedule.recurs(10))
  }

  override def spec: ZSpec[Environment, Failure] =
    suite(&quot;MainTest&quot;)(
      testM(&quot;Health check&quot;) {
        for {
          _ &lt;- TestClock.adjust(clockDuration).fork
          _ &lt;- isLocalPortInUse(8080)
          client &lt;- Task(JavaNetClientBuilder[Task](blocker).create)
          response &lt;- client.expect[HealthReplyDTO](&quot;http://localhost:8080/health&quot;)
          expected = HealthReplyDTO(&quot;OK&quot;)
        } yield assert(response) {
          equalTo(expected)
        }
      },
      testM(&quot;Distances endpoint check&quot;) {
        for {
          _ &lt;- TestClock.adjust(clockDuration).fork
          _ &lt;- isLocalPortInUse(8080)
          client &lt;- Task(JavaNetClientBuilder[Task](blocker).create)
          response &lt;- client.expect[DistanceReplyDTO](
            Request[Task](method = Method.GET, uri = uri&quot;http://localhost:8080/distances&quot;)
              .withEntity(DistanceRequestDTO(List(&quot;JFK&quot;, &quot;LHR&quot;)))
          )
          expected = DistanceReplyDTO(5000)
        } yield assert(response) {
          equalTo(expected)
        }
      }
    ).provideCustomLayerShared(httpServer)
}
</code></pre>
<p>Output of the test is that the second test fails while the first succeeds.
And I debugged enough to see that the HTTPServer is already brought down before the second test.</p>
<pre><code>stopped with exitCode: ()
- MainTest
  + Health check
  - Distances endpoint check
    Fiber failed.
    A checked error was not handled.
    org.http4s.client.UnexpectedStatus: unexpected HTTP status: 404 Not Found
</code></pre>
<p>And whether I run the tests from Intellij on sbt testOnly, the test process keeps hung after all this and I have to manually terminate it.</p>
",https://stackoverflow.com/questions/64060580/integration-testing-an-http-server-with-zio-test-suite,"['scala', 'integration-testing', 'http4s', 'zio']",1139,True,4,2
Jenkins jobs for spring boot application with Integration testing,"<p>The following is my scenario.</p>

<p>I have my application which is built on Spring boot with embedded tomcat server. In my application, I have unit tests as well as integration tests.</p>

<p>First I want to build my application as a maven package (jar) which will cover all the unit tests and then the next step is to run the jar file as spring boot application ((java -jar myapplication.jar) which will start the tomcat server. As a final step, I want to run my integration tests on top of the running spring boot application.</p>

<p>To achieve this in Jenkins what is the best solutions.</p>

<ol>
<li><p>Is it possible to have a single Jenkins job and achieve the above scenario? (like in post-build steps to run the generated jar as an application using the command and run the integration test on it)</p></li>
<li><p>Else will create 3 jobs in Jenkins ( one for maven package, the second one for deploying the generated jar file and run the application and third one is for running the integration tests on top of the running application.</p></li>
</ol>

<p>Please suggest the best possible solution.</p>

<p>Thanks in advance. </p>

<p>Bala.</p>
",https://stackoverflow.com/questions/60157677/jenkins-jobs-for-spring-boot-application-with-integration-testing,"['java', 'spring-boot', 'maven', 'jenkins']",1678,False,2,1
Spring integration Testing with Testcontainer - Database starting after Application,"<p>My App under test with spring (core) wants to connect to a database by testcontainer, but the testcontainer is not started at this point. How can I achieve that the testcontainer gets ready and then the whole context ist started up?</p>
<pre><code> import org.junit.jupiter.api.Order;
 import org.junit.jupiter.api.Test;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
 import org.testcontainers.containers.PostgreSQLContainer;
 import org.testcontainers.junit.jupiter.Container;
 import org.testcontainers.junit.jupiter.Testcontainers;

@Testcontainers
@SpringJUnitWebConfig(locations = {&quot;classpath:it-context.xml&quot;})
public class IntegrationTest {


    @Container
    private PostgreSQLContainer postgresqlContainer = new PostgreSQLContainer();

    @Autowired
    private StatusBean status;

    @Test
    public void appStartedSuccessful(){
        // app &amp; database successful started and connected
        System.out.println(postgresqlContainer.getJdbcUrl());
        System.out.println(postgresqlContainer.getTestQueryString());
        System.out.println(status.getStartupTimestamp());
    }

}
</code></pre>
",https://stackoverflow.com/questions/63247905/spring-integration-testing-with-testcontainer-database-starting-after-applicat,"['spring', 'junit5', 'testcontainers']",1029,False,1,3
How to instantiate AngularFireAuth and AngularFirestore for integration testing?,"<p>I'd like to write some Karma/Jasmine tests to make sure my angular backend services are acting as expected, but I'm having trouble getting an instance AngularFireAuth and which I need to pass to the constructor of my various services.</p>

<p>For example the constructor of my AuthService looks like this, and I guess Angular knows how to provide these params somehow for dependency injection, since my app is running as expected.  But for testing, I would really like to have more fined grained ability to call specific methods on my services and confirm that my observables are responding as expected.</p>

<pre><code>constructor(
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,

  ) { ... }
</code></pre>

<p>But I would like to instantiate them by manually, so I can just instantiate my services as instances manually in my test code, without having to rely on a testbed and mocks and spies which is what I keep seeing in the various google results on this subject.  I would like to test against my real Firestore backend, not a mock, sort of like in RubyOnRails where you test against a dev database on the server.</p>

<p>However, I can't figure out how to manually create an instance of AngularFireAuth and AngularFirestore for these tests, so I can provide these to the constructor of my services. Is this possible or am I just barking up wrong tree?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/61741499/how-to-instantiate-angularfireauth-and-angularfirestore-for-integration-testing,"['angular', 'firebase', 'google-cloud-firestore', 'angularfire2']",963,True,1,2
Integration testing for methods annotated with CircuitBreaker not working,"<p>I have a SpringBoot application which has circuitBreaker implemented with annotations. The annotated circuitbreaker is an Aspect so that the client doesnt have to explicitly annotate their methods with the circuitBreaker annotation.When I hit the RequestMapping from the browser in high frequency the circuitbreaker settings are getting applied and the fallback is getting called.</p>
<p>Issue is when I try to test this from the Test class by calling the api using concurrent threads. As the api is down the fallback mechanism kicks in but the config settings of the circuit breaker doesnt come into picture. Also same is the behavior when multiple requests are called from Postman.</p>
",https://stackoverflow.com/questions/62676549/integration-testing-for-methods-annotated-with-circuitbreaker-not-working,"['spring', 'aop', 'spring-boot-test', 'circuit-breaker', 'resilience4j']",254,False,1,0
Cypress PORT is returning undefined in integration testing (visual),"<p>How can I access the Cypress test running port in my test file? I am visual testing my application and I need to test different base URLs in a single script command. So I am planning to use <code>cy.visit(&lt;base_ulr&gt;:&lt;port&gt;')</code> directly in test file. But when I tried to access the PORT using env variable, <code>porcess.env.PORT</code>, its getting undefined. Anyone have any idea about this? Please need some help....</p>
",https://stackoverflow.com/questions/61244915/cypress-port-is-returning-undefined-in-integration-testing-visual,"['testing', 'environment-variables', 'integration-testing', 'port', 'cypress']",485,False,0,1
Google Cloud Functions CI/CD for integration testing(Python)?,"<p>I am developing different Cloud Functions. Most of the functions have Google-Datastore, Pub/Sub and IoT external dependencies. I would like to run integration tests while deploying using <code>cloudbuild.yaml</code>. <br>
I can test the unittest via pytest by having this in the cloudbuild.yaml file</p>

<pre><code>steps:

- name: 'python:3.7'
  entrypoint: 'bash'
  args: 
    - '-c'
    - |
        pip3 install -r requirements.txt
        pytest 

- name: 'gcr.io/cloud-builders/gcloud'
  args:
  - functions
  - deploy
  - My-Function
  - --runtime=python37
  - --source=Soure_Dir
  - --entry-point=main
  - --trigger-topic=My-Function-Topic
  - --region=REGION
</code></pre>

<p>Is there any way of writing integration tests to test datastore, pub/sub, iot in this pipline?
or is there any other way of testing the function locally?<br>
What is the efficient way of testing the cloud-functions?</p>
",https://stackoverflow.com/questions/61251666/google-cloud-functions-ci-cd-for-integration-testingpython,"['google-cloud-platform', 'google-cloud-functions', 'google-cloud-datastore', 'google-cloud-pubsub', 'google-cloud-python']",550,False,1,0
Postgis Spring Boot Integration Testing with index based operator &lt;-&gt;,"<p>I'm currently writing an integration test with spring boot and a Post<strong>gis</strong> connection. In my original application a query uses <a href=""https://postgis.net/workshops/postgis-intro/knn.html#index-based-knn"" rel=""nofollow noreferrer"">the &lt;-&gt; operator</a>. For my tests I used a h2 in-memory database with the <a href=""http://www.h2gis.org/"" rel=""nofollow noreferrer"">h2gis</a> extension. Unfortunately, the &lt;-&gt; is not recognized and throws a syntax error. Do you have any ideas how to do this with an in-memory database or is there only the chance to run a docker container with a proper postgis database running?</p>
<p>Thank you!</p>
",https://stackoverflow.com/questions/64429121/postgis-spring-boot-integration-testing-with-index-based-operator,"['spring-boot', 'spring-data-jpa', 'h2', 'postgis', 'spring-boot-test']",340,True,0,1
React Jest issue when exporting server for integration testing,"<p>Quite simple situation, I am trying to import app.listen(port) for testing purposes. The tests will fail (fail reasons: app.address is not a function &amp; server.close is not a function). Actually the server variable returns an empty object so the import is not done properly and that is the reason why the test cases are failing...</p>

<p>genres.test.js</p>

<pre><code>const request = require(""supertest"");

let server;

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

  describe(""GET /"", () =&gt; {
    it(""should return all genres"", async () =&gt; {
      const res = await request(server).get(""/api/genres"");
      expect(res.status).toBe(200);
    });
  });
});
</code></pre>

<p>index.js</p>

<pre><code>const express = require(""express"");
const app = express();

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

    module.exports = server;
</code></pre>

<p>Am I missing something about the import? 
Let me know if you need the more code lines/parts (note that the index.js I provided is not complete) or if you need the full error message.</p>

<p>I know this question has been already asked several times but in most cases, the solution is just to import app.listen instead of app, which I already did.
I also tried to use export default instead of module.exports.</p>
",https://stackoverflow.com/questions/60321422/react-jest-issue-when-exporting-server-for-integration-testing,"['javascript', 'reactjs', 'testing', 'jestjs', 'supertest']",101,True,0,1
Integration testing for events in the Jersey container listener,"<p>I have an application based on Jersey JAX-RS. I need to refactor the event handler and therefore also write a test for it.</p>

<p>I'm trying to do this with the JerseyTest Framework. I created a configuration to extend ResourceConfig, but when I use the target () call the handler is not called.</p>

<p>I will present the situation using code.
Here is an example Resource class:</p>

<pre class=""lang-java prettyprint-override""><code>package com.my.page;

import org.glassfish.hk2.api.messaging.Topic;
import com.my.core.entity.Link;
import com.my.core.location.LinkHitLocationFactory;
import com.my.core.service.LinkService;
import com.my.core.service.link.LinkFinder;
import com.my.core.service.link.LinkFinderFactory;
import com.my.event.LinkHitEvent;
import com.my.exception.FragmentNotFoundException;

import javax.annotation.security.PermitAll;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;

@PermitAll
@Path(""/"")
public class LinkResource {

    @Inject
    private LinkService linkService;

    @Inject
    private Topic&lt;LinkHitEvent&gt; linkHitPublisher;

    @Inject
    private LinkFinderFactory linkFinderFactory;

    @Inject
    private LinkHitLocationFactory linkHitLocationFactory;


    @GET
    @Path(""/{fragment:[^ ]{1,32}}"")
    public Response redirect(
            @PathParam(""fragment"") String fragment,
            @HeaderParam(""Range"") String range,
            @HeaderParam(""User-Agent"") String userAgent,
            @Context HttpHeaders headers) throws Exception {

        LinkFinder linkFinder = linkFinderFactory.getLinkFinder(fragment);
        Link link = linkFinder.getLink(fragment);

        if (link.isExpired()) {
            throw new FragmentNotFoundException(fragment);
        }

        linkService.insertHit();
        linkHitPublisher.publish(new LinkHitEvent(link));

        return handlerFactory.getHandler(link).handleGet(link, range).build();
    }
}

</code></pre>

<p>Event test:</p>

<pre class=""lang-java prettyprint-override""><code>package com.my.page;

import org.glassfish.hk2.extras.events.internal.TopicDistributionModule;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import pl.comvision.hk2.events.ThreadedEventDistributorService;
import com.my.client.CallbackTargetBuilder;
import com.my.core.entity.Link;
import com.my.core.mapper.LinkMapper;
import com.my.core.service.LinkService;
import com.my.page.resource.LinkResource;

import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;

import static javax.ws.rs.core.Response.Status.TEMPORARY_REDIRECT;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class CallbackEventTest extends JerseyTest {
    @Mock
    private LinkMapper linkMapper;

    @Mock
    private LinkService linkService;

    private CallbackTargetBuilder callbackTargetBuilder;
    private final String callbackUrl = """";

    @Override
    protected Application configure() {
        this.callbackTargetBuilder = spy(new CallbackTargetBuilder(this.callbackUrl));

        ResourceConfig config = new ResourceConfig(LinkResource.class);
        config.register(new TopicDistributionModule());
        config.register(new AbstractBinder() {
            @Override
            protected void configure() {
                addActiveDescriptor(ThreadedEventDistributorService.class).setRanking(100);
            }
        });
        config.register(new EventsContainerListener(CallbackEventHandler.class));

        config.register(new AbstractBinder() {
            @Override
            protected void configure() {
                bind(linkMapper).to(LinkMapper.class);
                bind(linkService).to(LinkService.class);
                bind(mock(LinkService.class)).to(LinkService.class);

                bind("""").to(String.class).named(""varPath"");
                bind(""127.0.0.1"").to(String.class).named(""requestIP"");
                bind(callbackTargetBuilder).to(CallbackTargetBuilder.class);
            }
        });

        return config;
    }

    @Test
    public void publish_event() {
        Link link = mock(Link.class);
        when(link.getUrl()).thenReturn(""example"");
        when(link.getName()).thenReturn(""test"");
        when(linkMapper.getByName(anyString())).thenReturn(link);

        Response response = target(""/testY"").property(""jersey.config.client.followRedirects"", false).request().get();
        assertEquals(TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
        verify(callbackTargetBuilder).build();
    }
}
</code></pre>

<p>For testing purposes, I only injected callbackTargetBuilder into the handler, and called the build method on it to verify the call:</p>

<pre class=""lang-java prettyprint-override""><code>package com.my.page;

import org.glassfish.hk2.api.messaging.MessageReceiver;
import org.glassfish.hk2.api.messaging.SubscribeTo;
import org.jvnet.hk2.annotations.Service;
import com.my.client.CallbackTargetBuilder;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;

@Service
@Singleton
@MessageReceiver
public class CallbackEventHandler {

    @Named(""callbackUrl"")
    private String url;

    @Inject
    private CallbackTargetBuilder callbackTargetBuilder;

    @MessageReceiver
    public void handle(@SubscribeTo LinkHitEvent event) {
        Form form = new Form();
        form.param(""id"", event.getLink().getId().toString());
        form.param(""name"", event.getLink().getName());

        callbackTargetBuilder.build();

        Client client = ClientBuilder.newClient();
        client.target(url).request().post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
    }
}
</code></pre>

<p>Edit:
I tried to register dependencies differently, but it does not bring satisfactory results. Each time verification fails:
<code>verify (callbackTargetBuilder) .build ();</code></p>

<p>Looking for information I found that I can configure the DeploymentContext, but I don't know if this is the right direction.</p>

<p>Edit the second:
A quick test shows that I may have some more basic problem with mocking. Because the call:
<code>verify (linkService) .insertHit (anyObject ());</code>
It also fails.</p>
",https://stackoverflow.com/questions/61470177/integration-testing-for-events-in-the-jersey-container-listener,"['java', 'testing', 'jersey', 'jax-rs']",161,False,0,1
How can solve requesting &quot;dart.ui&quot; in Flutter while Integration Testing,"<p>I am doing integration testing to my Login Page. Here the error that I got. How can I solve this error.</p>

<blockquote>
  <p>C:\Users\user\AndroidStudioProjects\flutter_project>flutter drive --target=test_driver/app.dart Found multiple connected devices: SM J210F                  • 4200a590689b1400 • android-arm • Android
  6.0.1 (API 23) Android SDK built for x86 • emulator-5554    • android-x86 • Android 8.1.0 (API 27) (emulator) Using device SM J210F.
  Starting application: test_driver/app.dart Installing
  build\app\outputs\apk\app.apk...                        92.6s Running
  Gradle task 'assembleDebug'... I/flutter ( 5922): Observatory
  listening on <a href=""http://127.0.0.1:54862/GeAeXgP3k4M=/"" rel=""nofollow noreferrer"">http://127.0.0.1:54862/GeAeXgP3k4M=/</a></p>
  
  <p>E/FlutterFcmService( 5922): Fatal: failed to find callback</p>
  
  <p>I/flutter ( 7271): Observatory listening on
  <a href=""http://127.0.0.1:48093/UgDcJGtlUI0=/"" rel=""nofollow noreferrer"">http://127.0.0.1:48093/UgDcJGtlUI0=/</a></p>
  
  <p>E/FlutterFcmService( 7271): Fatal: failed to find callback</p>
  
  <p>registerResGeneratingTask is deprecated, use
  registerGeneratedResFolders(FileCollection)</p>
  
  <p>registerResGeneratingTask is deprecated, use
  registerGeneratedResFolders(FileCollection)</p>
  
  <p>registerResGeneratingTask is deprecated, use
  registerGeneratedResFolders(FileCollection) Running Gradle task
  'assembleDebug'...                             95.3s √ Built
  build\app\outputs\apk\debug\app-debug.apk. Installing
  build\app\outputs\apk\app.apk...                        28.1s Package
  install error: Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE]
  Uninstalling old version... Installing
  build\app\outputs\apk\app.apk...                        93.1s
  I/flutter ( 8617): Observatory listening on
  <a href=""http://127.0.0.1:54916/WUrIswnOm3g=/"" rel=""nofollow noreferrer"">http://127.0.0.1:54916/WUrIswnOm3g=/</a> E/FlutterFcmService( 8617):
  Fatal: failed to find callback /</p>
  
  <ul>
  <li><p>D:/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.13.4+2/lib/cloud_firestore.dart:8:8:
  Error: Not found: 'dart:ui' import 'dart:ui' show hashList;</p></li>
  <li><p>^    /D:/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-6.0.12/lib/firebase_messaging.dart:7:8:
  Error: Not found: 'dart:ui' import 'dart:ui';</p></li>
  <li><p>^    /D:/flutter/packages/flutter/lib/src/material/animated_icons.dart:9:8:
  Error: Not found: 'dart:ui' import 'dart:ui' as ui show Paint, Path,<br>
  Canvas;</p></li>
  <li><p>/D:/flutter/packages/flutter/lib/src/material/animated_icons.dart:10:8:
  Error: Not found: 'dart:ui' import 'dart:ui' show lerpDouble;</p></li>
  <li><p>^ /D:/flutter/packages/flutter/lib/src/material/app.dart:5:8: Error:    Not found: 'dart:ui' import 'dart:ui' as ui;</p></li>
  <li>^    /D:/flutter/packages/flutter/lib/src/material/app_bar_theme.dart:5:8: 
  Error: Not found: 'dart:ui' import 'dart:ui' show lerpDouble;</li>
  <li><p>^ /D:/flutter/packages/flutter/lib/src/material/arc.dart:6:8: Error:    Not found: 'dart:ui' import 'dart:ui' show lerpDouble;</p></li>
  <li><p>^    /D:/flutter/packages/flutter/lib/src/material/bottom_app_bar_theme.dart:5:8:
  Error: Not found: 'dart:ui' import 'dart:ui' show lerpDouble;</p></li>
  <li><p>^    /D:/flutter/packages/flutter/lib/src/material/bottom_sheet_theme.dart:5:8:
  Error: Not found: 'dart:ui' import 'dart:ui' show lerpDouble;</p></li>
  <li><p>^    /D:/flutter/packages/flutter/lib/src/material/button_bar_theme.dart:5:8:
  Error: Not found: 'dart:ui' import 'dart:ui' show lerpDouble;
           ^</p></li>
  <li>Stopping application instance. Driver tests failed: 254</li>
  </ul>
</blockquote>

<p>My app_test.dart code</p>

<pre><code>import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';`


void main() {
group(""Flutter Auth Test"", () {
  final emailField = find.byValueKey(""emailfield"");
  final passwordField = find.byValueKey(""passwordfield"");
  final signbutton = find.byValueKey(""log"");
  final adminPage = find.byValueKey(""home"");
  final userPage = find.byValueKey(""userp"");

  FlutterDriver driver;
  setUpAll(()async{
    driver = await FlutterDriver.connect();
  });

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

  test(""login with incorrect email and password"",() async{
    await driver.tap(emailField);
    await driver.enterText(""test@gmail.com"");
    await driver.tap(passwordField);
    await driver.enterText(""test123"");
    await driver.tap(signbutton);
    await driver.waitUntilNoTransientCallbacks();
    assert(adminPage == null &amp;&amp; userPage == null);
  });

  test(""login admin with correct email and password"",() async {
    await driver.tap(emailField);
    await driver.enterText(""madhuwanthiaah@gmail.com"");
    await driver.tap(passwordField);
    await driver.enterText(""admin123"");
    await driver.tap(signbutton);
    assert(adminPage != null &amp;&amp; userPage == null);

  });

  test(""login user with correct email and password"",() async {
    await driver.tap(emailField);
    await driver.enterText(""cst16029@gmail.com"");
    await driver.tap(passwordField);
    await driver.enterText(""user123"");
    await driver.tap(signbutton);
    assert(userPage != null &amp;&amp; adminPage == null);
  });
});
}
</code></pre>
",https://stackoverflow.com/questions/60763221/how-can-solve-requesting-dart-ui-in-flutter-while-integration-testing,"['flutter', 'flutter-test']",2041,True,3,1
Integration testing Google Signin JWT id token with backend API,"<p>I have an API that accepts google id tokens in the standard way <a href=""https://developers.google.com/identity/sign-in/web/backend-auth"" rel=""nofollow noreferrer"">described here</a>.</p>
<ol>
<li>user opens Google oAuth popup and selects account</li>
<li>popup closes resolving with google id JWT</li>
<li>JWT is sent to my API <code>/login</code> or <code>/register</code> endpoint</li>
<li>backend decodes and verifies the JWT then uses the contained claims to register or log the user in accordingly.</li>
</ol>
<p>I also have a suite of simple integration tests that run against the API including tests for whether it can register or log a user in using an email/password.</p>
<p>I'd like to write tests for whether <code>/login</code> and <code>/register</code> work correctly with google JWT but I can't think of a way given that JWT by design are only valid when signed by Google which I can't get in automated tests. My current ideas:</p>
<ul>
<li>config of some kind that skips JWT verification in dev/test mode - this would work but introducing a potential security vulnerability for the sake of a test feels like a code smell</li>
<li>not testing :(</li>
</ul>
<p>Any ideas?</p>
",https://stackoverflow.com/questions/63696996/integration-testing-google-signin-jwt-id-token-with-backend-api,"['oauth', 'jwt', 'google-oauth', 'integration-testing', 'google-signin']",437,False,2,0
Disabling or mocking Spring Security filters while integration testing RestController,"<p>In my app I've got a custom filter added in WebSecurityConfigurerAdapter extension:</p>

<pre><code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private static final RequestMatcher PROTECTED_URLS = new AntPathRequestMatcher(""/v1/**"");

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
                .addFilterBefore(authenticationFilter(), AnonymousAuthenticationFilter.class)
                .authorizeRequests()
                .requestMatchers(PROTECTED_URLS)
                .authenticated()
            .and()
                .csrf().disable()
                .formLogin().disable()
                .httpBasic().disable()
                .logout().disable();
    }

    @Bean
    AuthenticationFilter authenticationFilter() throws Exception {
        final AuthenticationFilter filter = new AuthenticationFilter(PROTECTED_URLS);

        // filter setup...

        filter.setAuthenticationManager(authenticationManager());
        return filter;
    }
}
</code></pre>

<p>The filter itself, which is responsible for validating the access token by calling an external authorization server is defined as:</p>

<pre><code>public class AuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    AuthenticationFilter(final RequestMatcher requiresAuth) {
        super(requiresAuth);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest,
                                                HttpServletResponse httpServletResponse)
        throws AuthenticationException, IOException, OAuth2Exception {
        try {
            // Get Authorization header.
            String token = httpServletRequest.getHeader(AUTHORIZATION);

            // Check if the token is valid by calling an external authorization server.
            // Returns some Authentication if successful.
        } catch (OAuth2Exception exception) {
            // Return 401
        } catch (Exception exception) {
            // All other errors are 500s
        }
    }

    @Override
    protected void successfulAuthentication(final HttpServletRequest request,
                                            final HttpServletResponse response,
                                            final FilterChain chain,
                                            final Authentication authResult)
        throws IOException, ServletException {
        SecurityContextHolder.getContext().setAuthentication(authResult);
        chain.doFilter(request, response);
    }
}
</code></pre>

<p>What I'm trying to do is to perform integration test on the controller defined as:</p>

<pre><code>@RestController
@RequestMapping(value = ""/v1"", produces = ""application/json"")
public class SomeController {

    @Autowired
    private SomeService someService;

    @ResponseStatus(OK)
    @PostMapping(value = ""/a/path"")
    public SomeSuccessResponse pathHandlerMethod() {
        return someService.someServiceMethod();
    }
}
</code></pre>

<p>Finally, my test setup is as following:</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
@Import(SecurityConfig.class)
@ContextConfiguration
@WebAppConfiguration
public class SomeControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private WebApplicationContext context;

    @MockBean
    private SomeService someService;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply(springSecurity()) // When I comment out this line I'm getting 404 errors instead.
            .build();
    }

    @Test
    @WithMockUser
    public void performIntegrationTest() throws Exception {
        mockMvc.perform(post(""/v1/a/path"")).andExpect(status().isOk());
    }
}
</code></pre>

<p>I'd like the authentication to be either turned off or somehow mocked out for this scenario - the actual code in <code>AuthenticationFilter</code> sholdn't be invoked at all. In order to achieve this, in <code>SomeControllerTest</code> class I've tried:</p>

<ul>
<li>annotating test methods with <code>@WithMockUser</code></li>
<li>setting <code>mockMvc</code> with <code>MockMvcBuilders</code> (see the <code>setup()</code> method above) with <code>.apply(springSecurity())</code> and without it</li>
<li>annotating the <code>SomeControllerTest</code> class with <code>@AutoConfigureMockMvc</code> (with both <code>secure</code> and <code>addFilters</code> parameters set to <code>false</code>)</li>
<li>annotating the <code>SomeControllerTest</code> class with <code>@ContextConfiguration</code> and <code>@WebAppConfiguration</code> (I don't know if it changes anything)</li>
</ul>

<p>None of these approaches disable the authentication. When I run the test, the <code>AuthenticationFilter</code>'s <code>attemptAuthentication()</code> method calling external service is still invoked which I don't want to happen.</p>
",https://stackoverflow.com/questions/59950812/disabling-or-mocking-spring-security-filters-while-integration-testing-restcontr,"['java', 'spring', 'spring-security', 'integration-testing']",1085,True,2,1
Unable to integration-testing gradle multi-module Spring-Boot-Application,"<p>Within a Gradle multi-module project with the bootstrapping in its own module I'm unable to use <a href=""https://spring.io/guides/gs/testing-web/"" rel=""nofollow noreferrer"">MockMvc</a>, because its need to reference the bootstrapping-module. I'm not sure if I have misconfigured something. The basic structure is:</p>

<ul>
<li>module: a module containing some REST-Services and needs a testImplementation-Dependency on starter</li>
<li>starter: the bootstrapping-module which gets the spring-boot-plugin applied and depends on module</li>
</ul>

<p>I have set up a minimal example on <a href=""https://github.com/gaerfield/spring-multimodule-integrationtest"" rel=""nofollow noreferrer"">github</a> using Spring-Boot 2.3.1.RELEASE and Gradle 6.4 with the following configuration:</p>

<p><em>./settings.gradle.kts</em></p>

<pre class=""lang-kotlin prettyprint-override""><code>rootProject.name = ""spring-multimodule-integrationtest""
include(""starter"", ""module"")
</code></pre>

<p><em>./build.gradle.kts</em></p>

<pre class=""lang-kotlin prettyprint-override""><code>subprojects {
    repositories {
        jcenter()
    }
    dependencies {
        apply(plugin = ""java-library"")
        ""testImplementation""(""junit:junit:4.12"")
    }
}
</code></pre>

<p><em>./starter/build.gradle.kts</em></p>

<pre class=""lang-kotlin prettyprint-override""><code>plugins {
    id(""org.springframework.boot"") version ""2.3.1.RELEASE""
}

dependencies {
    implementation(project("":module""))
}
</code></pre>

<p><em>./module/build.gradle.kts</em></p>

<pre><code>dependencies {
    testImplementation(project("":starter""))
}
</code></pre>

<p>The <em>starter</em>-module contains only one a single class ""Starter"" referencing the <em>module</em>-module:</p>

<pre class=""lang-java prettyprint-override""><code>public class Starter {
    public String info() { return ""starter""; }
    public static void main(String[] args) {
        System.out.println(new Starter().info() + "" and "" + new Module().info());
    }
}
</code></pre>

<p>The <em>module</em>-module (*sigh I should have chosen a different name for this module) contains only this  implemenation-class:</p>

<pre class=""lang-java prettyprint-override""><code>public class Module {
    public String info() { return ""module""; }
}
</code></pre>

<p>Additionally, the <em>module</em>-module has the following test-class doing the integration-test:</p>

<pre class=""lang-java prettyprint-override""><code>public class IntegrationTest
{
    @Test public void testSomeLibraryMethod() {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        Starter.main(new String[0]);
        assertEquals(""starter and module\n"", out.toString());
    }
}
</code></pre>

<p>This code runs fine until the applying of the spring-boot-plugin within ""./starter/build.gradle.kts"". When the tasks ""clean test"" issued on the shell I get:</p>

<pre><code>❯ ./gradlew clean test

&gt; Task :module:test FAILED

de.kramhal.multi.IntegrationTest &gt; testSomeLibraryMethod FAILED
    java.lang.NoClassDefFoundError at IntegrationTest.java:17
        Caused by: java.lang.ClassNotFoundException at IntegrationTest.java:17

1 test completed, 1 failed
</code></pre>

<p>This problem does not occur, when tests are executed within the IDE (IntelliJ to be exact).</p>

<p>I already tried unsuccessfully to use the spring-dependency-management as suggested in this <a href=""https://stackoverflow.com/a/60496709/5029667"">answer</a> (as well as in several other answers). </p>

<p>What have I done wrong?</p>
",https://stackoverflow.com/questions/62340841/unable-to-integration-testing-gradle-multi-module-spring-boot-application,"['java', 'spring', 'spring-boot', 'gradle', 'multi-module']",1953,True,1,1
Register Mock Bean during Integration Testing for SpEL Bean Reference,"<p>I am getting the following error while running the test from my spring-boot app. I am using version= 2.3.3.RELEASE of <code>spring-boot-starter-data-mongodb</code> and version=2.2.0 of <code>de.flapdoodle.embed.mongo</code> for integration testing.</p>
<pre><code>org.springframework.expression.spel.SpelEvaluationException: EL1058E: A problem occurred when trying to resolve bean 'gameServiceImpl':'Could not resolve bean reference against BeanFactory'

    at org.springframework.expression.spel.ast.BeanReference.getValueInternal(BeanReference.java:59)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:55)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:91)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:117)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:308)
    at org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity.getCollection(BasicMongoPersistentEntity.java:129)
    at org.springframework.data.mongodb.repository.support.MappingMongoEntityInformation.getCollectionName(MappingMongoEntityInformation.java:97)
    at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.save(SimpleMongoRepository.java:88)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.data.repository.core.support.ImplementationInvocationMetadata.invoke(ImplementationInvocationMetadata.java:72)
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:382)
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:205)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:549)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:155)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy70.save(Unknown Source)
    at eatigo.com.webscraper.service.GameServiceImplTest.testSavingSingleEntity(GameServiceImplTest.java:107)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    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:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    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:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
    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: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:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
    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: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:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    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:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: org.springframework.expression.AccessException: Could not resolve bean reference against BeanFactory
    at org.springframework.context.expression.BeanFactoryResolver.resolve(BeanFactoryResolver.java:54)
    at org.springframework.expression.spel.ast.BeanReference.getValueInternal(BeanReference.java:55)
    ... 89 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'gameServiceImpl' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:816)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1109)
    at org.springframework.context.expression.BeanFactoryResolver.resolve(BeanFactoryResolver.java:51)
    ... 90 more
</code></pre>
<p>Below is my simple code implementations</p>
<p>I underdtand that the problem lies in this statement <code>@Document(collection = &quot;#{@gameServiceImpl.getCollectionName()}&quot;)</code> because during testing, the SPEL can't find any bean with name='gameServiceImpl' because it has been mocked during testing.</p>
<ol>
<li>Is there a way to inject a mock bean in the spring container registry for it to be recognized by SPEL?</li>
<li>Is it possible to replace and inject value in the class annotation here <code>@Document(collection = &quot;replace and inject value here&quot;)</code> during the initialization of entity class e.g <code>Game game= new Game();</code></li>
</ol>
<p>Entity</p>
<pre><code>@Document(collection = &quot;#{@gameServiceImpl.getCollectionName()}&quot;)
public class Game {
    @Id
    private int gameId;
}
</code></pre>
<p>Repository</p>
<pre><code>@Repository
public interface GameRepository extends MongoRepository&lt;Game, String&gt; {
}
</code></pre>
<p>Service</p>
<pre><code>@Service
public class GameServiceImpl implements GameService {

    private GameRepository gameRepository;
    private String collectionName;

    @Autowired
    public GameServiceImpl(GameRepository gameRepository){
        this.gameRepository = gameRepository;
    }

    @Override
    public String getCollectionName() {
        return collectionName;
    }

    @Override
    public void setCollectionName(String collectionName) {
        this.collectionName = collectionName;
    }

    public Game save(Game game){
        return gameRepository.save(game);
    }
}
</code></pre>
<p>Test</p>
<pre><code>ExtendWith(SpringExtension.class)
@ActiveProfiles(&quot;test&quot;)
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@SpringBootTest(classes = {MainApplication.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@DataMongoTest
public class GameServiceImplTest {

    @Mock(name = &quot;gameServiceImpl&quot;)
    private GameServiceImpl gameServiceImpl;

    @Autowired
    private GameRepository gameRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @BeforeEach
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testSavingGame(){
        Game game= new Game();

        String collectionName = &quot;testing&quot;;
        gameServiceImpl.setCollectionName(collectionName);
        when(gameServiceImpl.save(game)).thenReturn(gameRepository.save(game));
        when(gameServiceImpl.getCollectionName()).thenReturn(collectionName);

        Game result = gameServiceImpl.save(game);

        assertThat(result, is(notNullValue()));
        assertThat(mongoTemplate.collectionExists(collectionName), is(true));
        assertThat(mongoTemplate.findAll(Game.class, collectionName).size(), equalTo(1));
    }
}
</code></pre>
",https://stackoverflow.com/questions/64167148/register-mock-bean-during-integration-testing-for-spel-bean-reference,"['mongodb', 'spring-boot', 'mockito', 'integration-testing']",1256,False,1,1
Use production database as in memory database for integration testing,"<p>I have 58 tables in my production database, and currently these tables have some initial records. My question: is it possible to somehow copy the production database to an in memory database for testing?</p>

<p>Here is the part where the <code>DbContext</code> is set up:</p>

<pre><code>var descriptor = services.SingleOrDefault(d =&gt; d.ServiceType == typeof(DbContextOptions&lt;AppDbContext&gt;));

if (descriptor != null)
{
    services.Remove(descriptor);
}

services.AddEntityFrameworkInMemoryDatabase();
services.AddDbContext&lt;AppDbContext&gt;(
    options =&gt;
    {
        options.UseInMemoryDatabase(""AppInMemoryDb"");
    });
</code></pre>
",https://stackoverflow.com/questions/60799412/use-production-database-as-in-memory-database-for-integration-testing,"['c#', 'asp.net', 'database', 'entity-framework']",380,False,0,0
Spring Integration Testing environment not dispatching JPA entity lifecycle event,"<p>I have a simple Spring project with an embedded in memory database. I have a simple post persist lifecycle method that just calls print. When I run the app it logs correctly when I run test it doesn't. How can I make the test environment calls the lifecycle callback method? I need to know how to do it because my intention is to perform an integration test with the lifecycle callback method.</p>

<p>Here the logs when I run <code>./gradlew bootRun</code></p>

<pre><code>...
2020-04-19 22:04:14.532  INFO 24183 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-04-19 22:04:14.765  INFO 24183 --- [           main] c.flama.lifecycle.LifecycleApplication   : Started LifecycleApplication in 1.885 seconds (JVM running for 2.218)
INSIDE CRAZY METHOD
PRINTING ENTITIES
1
2020-04-19 22:04:14.877  INFO 24183 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
...
</code></pre>

<p>and here the logs when I run <code>./gradlew test</code></p>

<pre><code>&gt; Task :test
2020-04-19 22:04:07.308  INFO 24076 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-04-19 22:04:07.308  INFO 24076 --- [extShutdownHook] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2020-04-19 22:04:07.312  INFO 24076 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2020-04-19 22:04:07.319  INFO 24076 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

BUILD SUCCESSFUL in 5s
4 actionable tasks: 2 executed, 2 up-to-date
</code></pre>

<p>Here build.gradle:</p>

<pre><code>plugins {
    id 'org.springframework.boot' version '2.2.6.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
}

group = 'com.flama'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    runtimeOnly 'com.h2database:h2'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

test {
    useJUnitPlatform()
}
</code></pre>

<p>This is my main class:</p>

<pre><code>package com.flama.lifecycle;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.flama.lifecycle.repository.SillyRepository;
import com.flama.lifecycle.domain.SillyEntity;

@SpringBootApplication
public class LifecycleApplication {

    public static void main(String[] args) {
        ApplicationContext context = (ApplicationContext)SpringApplication.run(LifecycleApplication.class, args);
        SillyRepository repository = (SillyRepository) context.getBean(""sillyRepository"");
        repository.saveAndFlush(new SillyEntity());
        System.out.println(""PRINTING ENTITIES"");
        for (SillyEntity entity: repository.findAll()){
            System.out.println(entity.getId());
        }
    }

}
</code></pre>

<p>The domain class:</p>

<pre><code>package com.flama.lifecycle.domain;

import javax.persistence.*;

@Entity
@Table(name = ""silly"")
public class SillyEntity{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    public Long getId(){
        return id;
    }

    @PostPersist
    public void crazyMethod(){
        System.out.println(""INSIDE CRAZY METHOD"");
    }

}

</code></pre>

<p>The repository class:</p>

<pre><code>package com.flama.lifecycle.repository;

import org.springframework.stereotype.Repository;
import com.flama.lifecycle.domain.SillyEntity;
import org.springframework.data.jpa.repository.*;

@Repository
public interface SillyRepository extends JpaRepository&lt;SillyEntity, Long&gt;{
}

</code></pre>

<p>The test class:</p>

<pre><code>package com.flama.lifecycle;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;
import com.flama.lifecycle.domain.SillyEntity;
import com.flama.lifecycle.repository.SillyRepository;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
class LifecycleApplicationTests {

    @Autowired
    private SillyRepository repository;

    @Test
    void contextLoads() {
    }

    @Test
    void createSillyEntity(){
        SillyEntity entity = new SillyEntity();
        int sizeBefore = repository.findAll().size();
        repository.saveAndFlush(entity);
        assertThat(repository.findAll().size()).isEqualTo(sizeBefore + 1);
    }

}
</code></pre>
",https://stackoverflow.com/questions/61313788/spring-integration-testing-environment-not-dispatching-jpa-entity-lifecycle-even,"['java', 'spring', 'hibernate', 'spring-boot', 'jpa']",120,False,0,1
Void Method in Service is not Mocking in Integration Testing,"<p>In my spring boot project, one of my Service depends on external service like Amazon. I am writing the integration testing of the Controller classes. So, I want to mock the method in the AmazonService class(as it depends on third party API). The method is void with a single Long argument and can throw a <strong>custom application-specific exceptions.</strong> </p>

<p>The method is as follows:-</p>

<pre><code>class AmazonService{
public void deleteMultipleObjects(Long enterpriseId) {
        String key = formApplicationLogokey(enterpriseId,null);
        List&lt;S3ObjectSummary&gt; objects = getAllObjectSummaryByFolder(key);
        List&lt;DeleteObjectsRequest.KeyVersion&gt; keys = new ArrayList&lt;&gt;();
        objects.stream().forEach(object-&gt;keys.add(new DeleteObjectsRequest.KeyVersion(object.getKey())));
        try{
            DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(this.bucket).withKeys(keys);
            this.s3client.deleteObjects(deleteObjectsRequest);
            log.debug(""All the Application logos deleted from AWS for the Enterprise id: {}"",enterpriseId);
        }
        catch(AmazonServiceException e){
            throw new AppScoreException(AppScoreErrorCode.OBJECT_NOT_DELETED_FROM_AWS);
        }
    }}
</code></pre>

<p><strong>class Test</strong></p>

<pre><code>class Test
    {
        @Autowired
        AmazonServiceImpl amazonService;

        @Autowired
        EnterpriseService enterpriseService;

        @Before
        public void init()
        {
            amazonService = Mockito.mock(AmazonServiceImpl.class);        
            Mockito.doNothing().when(amazonService).deleteMultipleObjects(isA(Long.class));
        }


        @Test
        public void testDeleteEnterprise(){
            setHeaders();
            EnterpriseDTO enterpriseDTO = createEnterpriseEntity(null,""testDeleteEnterpriseName3"",null,null,null);
            String postUrl = TestUrlUtil.createURLWithPort(TestConstants.ADD_ENTERPRISE,port);
            HttpEntity&lt;EnterpriseDTO&gt; request1 = new HttpEntity&lt;&gt;(enterpriseDTO,headers);
            ResponseEntity&lt;EnterpriseDTO&gt; response1 = restTemplate.postForEntity(postUrl,request1,EnterpriseDTO.class);
            assert response1 != null;
            Long enterpriseId = Objects.requireNonNull(response1.getBody()).getId();
            String url = TestUrlUtil.createURLWithPort(TestConstants.DELETE_ENTERPRISE,port)+File.separator+enterpriseId;
            HttpEntity&lt;EnterpriseDTO&gt; request = new HttpEntity&lt;&gt;(null, headers);
            ResponseEntity&lt;Object&gt; response = restTemplate.exchange(url,HttpMethod.DELETE,request,Object.class);
            Assert.assertEquals(Constants.ENTERPRISE_DELETION_SUCCESS_MESSAGE,response.getBody());
        }
    }
</code></pre>

<p><strong>class EnterpriseResource</strong></p>

<pre><code>class EnterpriseResource
{
    @DeleteMapping(""/enterprises/{enterpriseId}"")
    public ResponseEntity&lt;Object&gt; deleteEnterprise(@PathVariable Long enterpriseId) {
        log.debug(""REST request to delete Enterprise : {}"", enterpriseId);
        enterpriseService.delete(enterpriseId);
        return ResponseEntity.badRequest().body(Constants.ENTERPRISE_DELETION_SUCCESS_MESSAGE);
    }
}
</code></pre>

<p><strong>class EnterpriseServiceImpl</strong></p>

<pre><code>class EnterpriseServiceImpl
{
    @Override
    public void delete(Long enterpriseId) {
        log.debug(""Request to delete Enterprise : {}"", enterpriseId);
        enterpriseRepository.deleteById(enterpriseId);
        amazonService.deleteMultipleObjects(enterpriseId);
    }
} 
</code></pre>

<p>I have tried various approaches to Mock this method but it didn't work and control is going inside this method during debugging. I want to do nothing in this method during testing.
I have tried the various approaches like throw(), doNothing(), spy() etc.</p>

<p>Please help what is missing here?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/60725671/void-method-in-service-is-not-mocking-in-integration-testing,"['java', 'testing', 'mockito', 'integration', 'void']",198,False,0,0
Integration testing of graphQL query and a page component in gatsbyJS,"<p>I would like to have an integration test for my page query + page component:</p>

<pre><code>import React from ""react"";
import { graphql } from ""gatsby"";

const NotFound = ({ data }) =&gt; {
  const { title, text } = data.allFile.edges[0].node.childDataJson;

  return (
    &lt;React.Fragment&gt;
      &lt;h1&gt;{title}&lt;/h1&gt;
      &lt;p&gt;{text}&lt;/p&gt;
    &lt;/React.Fragment&gt;
  );
};

export const query = graphql`
  query {
    allFile(filter: { name: { eq: ""404"" } }) {
      edges {
        node {
          childDataJson {
            title
            text
          }
        }
      }
    }
  }
`;

export default NotFound;
</code></pre>

<p>What I would like to test is if the query structure is correct, and therefore check the presence of the title in DOM:</p>

<pre><code>describe(""404 page"", () =&gt; {
  it(""Contains a title"", () =&gt; {
    const { getByText } = render(&lt;NotFound /&gt;);
    expect(getByText(""Not found"")).toBeInTheDocument();
  });
});
</code></pre>

<p>I get the following error:
<code>It appears like Gatsby is misconfigured. Gatsby related</code>graphql<code>calls are supposed to only be evaluated at compile time, and then compiled away. Unfortunately, something went wron
g and the query was left in the compiled code.</code></p>

<p>Is it possible to write integration test checking graphQL queries?</p>

<p>I know that I can mock the graphql page query in <code>mocks</code> to avoid this error, but I would like for graphql not to be mocked:</p>

<pre><code>const React = require(""react"");
const gatsby = jest.requireActual(""gatsby"");

module.exports = {
  ...gatsby,
  graphql: jest.fn(),
};
</code></pre>
",https://stackoverflow.com/questions/59630249/integration-testing-of-graphql-query-and-a-page-component-in-gatsbyjs,"['reactjs', 'testing', 'graphql', 'integration-testing', 'gatsby']",404,False,3,0
Flutter: Integration testing. Is it possible to visualize taps and scrolls?,"<p>As far as I can see, integration tests are good for running on a device and see how my program behaves.
The problem is that it runs too fast and I can't see anything.</p>
<p>I came up with solution to set <code>await Future.delayed(Duration(seconds: 3));</code> in <code>setUpAll()</code> and after any significant action to at least see what is happenning on the screen.</p>
<p>Can I also see Driver taps and scrolls simulation somehow?</p>
<p>I tried to enter Developer Settings on my Emulator and turn on &quot;Show taps&quot; and &quot;Pointer location&quot;, but it doesn't help. It shows only real taps by mouse cursor and not by FlutterDriver.</p>
",https://stackoverflow.com/questions/62504008/flutter-integration-testing-is-it-possible-to-visualize-taps-and-scrolls,"['flutter', 'testing', 'dart', 'integration-testing']",132,False,2,0
"Integration Testing with Spring Boot, RabbitMQ and UUID as primary key","<p>I have a Spring Boot application written in Kotlin with RabbitMQ and PostgreSQL. Primary keys in the DataBase are of type UUID and are generated by the application with a distinct service.</p>

<p>For integration testing this service is stubbed to generate UUIDs sequentionally instead of randomly, because they are checked against the expected data set. There is a simple incremental counter in the service.</p>

<p>This stub service has Prototype scope to every repository have its own UUID generator.</p>

<p>This approach had worked perfectly until I had to test cases with RabbitMQ.
The flow is following:</p>

<ol>
<li>A request to controller is performed.</li>
<li>A record is saved in operations history table.</li>
<li>A message is sent to the RabbitMQ topic.</li>
<li>Then message is returned back to the application.</li>
<li>A new record is saved in operations history table.</li>
</ol>

<p>When this test is run alone it passes and everything works as expected.
When this test is run together with the other tests it fails. An error occurs on step 5 when it tries to save new record to the data base.</p>

<p>Via debug I have discovered the following:
In the first case when the test is run alone the repository instance and the UUID generator service instance are the same on both steps 2 and 5.
In the second case when test is run together with the other, the repository instance and the UUID generator service instance are different on steps 2 and 5. As result there are different counters that are not syncronized. It leads to generation of the same id and a primary key exception on step 5.</p>

<p>As I understand this issue happens because Spring RabbitMQ creates listener containers that may have its own bean instances. It is still a riddle to me how it chooses to create a new bean instance or to use the existing.</p>

<p>Can you propose any solution or a different approach to implement this test?</p>
",https://stackoverflow.com/questions/60428725/integration-testing-with-spring-boot-rabbitmq-and-uuid-as-primary-key,"['spring', 'spring-boot', 'junit', 'rabbitmq', 'integration-testing']",175,False,1,0
&quot;Tracking Information Not Found&quot; error with UPS RESTful Integration Testing URI,"<p>I tried to get the result of UPS RESTful API with my valid track number and API key. I get the following error: &quot;TW0001, Tracking Information Not Found&quot;. This happens if I use this Integration Testing URI (<code>https://wwwcie.ups.com/track/v1/details/</code>). When I replaced it with Production URI, I got track information without any errors:</p>
<p><code>https://onlinetools.ups.com/track/v1/details/</code>.</p>
<p>I don’t think it’s normal, because the Integration Testing URI should have returned valid information, not an error.</p>
<p>My HTTP GET request example:</p>
<pre><code>GET https://wwwcie.ups.com/track/v1/details/1ZXXXXXXXXXXXXXXXX HTTP/1.1
transId: 12345
transactionSrc: TestTrack
AccessLicenseNumber: MY_KEY
Content-Type: application/json
Accept: application/json
Username: MY_USERNAME
Password: MY_PASSWORD
</code></pre>
",https://stackoverflow.com/questions/62626015/tracking-information-not-found-error-with-ups-restful-integration-testing-uri,"['json', 'rest', 'http', 'get', 'ups']",1026,True,1,1
Integration testing Azure function app that connect to Service Bus queue,"<p>I have developed a function app that is triggered by a Http request, and peeks a respective queue (connects to it by a connection string) on the Service Bus for messages with a specific parameter value, and delete them. </p>

<p>In addition to regular testing when developing, it would be great to create integration tests and run them in a CI/CD process, but I don't know how to mock the queue that the function app connects too (creating a test queue that resides on the Service bus only to be used for test-purposes is not an option). Does anyone have any idea how to proceed?</p>
",https://stackoverflow.com/questions/61473664/integration-testing-azure-function-app-that-connect-to-service-bus-queue,"['azure', 'queue', 'azure-functions', 'azureservicebus', 'azure-function-app']",782,True,1,1
Enzyme integration testing: axios.get call not being executed in redux-saga,"<p>I am trying to setup tests for some an action creator that is triggering a redux saga.</p>
<p>My saga retrieves a word from a local flask server (will always return the same word) and then displays that word. This is not my real-life case but I tried to start with something easy...</p>
<p>My action creator and saga work as expected when I trigger them with a button in my react app (the word is retrieved from the server, stored in my redux store and the displayed with a selector in my react component), but I cannot get the test to succeed.</p>
<p>I would like to test only the redux part, not the actual rendered react component (not sure if that is part of my problem or not)</p>
<p>I use Enzyme for tests, my store is created correctly and can dispatch the action. I can also see that my saga is being called with the console logs:</p>
<p>My test code:</p>
<pre><code>import { Store } from 'redux';

import { RootState } from '../root.reducer';
import { storeFactory } from '../../../test/testUtils';
import { getSecretWord } from './secret-word.actions';

describe('getSecretWord action creator', () =&gt; {
  let store: Store&lt;RootState&gt;;
  beforeEach(() =&gt; {
    store = storeFactory();
  });
  test('add response word to state', () =&gt; {
    const secretWord = 'party';
    store.dispatch(getSecretWord());
    const newState = store.getState();
    console.log('new state: ' + newState.secretWord);
    expect(newState.secretWord).toBe(secretWord);
  });
});
</code></pre>
<p>and my saga function:</p>
<pre><code>export function* getSecretWordSaga(action: getSecretWordAction): Generator&lt;ForkEffect | CallEffect | PutEffect, void, unknown&gt;
  {
  try {
    console.log('getSecretWordSaga() saga started');
    console.log('before axios query call:');
    const response:any =  yield call(api.get, '/api/word');
    // const response = {data: { word: 'party'}, status:200}
    
    console.log('axios query returned: ');
    console.log(response);

    yield put(setSecretWord(response.data.word));
    console.log('getSecretWordSaga() saga finsshed');
 
  } catch (err) {
    console.log('error occured:');
    console.log(err);
    console.log('getSecretWordSaga() saga finsshed with errors');
  }
}

export function* getSecretWordSagaStart(): Generator&lt;
  ForkEffect&lt;never&gt;,
  void,
  unknown
&gt; {
  yield takeLatest(SecretWordActionTypes.GET_SECRET_WORD, getSecretWordSaga);
}
</code></pre>
<p>The axios api is very basic and it includes two interceptors for logging purposes:</p>
<pre><code>import axios from 'axios';

export const api = axios.create({
  baseURL: 'http://localhost:5000',
  responseType: 'json',
});

api.interceptors.request.use(request =&gt; {
  console.log('Starting Request', JSON.stringify(request, null, 2))
  return request
})

api.interceptors.response.use(response =&gt; {
  console.log('Response:', JSON.stringify(response, null, 2))
  return response
})
</code></pre>
<p>I can see in the logs (in &quot;npm test&quot;) that I get log for the line &quot;before axios query call:' and one console.log for the request interceptor (everything looks fine there), but no more logs afterwards (neither success nor error)</p>
<p>If I comment out the &quot;yield call..&quot; and hardcode the response (like in the commented out line below), my saga runs through the end and my test succeeds.</p>
<p>Why is the yield Call(api.get, '/api/word') not being executed (and I don't get any error message)?</p>
<p>The code is my opinion correct as it is running fine when executed in react. My flask server is obviously also running and I can see in the flask app than no call to the api are being made by the running tests.</p>
<p>I obviously plan to mock that api call but was also running into some problems there, that's why I first wanted to get the real api call working.</p>
",https://stackoverflow.com/questions/65111399/enzyme-integration-testing-axios-get-call-not-being-executed-in-redux-saga,"['testing', 'axios', 'integration', 'enzyme', 'redux-saga']",232,False,0,1
How to get the device Id while doing integration testing in flutter?,"<p>I am trying to get the device Id inside app_test.dart file. But i am getting the following error. while executing the following command: flutter drive --target=test_driver/app.dart.</p>
<p>Please find the error details below:</p>
<pre><code>I/flutter (20622): Observatory listening on http://127.0.0.1:43149/9iUskIArAjk=/
../../../FlutterSDK/flutter/packages/flutter/lib/src/semantics/semantics.dart:2121:39: Warning: Operand of null-aware operation '!' has type 'List&lt;SemanticsNode&gt;' which excludes null.
 - 'List' is from 'dart:core'.
 - 'SemanticsNode' is from 'package:flutter/src/semantics/semantics.dart' ('../../../FlutterSDK/flutter/packages/flutter/lib/src/semantics/semantics.dart').
    for (int position = 0; position &lt; childrenInDefaultOrder!.length; position += 1) {
                                      ^
lib/utility/colors.dart:1:8: Error: Not found: 'dart:ui'
import 'dart:ui';
       ^
../../../FlutterSDK/flutter/packages/flutter/lib/src/widgets/app.dart:33:1: Error: Not found: 'dart:ui'
export 'dart:ui' show Locale;
^
../../../FlutterSDK/flutter/packages/flutter/lib/src/widgets/basic.dart:7:8: Error: Not found: 'dart:ui'
import 'dart:ui' as ui show Image, ImageFilter, TextHeightBehavior;
       ^
../../../FlutterSDK/flutter/packages/flutter/lib/src/widgets/binding.dart:9:8: Error: Not found: 'dart:ui'
import 'dart:ui' show AppLifecycleState, Locale, AccessibilityFeatures, FrameTiming, TimingsCallback;
       ^
../../../FlutterSDK/flutter/packages/flutter/lib/src/widgets/binding.dart:24:1: Error: Not found: 'dart:ui'
export 'dart:ui' show AppLifecycleState, Locale;
^
../../../FlutterSDK/flutter/packages/flutter/lib/src/widgets/bottom_navigation_bar_item.dart:7:8: Error: Not found: 'dart:ui'
import 'dart:ui' show Color;
       ^
../../../FlutterSDK/flutter/packages/flutter/lib/src/widgets/color_filter.dart:7:8: Error: Not found: 'dart:ui'
import 'dart:ui';
       ^
../../../FlutterSDK/flutter/packages/flutter/lib/src/widgets/editable_text.dart:9:8: Error: Not found: 'dart:ui'
import 'dart:ui' as ui hide TextStyle;
       ^
../../../FlutterSDK/flutter/packages/flutter/lib/src/widgets/focus_manager.dart:8:8: Error: Not found: 'dart:ui'
import 'dart:ui';
       ^
../../../FlutterSDK/flutter/packages/flutter/lib/src/widgets/focus_traversal.dart:7:8: Error: Not found: 'dart:ui'
import 'dart:ui';
       ^
Stopping application instance.
Driver tests failed: 254
</code></pre>
",https://stackoverflow.com/questions/64820606/how-to-get-the-device-id-while-doing-integration-testing-in-flutter,"['flutter', 'flutterdriver']",908,False,4,1
How can I do integration testing in elasticsearch with spring-data-elasticsearch?,"<p>I am using spring-data-elasticsearch v3.2.4.RELEASE which is available via spring-boot-starter-data-elasticsearch v2.2.4.RELEASE. 
I want to do the integration tests for this but the available option which is this:
<a href=""https://github.com/allegro/embedded-elasticsearch"" rel=""nofollow noreferrer"">https://github.com/allegro/embedded-elasticsearch</a> not working.</p>

<p>The part which I tried to get started as POC is below and it is throwing exception:</p>

<pre><code>    public class EmbeddedElasticConfiguration {

    public static final String VERSION = ""6.8.4"";
    public static final String DOWNLOAD_DIRECTORY = ""&lt;path&gt;\\test-elasticsearch"";
    public static final String INSTALLATION_DIRECTORY = ""&lt;path&gt;\test-elasticsearch"";
    public static final String NAME = ""elasticsearch"";
    public static final String TRANSPORT_PORT = ""9300"";
    public static final String HTTP_CLIENT_PORT = ""9200"";
    public static final String TEST_INDEX = ""salesorder"";
    public static final String TEST_TYPE = ""salesorder"";
    public static final String RESOURCE_LOCATION = ""src/test/resources/salesorder-mapping.json"";
    private ObjectMapper objectMapper = new ObjectMapper();
    EmbeddedElastic embeddedElastic;

    @Test
    public void configure() throws IOException, InterruptedException {
        embeddedElastic = EmbeddedElastic.builder()
                .withElasticVersion(VERSION)
                .withSetting(TRANSPORT_TCP_PORT, 9300)
                .withSetting(CLUSTER_NAME, ""my-cluster"")
                //.withPlugin(""analysis-stempel"")
                .withDownloadDirectory(new File(DOWNLOAD_DIRECTORY))
                .withInstallationDirectory(new File(INSTALLATION_DIRECTORY))
                .withSetting(HTTP_PORT, 9200)
                .withIndex(TEST_INDEX, IndexSettings.builder()
                       .withType(TEST_TYPE, readMappingFromJson())
                     .build())
                .build();

        embeddedElastic.start();
    }

    private String readMappingFromJson() throws IOException {
        final File file = ResourceUtils.getFile(RESOURCE_LOCATION);
        String mapping = new String(Files.readAllBytes(file.toPath()));
        System.out.println(""mapping: ""+ mapping);
        return mapping;
    }

    @After
    public void stopServer() {
        embeddedElastic.stop();
    }
}
</code></pre>

<p>I am below getting below exception:</p>

<pre><code>pl.allegro.tech.embeddedelasticsearch.EmbeddedElasticsearchStartupException: Failed to start elasticsearch within time-out

    at pl.allegro.tech.embeddedelasticsearch.ElasticServer.waitForElasticToStart(ElasticServer.java:127)
    at pl.allegro.tech.embeddedelasticsearch.ElasticServer.start(ElasticServer.java:50)
    at pl.allegro.tech.embeddedelasticsearch.EmbeddedElastic.startElastic(EmbeddedElastic.java:82)
    at pl.allegro.tech.embeddedelasticsearch.EmbeddedElastic.start(EmbeddedElastic.java:63)
    at com.xxx.elasticsearch.adapter.configuration.EmbeddedElasticConfiguration.configure(EmbeddedElasticConfiguration.java:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
</code></pre>

<p>Can someone help with any other options for integration tests in elasticsearch with spring-data or How should I write integration tests for elasticsearch.</p>

<p>I know there are other answers on stackoverflow and other portals for embedded-elasticsearch but those are not working with my current elasticsearch version.</p>
",https://stackoverflow.com/questions/60435419/how-can-i-do-integration-testing-in-elasticsearch-with-spring-data-elasticsearch,"['java', 'elasticsearch', 'integration-testing', 'spring-data-elasticsearch', 'elasticsearch-6.8']",4836,True,3,1
Integration testing of a Spring Cloud application with the AWS Parameter Store,"<p>How to perform integration testing of a Spring Boot application reading properties from the AWS Parameter Store (dependency <code>org.springframework.cloud:spring-cloud-starter-aws-parameter-store-config</code>).</p>

<p>Should the AWS Parameter Store integration be disabled in integration tests?</p>

<p>How to use local server (or mock) instead of the real AWS Parameter Store in integration tests?</p>
",https://stackoverflow.com/questions/60915364/integration-testing-of-a-spring-cloud-application-with-the-aws-parameter-store,"['spring', 'amazon-web-services', 'spring-boot', 'spring-cloud', 'aws-parameter-store']",2058,True,3,1
How to do integration testing of KStream topology using spring-boot EmbeddedKafka?,"<p>I have a simple spring-boot KStream topology that transforms a string from lowercase to uppercase. I want my integration test to launch an embedded kafka, and then test the topology. I would like to know if it possible to write integration tests like these using spring <code>@EmbeddedKafka</code>?</p>
<p>I have seen several examples using <code>@EmbeddedKafka</code> with simple consumers using <code>@KafkaListener</code> but not any that uses KStream.</p>
<p>I tried attempting to test the following topology to transform from incoming text stream from lowercase to uppercase.</p>
<p>Here's the topology:</p>
<pre class=""lang-java prettyprint-override""><code>
    @Configuration
    public class UppercaseStream {
    
        private static final String LOWERCASE_TOPIC = &quot;t.lower.case&quot;;
        private static final String UPPERCASE_TOPIC = &quot;t.upper.case&quot;;
    
        @Bean
        @Qualifier(&quot;kStreamPromoToUppercase&quot;)
        public KStream&lt;String, String&gt; kStreamPromoToUppercase(StreamsBuilder builder) {
    
            KStream&lt;String, String&gt; sourceStream = builder
                    .stream(LOWERCASE_TOPIC, Consumed.with(Serdes.String(), Serdes.String()));
    
            sourceStream.print(Printed.&lt;String, String&gt;toSysOut().withLabel(&quot;Original KStream...&quot;));
    
            KStream&lt;String, String&gt; upperCaseStream = sourceStream.mapValues(text -&gt; text.toUpperCase());
    
            upperCaseStream.print(Printed.&lt;String, String&gt;toSysOut().withLabel(&quot;Uppercase KStream...&quot;));
    
            upperCaseStream.to(UPPERCASE_TOPIC);
    
            return upperCaseStream;
        }
    }

</code></pre>
<p>The unit test that tests the topology is:</p>
<pre class=""lang-java prettyprint-override""><code>
    @TestInstance(TestInstance.Lifecycle.PER_CLASS)
    public class UpperCaseTopologyTest {
        TopologyTestDriver testDriver;
    
        @AfterAll
        void tearDown(){
            testDriver.close();
        }
    
        @Test
        @DisplayName(&quot;should transform lowercase to uppercase words&quot;)
        void shouldTransformLowercaseWords() {
            //Given
            StreamsBuilder builder = new StreamsBuilder();
            new UppercaseStream().kStreamPromoToUppercase(builder);
    
            Topology topology = builder.build();
            // setup test driver
            Properties props = new Properties();
            props.put(StreamsConfig.APPLICATION_ID_CONFIG, &quot;kafka-stream&quot;);
            props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, &quot;localhost:9092&quot;);
            props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
            props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
    
            //Create a Topology Test Driver 
            testDriver = new TopologyTestDriver(topology, props);
            TestInputTopic&lt;String, String&gt; inputTopic = testDriver.createInputTopic(&quot;t.lower.case&quot;, new Serdes.StringSerde().serializer(), new Serdes.StringSerde().serializer());
            TestOutputTopic&lt;String, String&gt; outputTopic = testDriver.createOutputTopic(&quot;t.upper.case&quot;, new Serdes.StringSerde().deserializer(), new Serdes.StringSerde().deserializer());
    
            //When
            inputTopic.pipeInput(&quot;test&quot;);
    
            //Then
            assertThat(outputTopic.readValue()).isEqualTo(&quot;TEST&quot;);
        }
    }

</code></pre>
<p>I want to write an integration test that first launches an embedded kafka server and then test the UppercaseStream topology.</p>
<p>I tried the following:</p>
<pre class=""lang-java prettyprint-override""><code>
    @SpringBootTest
    @DirtiesContext
    @EmbeddedKafka(partitions = 1, brokerProperties = { &quot;listeners=PLAINTEXT://localhost:9092&quot;, &quot;port=9092&quot; })
    class EmbeddedKafkaIntegrationTest {
    
        @Autowired
        public KafkaTemplate&lt;String, String&gt; template;
        @Autowired
        private KafkaConsumer consumer;
        private KafkaStreams kafkaStreams;
    
        @Value(&quot;${test.topic}&quot;)
        private String topic;
    
        @Autowired
        private KafkaStreamsConfiguration kafkaStreamsConfiguration;
        
        @Test
        public void should_transform_lowercase_to_uppercase() throws Exception {
            //Create a StreamsBuilder
            StreamsBuilder streamsBuilder = new StreamsBuilder();
            streamsBuilder.stream(topic, Consumed.with(new Serdes.StringSerde(), new Serdes.StringSerde()));
    
            //Add a topology
            new UppercaseStream().kStreamPromoToUppercase(streamsBuilder);
            kafkaStreams = new KafkaStreams(streamsBuilder.build(), kafkaStreamsConfiguration.asProperties());
    
            kafkaStreams.start();
            template.send(topic, &quot;test&quot;);
            consumer.getLatch().await(10000, TimeUnit.MILLISECONDS);
    
            assertThat(consumer.getLatch().getCount(), equalTo(0L));
            assertThat(consumer.getPayload(), containsString(&quot;TEST&quot;));
        }
    
        @After
        public void tearDown() {
            if (kafkaStreams!= null) kafkaStreams.close();
    
        }
    }
</code></pre>
<p>The test fails the assertion. I am not sure how to get kStreamPromoToUppercase bean. I am not sure if I am trying following the correct approach.</p>
",https://stackoverflow.com/questions/65043793/how-to-do-integration-testing-of-kstream-topology-using-spring-boot-embeddedkafk,"['apache-kafka', 'apache-kafka-streams', 'spring-kafka', 'spring-kafka-test']",2198,True,1,2
How to start spring boot application for the sake of integration testing,"<p>I am wondering. How do you start a springboot application from a unit test? I am working on building an integration test suite, and I want to start the application in the test so the integration tests can run. It seems like there should be a pretty straight forward way to do this, but I don't see how to do it.</p>
",https://stackoverflow.com/questions/61021446/how-to-start-spring-boot-application-for-the-sake-of-integration-testing,"['java', 'spring']",11,False,0,0
How to do integration testing using Fongo (Fake mongo) in Spring Boot,"<p>I am working on spring boot application with mongodb as backend.</p>
<p>mongorepository for crud operation</p>
<p>I want to do integration testing using fake mongo (fongo)</p>
<p>I have taken reference from following link to do integration testing using fongo but no luck.</p>
<p><a href=""https://www.paradigmadigital.com/dev/tests-integrados-spring-boot-fongo/"" rel=""nofollow noreferrer"">https://www.paradigmadigital.com/dev/tests-integrados-spring-boot-fongo/</a></p>
<p>INTEGRATION test is trying to connect to real database and IT fails</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { ConfigServerWithFongoConfiguration.class }, properties = {
        &quot;server.port=8980&quot; }, webEnvironment = WebEnvironment.DEFINED_PORT)
@AutoConfigureMockMvc
@TestPropertySource(properties = { &quot;spring.data.mongodb.database=test&quot; })
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class PersonControllerITest {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private MockMvc mockMvc;

    private ObjectMapper jsonMapper;

    @Before
    public void setUp() {
        jsonMapper = new ObjectMapper();
    }

    @Test
    public void testGetPerson() throws Exception {

        Person personFongo = new Person();
        personFongo.setId(1);
        personFongo.setName(&quot;Name1&quot;);
        personFongo.setAddress(&quot;Address1&quot;);
        mongoTemplate.createCollection(&quot;person&quot;);
        mongoTemplate.insert(personFongo);

        ResultActions resultAction = mockMvc.perform(MockMvcRequestBuilders.get(&quot;http://localhost:8090/api/person/1&quot;));
        resultAction.andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
        MvcResult result = resultAction.andReturn();
        Person personResponse = jsonMapper.readValue(result.getResponse().getContentAsString(), Person.class);
        Assert.assertEquals(1, personResponse.getId());
        Assert.assertEquals(&quot;Name1&quot;, personResponse.getName());
        Assert.assertEquals(&quot;Address1&quot;, personResponse.getAddress());

    }

    @Test
    public void testCreatePerson() throws Exception {

        Person personRequest = new Person();
        personRequest.setId(1);
        personRequest.setName(&quot;Name1&quot;);
        personRequest.setAddress(&quot;Address1&quot;);

        String body = jsonMapper.writeValueAsString(personRequest);

        ResultActions resultAction = mockMvc.perform(MockMvcRequestBuilders.post(&quot;http://localhost:8090/api/person&quot;)
                .contentType(MediaType.APPLICATION_JSON).content(body));
        resultAction.andExpect(MockMvcResultMatchers.status().isCreated());

        Person personFongo = mongoTemplate.findOne(new Query(Criteria.where(&quot;id&quot;).is(1)), Person.class);
        Assert.assertEquals(personFongo.getName(), &quot;Name1&quot;);
        Assert.assertEquals(personFongo.getAddress(), &quot;Address1&quot;);
    }
}
</code></pre>
<p>I am getting following error while executing Integration test</p>
<pre><code>   java.lang.IllegalStateException: Failed to load ApplicationContext
    
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
        at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
        at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
        at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig': Unsatisfied dependency expressed through field 'entitlementsRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entitlementsRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        ... 25 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entitlementsRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1531)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1276)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        
        ... 44 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
        
        ... 57 more
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 66 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        
        ... 67 more
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 89 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.obtainBeanInstanceFromFactory(ConfigurationClassEnhancer.java:389)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.mongoClient(&lt;generated&gt;)
        at com.company.myapp.configs.MongoConfig.mongoDbFactory(MongoConfig.java:73)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.CGLIB$mongoDbFactory$1(&lt;generated&gt;)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08$$FastClassBySpringCGLIB$$50ee8948.invoke(&lt;generated&gt;)
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.mongoDbFactory(&lt;generated&gt;)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
        ... 90 more
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 112 more
    Caused by: java.lang.NullPointerException
        at java.util.Hashtable.put(Hashtable.java:460)
        at java.util.Properties.setProperty(Properties.java:166)
        at java.lang.System.setProperty(System.java:796)
        at com.company.myapp.configs.MongoConfig.mongoClient(MongoConfig.java:78)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.CGLIB$mongoClient$3(&lt;generated&gt;)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08$$FastClassBySpringCGLIB$$50ee8948.invoke(&lt;generated&gt;)
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.mongoClient(&lt;generated&gt;)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
        ... 113 more
</code></pre>
<p>My main Application.java</p>
<pre><code>@SpringBootApplication(exclude = {MongoDataAutoConfiguration.class, MongoAutoConfiguration.class})
@EntityScan(basePackageClasses = Jsr310Converters.class)
@ComponentScan(basePackages = {&quot;com.company.myapp&quot;, &quot;com.company.myapp.repository&quot;})
@AutoConfigureAfter(MongoConfig.class)
@EnableSwagger2
@EnableScheduling
public class Application
{
public class Application
{
    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    @Value(&quot;${http.port}&quot;)
    int httpPort;

    @Value(&quot;${ssl.port}&quot;)
    int sslPort;

    @Value(&quot;${ssl.keystore.file}&quot;)
    String keyStoreFile;

    @Value(&quot;${ssl.keystore.password}&quot;)
    String keyStorePassword;

    @Autowired
    FileUtil fileUtil;

    public static void main(String[] args)
    {
        Runtime.getRuntime().addShutdownHook(new Thread() {                       
            @Override
            public void run() {
                logger.info(&quot;myapp server shutdown initiated&quot;);
                LogManager.shutdown();
                logger.info(&quot;myapp server shutdown completed&quot;);
            }
        });
        SpringApplication.run(Application.class, args);                          
    }

    @Bean
    public CompressingFilter compressingFilter()
    {
        return new CompressingFilter();
    }

    @Bean
    public EmbeddedServletContainerFactory servletContainer()
    {
        String keystore = &quot;dev&quot;;

        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) con -&gt; {
                    //if (&quot;true&quot;.equalsIgnoreCase(sslEnabled)) {
                    logger.info(&quot;----------------------------------------- Initialising ssl endpoint -------------------------------------&quot;);
                    Http11NioProtocol proto = (Http11NioProtocol) con.getProtocolHandler();
                    proto.setSSLEnabled(true);
                    con.setScheme(&quot;https&quot;);
                    con.setSecure(true);
                    con.setPort(sslPort);
                    proto.setKeystoreFile(fileUtil.getConfigFilePath(keyStoreFile));
                    proto.setKeystorePass(keystore);
                    proto.setKeyPass(keystore);
                    logger.info(&quot;---------------------------------------- Initialised ssl endpoint ----------------------------------------&quot;);
                    //}
                });

        tomcat.addAdditionalTomcatConnectors(createStandardConnector());
        return tomcat;
    }

    private Connector createStandardConnector()
    {
        Connector connector = new Connector(&quot;org.apache.coyote.http11.Http11NioProtocol&quot;);
        connector.setPort(httpPort);
        return connector;
    }
}
</code></pre>
<p><strong>AbstractFongoBaseConfiguration.java</strong></p>
<pre><code>@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public abstract class AbstractFongoBaseConfiguration extends AbstractMongoConfiguration{

    @Autowired
    private Environment env;

    @Override
    protected String getDatabaseName() {
        return env.getRequiredProperty(&quot;spring.data.mongodb.database&quot;);
    }

    @Override
    public Mongo mongo() throws Exception {
        return new Fongo(getDatabaseName()).getMongo();
    }
}
</code></pre>
<p><strong>ConfigServerWithFongoConfiguration.java</strong></p>
<pre><code>@EnableAutoConfiguration(exclude = { EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class,
        MongoDataAutoConfiguration.class })
@Configuration
@ComponentScan(basePackages = { &quot;com.company.myapp&quot; }, excludeFilters = {
        @ComponentScan.Filter(classes = { SpringBootApplication.class }) })
public class ConfigServerWithFongoConfiguration extends AbstractFongoBaseConfiguration {

}
</code></pre>
<p>Could you please suggest , what needs to be done to resolve this issue ?</p>
",https://stackoverflow.com/questions/63347525/how-to-do-integration-testing-using-fongo-fake-mongo-in-spring-boot,"['java', 'mongodb', 'integration-testing', 'fongo']",2568,True,0,3
Android Kotlin: Integration testing if the current activity or app is closed,"<p>I am working on an Android Kotlin project. I am writing integration/ UI tests for my application using the Expresso test framework. I am trying to write a test for a scenario where my application is closed or the first/ main activity currently open is closed. But it is not working.</p>

<p>See my test code below.</p>

<pre><code>@RunWith(AndroidJUnit4::class)
@LargeTest
class EventListTest: TestBuilder()
{
    @get:Rule
    val eventListActivityRule: ActivityTestRule&lt;EventListActivity&gt; = ActivityTestRule&lt;EventListActivity&gt;(EventListActivity::class.java, true, false)

    @Test
    fun itFinishesActivityWhenLogoutMenuItemIsTapped() {
        FakeEventService.SCENARIO_UNDER_TEST = 0
        this.eventListActivityRule.launchActivity(null)
        Intents.init()
        openActionBarOverflowOrOptionsMenu(ApplicationProvider.getApplicationContext&lt;Context&gt;())
        onView(withText(eventListActivityRule.activity.resources.getString(R.string.menu_item_logout))).perform(click())

        intended(not(hasComponent(EventListActivity::class.java.name)))
        Intents.release()
    }

}
</code></pre>

<p>Basically, I am testing that it closes the current activity when the log out menu item is clicked. Since the current activity (EventListActiivty) is the only open activity, it will finish the app. In the activity class, it closes itself using finish() method. But when I run the test, I got the following error.</p>

<pre><code>W/example.mement: Accessing hidden field Landroid/app/Activity;-&gt;mResultCode:I (light greylist, reflection)
W/example.mement: Accessing hidden field Landroid/app/Activity;-&gt;mResultData:Landroid/content/Intent; (light greylist, reflection)
E/TestRunner: failed: itFinishesActivityWhenLogoutMenuItemIsTapped(com.example.memento.EventListTest)
E/TestRunner: ----- begin exception -----
E/TestRunner: junit.framework.AssertionFailedError: Wanted to match 1 intents. Actually matched 0 intents.

    IntentMatcher: not has component: has component with: class name: is ""com.example.memento.EventListActivity"" package name: an instance of java.lang.String short class name: an instance of java.lang.String

    Matched intents:[]

    Recorded intents:[]
        at junit.framework.Assert.fail(Assert.java:50)
        at androidx.test.espresso.intent.VerificationModes$Times.verify(VerificationModes.java:80)
        at androidx.test.espresso.intent.Intents.internalIntended(Intents.java:346)
        at androidx.test.espresso.intent.Intents$3.run(Intents.java:204)
        at androidx.test.espresso.intent.Intents$PropogatingRunnable.run(Intents.java:224)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.app.Instrumentation$SyncRunnable.run(Instrumentation.java:2163)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
E/TestRunner: ----- end exception -----
I/TestRunner: finished: itFinishesActivityWhenLogoutMenuItemIsTapped(com.example.memento.EventListTest)
</code></pre>

<p>How can I test this scenario and how can I fix my code?</p>

<p>I also used this.</p>

<pre><code>Assert.assertTrue(eventListActivityRule.activity.isDestroyed)
</code></pre>

<p>But it is not working either.</p>
",https://stackoverflow.com/questions/61134835/android-kotlin-integration-testing-if-the-current-activity-or-app-is-closed,"['android', 'kotlin', 'android-activity', 'integration-testing', 'ui-testing']",443,False,0,1
How to disable auto-redirect when integration testing in ASP.NET Core 3,"<p>I have a controller endpoint that returns a <code>RedirectRequest</code> (status code 308). I am upgrading from ASP.NET Core 2.2 to 3.0, and will upgrade to 3.1 once the 3.0 upgrade is complete. I had an integration test that was working in .NET 2.2 that made a request to my redirected endpoint and confirmed it returns a 308. I also had a test that confirmed that my <code>/swagger</code> endpoint redirected to <code>/swagger/index.html</code>. It appears that both of these tests now are seeing the redirect response and automatically redirecting. My <code>/swagger</code> test returns a 200 with the contents of <code>/swagger/index.html</code>. My redirect to an external url that does not exist returns a 404 (I am using the test <code>HttpClient</code> so real sites would not load). </p>

<p>Controller:</p>

<pre class=""lang-cs prettyprint-override""><code>using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace MyService.Controllers
{
    [ApiController]
    public class MyController : ControllerBase
    {
        [HttpGet]
        [Route(""myroute"")]
        [ProducesResponseType(308)]
        [AllowAnonymous]
        public IActionResult MyEndpoint()
        {
            return new RedirectResult(""https://google.com/"", true, true);
        }
    }
}

</code></pre>

<p>My tests:</p>

<pre class=""lang-cs prettyprint-override""><code>using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Xunit;

namespace MyService.UnitTests.ControllerTests
{
    public class MyControllerTests : IClassFixture&lt;ControllerTestWebApplicationFactory&lt;Startup&gt;&gt;
    {
        private readonly ControllerTestWebApplicationFactory&lt;Startup&gt; _factory;

        public MyControllerTests(ControllerTestWebApplicationFactory&lt;Startup&gt; factory)
        {
            _factory = factory;
        }

        private HttpClient GetHttpClient()
        {
            return _factory.CreateClient();
        }

        [Fact]
        public async Task RedirectTest()
        {
            using (var client = GetHttpClient())
            {
                var request = new HttpRequestMessage(HttpMethod.Get, ""/myroute"");
                var response = await client.SendAsync(request);

                await response.AssertStatus(StatusCodes.Status308PermanentRedirect);
                var res = await response.Content.ReadAsStringAsync();
                Assert.Empty(res);
                Assert.Equal(""https://google.com"", response.Headers.Location.AbsoluteUri);
            }
        }

        [Fact]
        public async Task Swagger()
        {
            using (var client = GetHttpClient())
            {
                var request = new HttpRequestMessage(HttpMethod.Get, ""/swagger"");
                var response = await client.SendAsync(request);

                // This code passes in 2.2
                // await response.AssertStatus(StatusCodes.Status308);
                // var res = await response.Content.ReadAsStringAsync();
                // Assert.Empty(res);
                // Assert.Equal(""swagger/index.html"", response.Headers?.Location.OriginalString);

                // This code passes in 3.0
                await response.AssertStatus(StatusCodes.Status200OK);
                var res = await response.Content.ReadAsStringAsync();
                Assert.StartsWith(""&lt;!-- HTML for static distribution bundle"", res);
                Assert.Null(response.Headers?.Location);
            }
        }
    }
}
</code></pre>

<p>It looks like the tests are resolving the 30x response to the final location, but I want to prevent this automatic redirect so that I can test that the redirect is in place when I expect. Especially with the <code>myroute</code> endpoint that resolves to an external endpoint, since this creates a 404 in the test, I would not be able to tell the difference between the endpoint being deleted entirely and the redirect working as expected.</p>
",https://stackoverflow.com/questions/60019975/how-to-disable-auto-redirect-when-integration-testing-in-asp-net-core-3,"['c#', 'asp.net', 'asp.net-core', 'asp.net-core-3.0']",2100,True,0,2
How to run embedded Tomcat 9 inside Maven 3 for integration testing purposes?,"<p>I am trying to run embedded Tomcat 9 inside Maven 3 for integration testing purposes. I was led to <code>cargo-maven2-plugin</code> by other SO answers.</p>

<p>So, attempting to follow the instructions found here:</p>

<blockquote>
  <p><a href=""https://codehaus-cargo.github.io/cargo/Static+deployment+of+WAR.html"" rel=""nofollow noreferrer"">https://codehaus-cargo.github.io/cargo/Static+deployment+of+WAR.html</a></p>
</blockquote>

<p>I have this fragment in a simple POM:</p>

<pre><code>&lt;build&gt;
    &lt;plugins&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.codehaus.cargo&lt;/groupId&gt;
            &lt;artifactId&gt;cargo-maven2-plugin&lt;/artifactId&gt;
            &lt;version&gt;1.7.6&lt;/version&gt;
            &lt;configuration&gt;
                &lt;container&gt;
                    &lt;containerId&gt;tomcat9x&lt;/containerId&gt;
                    &lt;type&gt;embedded&lt;/type&gt;
                &lt;/container&gt;
                &lt;deployables&gt;
                    &lt;deployable&gt;
                        &lt;type&gt;war&lt;/type&gt;
                        &lt;properties&gt;
                            &lt;file&gt;path/to/myapp.war&lt;/file&gt;
                        &lt;/properties&gt;
                    &lt;/deployable&gt;
                &lt;/deployables&gt;
            &lt;/configuration&gt;
        &lt;/plugin&gt;
    &lt;/plugins&gt;
&lt;/build&gt;
</code></pre>

<p>Which I try to execute with <code>mvn org.codehaus.cargo:cargo-maven2-plugin:run</code></p>

<p>It fails with the error:</p>

<blockquote>
  <p>[INFO] [en2.ContainerRunMojo] Resolved container artifact
  org.codehaus.cargo:cargo-core-container-tomcat:jar:1.7.6 for container
  tomcat9x [WARNING] The defined deployable has the same groupId and
  artifactId as your project's main artifact but the type is different.
  You've defined a [war] type wher eas the project's packaging is [pom].
  This is possibly an error and as a consequence the plugin will try to
  find this deployable in the project's dependencies.</p>
</blockquote>

<p>How can I make this work? I just want to launch the given WAR in an embedded tomcat9, from within Maven.</p>
",https://stackoverflow.com/questions/59924534/how-to-run-embedded-tomcat-9-inside-maven-3-for-integration-testing-purposes,"['maven', 'tomcat9', 'cargo', 'maven-cargo']",5020,True,4,1
Running integration testing for Flutter on Azure Devops pipeline for UI automation testing,"<p>I would like to run automated UI testing using flutter driver on Azure Devops Pipelines and I'm using <a href=""https://github.com/aloisdeniel/vsts-flutter-tasks%20%20https://marketplace.visualstudio.com/items?itemName=aloisdeniel.flutter"" rel=""nofollow noreferrer"">Flutter Tasks by Alois Daniel</a>. There is no flutter driver support currenly on the azure flutter tasks plugin. We are looking for tasks where it would start up the simulators for Android and iOS while running flutter driver tests. We are running a vm-image for macos-latest in azure devops pipeline yml file.</p>
",https://stackoverflow.com/questions/65006575/running-integration-testing-for-flutter-on-azure-devops-pipeline-for-ui-automati,"['azure-devops', 'azure-pipelines', 'flutter-test']",1502,True,3,2
Running Integration Testing with WebApplicationFactory throws CancellationTokenSource has been disposed on Test Class Cleanup,"<p>I have a few Web Api Controller tests. These are built with the WebApplicationFactory provided by .NET Core Tests.</p>
<ul>
<li>When I run these Controller tests one-by-one, they all pass.</li>
<li>When I run these Controller test all at once (in Visual Studio, right click the Test-project and choose &quot;Run Tests&quot;) all the tests fail, except randomly one.</li>
</ul>
<p><strong>Print-screen 1</strong>: all success</p>
<p><a href=""https://i.stack.imgur.com/3xYJK.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/3xYJK.png"" alt=""All tests success one by one"" /></a></p>
<p><strong>Print-screen 2</strong>: all failed, except one:</p>
<p><a href=""https://i.stack.imgur.com/Er3cg.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/Er3cg.png"" alt=""all failed, except one"" /></a></p>
<p>All the tests consists of a [Theory] passing in MemberData to test various security combinations.</p>
<pre><code>7)  Project.UserRolesControllerTests.GetUserDetailsById_ReturnsConfiguredResult
  Duration: 1 ms

  Message: 
    [Test Class Cleanup Failure (Project.Controllers.UserRolesControllerTests)]: System.ObjectDisposedException : The CancellationTokenSource has been disposed.
  Stack Trace: 
    CancellationTokenSource.ThrowObjectDisposedException()
    RedisStorage.Dispose()
    Disposer.Dispose(Boolean disposing) line 38
    Disposable.Dispose() line 32
    LifetimeScope.Dispose(Boolean disposing) line 414
    Disposable.Dispose() line 32
    Container.Dispose(Boolean disposing) line 142
    Disposable.Dispose() line 32
    AutofacServiceProvider.Dispose() line 121
    WebHost.Dispose()
    WebApplicationFactory`1.Dispose(Boolean disposing)
    WebApplicationFactory`1.Dispose()
</code></pre>
<p>I have found a <a href=""https://github.com/dotnet/runtime/issues/39911"" rel=""noreferrer"">Github issue</a> on the Dotnet Runtime project <a href=""https://github.com/dotnet/runtime/issues/39911"" rel=""noreferrer"">here</a>. However, I'm not sure it's the same issue. Also, I can't seem to get the workaround fixed.</p>
<p>Any one has experience with this? I can run these tests manually for now, but it will also be part of the CI pipeline on DevOps. I persume it will break there as well.</p>
<p>Many thanks in advance.</p>
<p>EDIT: add used code</p>
<pre><code>public class MyCustomWebApplicationFactory&lt;TStartup&gt;
    : WebApplicationFactory&lt;TStartup&gt; where TStartup : class
{
    private UserConfiguration _userConfiguration;

    public void SetUser(UserConfiguration userConfiguration)
    {
        _userConfiguration = userConfiguration;
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        base.ConfigureWebHost(builder);

        Environment.SetEnvironmentVariable(&quot;Statistics:RedisDb&quot;, &quot;&lt;conn. string&gt;&quot;);

        builder.ConfigureTestServices(services =&gt;
        {
            services.AddMvc(options =&gt;
            {
                options.Filters.Add(new AllowAnonymousFilter()); // Remove entire JWT-requirement for all controllers during test
            });
            services.AddScoped&lt;IJwtService&gt;(instance =&gt;
            {
                var customJwtService = new CustomJwtService(() =&gt; _userConfiguration);

                return customJwtService;
            });
            services.AddScoped&lt;IHttpRequestHeaderService&gt;(instance =&gt;
            new CustomHttpRequestHeaderService(() =&gt; _userConfiguration));
        });

        builder.UseEnvironment(&quot;Test&quot;);
    }
}

public class CommunityPostsControllerTests : IClassFixture&lt;MyCustomWebApplicationFactory&lt;CommunityPostsController&gt;&gt;
{
    private MyCustomWebApplicationFactory&lt;CommunityPostsController&gt; _factory;

    public CommunityPostsControllerTests(MyCustomWebApplicationFactory&lt;CommunityPostsController&gt; factory)
    {
        _factory = factory;
    }

    public static IEnumerable&lt;object[]&gt; RoleAccess =&gt; new List&lt;object[]&gt;
    {
        new object[] { UserConfigurations.AdminCi1, Ci1EmployeePostInGroup, HttpStatusCode.OK},
        new object[] { UserConfigurations.EmployeeCi1, Ci1ParentPostInGroup, HttpStatusCode.Forbidden},
        // Omitted for readability
    };

    [Theory]
    [MemberData(nameof(RoleAccess))]
    public async Task GetPostById_ReturnsConfiguredResult(UserConfiguration userConfiguration, int communityPostId, HttpStatusCode expectedCode)
    {
        // Arrange
        _factory.SetUser(userConfiguration);
        var client = _factory.CreateClient();

        // Act
        var result = await client.GetAsync($&quot;api/v1/communityposts/{communityPostId}&quot;, cancellationToken: CancellationToken.None);

        // Assert
        Assert.Equal(expectedCode, result.StatusCode);
    }
}
</code></pre>
<p>Edit: CI result</p>
<p>As expected, the Azure DevOps CI pipeline also encounters this issue. Below is the log/result:</p>
<pre><code>Microsoft(R) Test Execution Command Line Tool Version 16.7.0
Copyright (c) Microsoft Corporation.All rights reserved.

Starting test execution, please wait...

A total of 1 test files matched the specified pattern.
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
      No XML encryptor configured.Key { 8ad52f98 - 5736 - 4d40 - 85b9 - e758dd2823e4}
may be persisted to storage in unencrypted form.
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
      No XML encryptor configured. Key {fd541f11-452b-4089-afd4-5f8cf81c43af} may be persisted to storage in unencrypted form.
  [xUnit.net 00:00:46.30][Test Class Cleanup Failure(Project.WebApi.IntegrationTests.Controllers.CommunityPostsControllerTests)] System.ObjectDisposedException
X Project.WebApi.IntegrationTests.Controllers.CommunityPostsControllerTests.GetPostById_ReturnsConfiguredResult [1ms]
Error Message:
   [Test Class Cleanup Failure(Project.WebApi.IntegrationTests.Controllers.CommunityPostsControllerTests)]: System.ObjectDisposedException : The CancellationTokenSource has been disposed.
  Stack Trace:
     at System.Threading.CancellationTokenSource.ThrowObjectDisposedException()
   at Hangfire.Pro.Redis.RedisStorage.Dispose()
   at Autofac.Core.Disposer.Dispose(Boolean disposing) in / home / appveyor / projects / autofac / src / Autofac / Core / Disposer.cs:line 38
   at Autofac.Util.Disposable.Dispose() in / home / appveyor / projects / autofac / src / Autofac / Util / Disposable.cs:line 32
   at Autofac.Core.Lifetime.LifetimeScope.Dispose(Boolean disposing) in / home / appveyor / projects / autofac / src / Autofac / Core / Lifetime / LifetimeScope.cs:line 414
   at Autofac.Util.Disposable.Dispose() in / home / appveyor / projects / autofac / src / Autofac / Util / Disposable.cs:line 32
   at Autofac.Core.Container.Dispose(Boolean disposing) in / home / appveyor / projects / autofac / src / Autofac / Core / Container.cs:line 142
   at Autofac.Util.Disposable.Dispose() in / home / appveyor / projects / autofac / src / Autofac / Util / Disposable.cs:line 32
   at Autofac.Extensions.DependencyInjection.AutofacServiceProvider.Dispose() in / home / appveyor / projects / autofac - extensions - dependencyinjection / src / Autofac.Extensions.DependencyInjection / AutofacServiceProvider.cs:line 121
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.Dispose()
   at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.Dispose(Boolean disposing)
   at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.Dispose()
Results File: /home/vsts/work/_temp/_fv-az6-181_2020-11-02_12_27_22.trx

Test Run Failed.
Total tests: 49
     Passed: 48
     Failed: 1
</code></pre>
<p>EDIT: Package configs</p>
<pre><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;netcoreapp2.1&lt;/TargetFramework&gt;
    &lt;IsPackable&gt;false&lt;/IsPackable&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.AspNetCore.App&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Mvc.Testing&quot; Version=&quot;2.1.3&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;16.7.1&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;PrivateAssets&gt;all&lt;/PrivateAssets&gt;
      &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;
    &lt;/PackageReference&gt;
    &lt;PackageReference Include=&quot;coverlet.collector&quot; Version=&quot;1.3.0&quot;&gt;
      &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;
      &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;
    &lt;/PackageReference&gt;
  &lt;/ItemGroup&gt;
&lt;/Project&gt;
</code></pre>
",https://stackoverflow.com/questions/64645161/running-integration-testing-with-webapplicationfactory-throws-cancellationtokens,"['c#', 'asp.net-core', 'integration-testing', 'xunit']",2723,True,7,2
How to inject dependencies into Firebase/Google Cloud Functions? (unit &amp; integration testing),"<p>I don't know whether my question is really related to Firebase Cloud Functions, but I came across this problem trying to test my Firebase Cloud Functions.</p>

<p>Let's say I have a Firebase Cloud function written in NodeJS:</p>

<p><em>function.ts</em></p>

<pre><code>import * as functions from ""firebase-functions""
const admin = require(""firebase-admin"")

import * as authVerifier from ""../../auth/authVerifier""

export default functions.https.onRequest(async (req, res) =&gt; {
  let authId
  try {
    authId = await authVerifier.identifyClientRequest(req)
  } catch (err) {
    console.error(`Unauthorized request error: ${err}`)
    return res.status(401).send({
      error: ""Unauthorized request""
    })
  }
}
</code></pre>

<p>Usually I have an interface and can easily mock any class I want to test it.</p>

<p>And, for example, authVerifier looks like:</p>

<p><em>authVerifier.ts</em></p>

<pre><code>import * as express from ""express""

export async function identifyClientRequest(req: express.Request) {
  return true // whatever, it doesn't really matter, should be real logic here
}
</code></pre>

<p>I'm trying to test <em>function.ts</em> and I only can pass res and req into it, e.g:</p>

<p><em>function.test.ts</em></p>

<pre><code>it(""should verify client identity"", async () =&gt; {
  const req = {
    method: ""PUT""
  }

  const res = { }

  await myFunctions(req as express.Request, res as express.Response)

  // assert that authVerifier.identifyClientRequest(req) called with passed req
})
</code></pre>

<p>So the question is: <strong>how can I mock <code>authVerifier.identifyClientRequest(req)</code> to use different implementations in function.ts</strong> and in function.test.ts? </p>

<p>I don't really know NodeJS/TypeScript, so I wonder if I can import another mock class of authVerifier for test or something like that.</p>
",https://stackoverflow.com/questions/60881775/how-to-inject-dependencies-into-firebase-google-cloud-functions-unit-integra,"['node.js', 'typescript', 'firebase', 'unit-testing', 'google-cloud-functions']",883,False,1,1
Custom WebApplicationFactory in integration testing not registering services in Startup.cs (ASP.NET Core 3.1),"<p>I am running into an issue where I am using a custom <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1#customize-webapplicationfactory"" rel=""nofollow noreferrer"">WebApplicationFactory</a> and it is not registering the services in my Startup.cs. I am using Asp.Net core 3.1 and Xunit. </p>

<p>I have below in my API (startup.cs) registered using extension methods:</p>

<pre><code>public void ConfigureServices(IServiceCollection services)
        {
            services.AddBaseApiConfiguration(Configuration);

            services.AddRepositoryServices();

            services.AddApiServices();

            services.AddMediatrServices();
        }
</code></pre>

<p>Per MS documentation:</p>

<blockquote>
  <p>The SUT's database context is registered in its
  Startup.ConfigureServices method. The test app's
  builder.ConfigureServices callback is executed after the app's
  Startup.ConfigureServices code is executed.</p>
</blockquote>

<p>But above is not occurring. None of my services from the startup I am using are being registered (<strong><em>i.e. the 4 extension methods I have are never being called and are never registered)</em></strong>. This is causing a few problems: my DB context uses IMediatr in its constructor so that events can be published during context.SaveChangesAsync() (on success). But as my service is never registered, it fails to find it. How do I ensure that this takes place correctly?</p>

<p>Below is my custom factory:</p>

<pre><code>    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder
        .UseEnvironment(""Development"")
        .ConfigureServices(services =&gt;
        {
            // Remove the app's db context registrations
            var descriptor = services.SingleOrDefault(
                d =&gt; d.ServiceType ==
                    typeof(DbContextOptions&lt;AppDbContext&gt;));


            if (descriptor != null)
            {
                services.Remove(descriptor );
            }

            services.AddSingleton&lt;IDbConnectionFactoryService, SqliteConnectionFactoryService&gt;();

            // Add a database context using an in-memory 
            // database for testing.
            services.AddDbContext&lt;AppDbContext&gt;(options =&gt;
            {
                options.UseSqlite(""Data Source=sqlitedemo.db"");
            });

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

            // Create a scope to obtain a reference to the database context 
            using (var scope = sp.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var db = scopedServices.GetRequiredService&lt;AppDbContext&gt;();

                // Ensure the database is created.
                db .Database.EnsureDeleted();
                db .Database.EnsureCreated();
            }
        });
    }
</code></pre>

<p><strong>Edit:</strong> It seems the services in <code>Startup.cs</code> are being called <strong>after</strong> the CustomWebApplication factory services. This is completely odd as per .Net core 3.0, the order was changed to be the opposite. So why is this still occuring?</p>

<p><strong>Edit 2</strong>: Need to use ConfigureTestServices instead of ConfigureServices.</p>
",https://stackoverflow.com/questions/61181935/custom-webapplicationfactory-in-integration-testing-not-registering-services-in,"['c#', 'asp.net-core']",3697,True,1,2
"Integration Testing in .NET Core 3.1 with AutoMapper, WebApplicationFactory, Entity Framework, and DTOs","<p>We have an API with about a dozen integration tests. All the tests passed until I added some DTOs and used AutoMapper. Now, all the tests that test methods that use AutoMapper and the DTOs are failing. I have provided all the code needed to understand one of the failing tests. Also, I read a lot about AutoMapper and the following StackOverflow posts:</p>
<ol>
<li><a href=""https://stackoverflow.com/questions/43630620/integration-testing-with-automapper-fails-to-initialise-configuration"">Integration Testing with AutoMapper fails to initialise configuration</a></li>
<li><a href=""https://stackoverflow.com/questions/50944862/a-kind-of-integration-testing-in-asp-net-core-with-ef-and-automapper"">A kind of integration testing in ASP.NET Core, with EF and AutoMapper</a></li>
</ol>
<p><strong>Startup.cs</strong></p>
<p>This is our Startup.ConfigureServices(). I have tried every code block commented out and/or marked &quot;ATTEMPTED&quot;.</p>
<pre><code> public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddDbContext&lt;OurContext&gt;(options =&gt;
                options.UseSqlServer(Configuration[&quot;ConnectionString&quot;]))
            .AddDbContext&lt;OurContext&gt;()
            .AddRazorPages()
            .AddMvcOptions(options =&gt; options.EnableEndpointRouting = false)
            .AddNewtonsoftJson(options =&gt; options.SerializerSettings.ContractResolver = new DefaultContractResolver());
        services
            .AddControllersWithViews();

        //ATTEMPTED
        //services
        //    .AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

        //ATTEMPTED
        //MapperConfiguration mapperConfiguration = new MapperConfiguration(mc =&gt;
        //{
        //    mc.AddProfile(new OurProfile());
        //});
        //IMapper mapper = mapperConfiguration.CreateMapper();
        //services
        //    .AddSingleton(mapper);

        //ATTEMPTED
        //services
        //    .AddAutoMapper(typeof(Startup));

        //ATTEMPTED
        //var assembly = typeof(Program).GetTypeInfo().Assembly;
        //services
        //    .AddAutoMapper(assembly);

        //ATTEMPTED
        var assembly = typeof(Program).GetTypeInfo().Assembly;
        services.AddAutoMapper(cfg =&gt;
        {
            cfg.AllowNullDestinationValues = true;
            cfg.CreateMap&lt;OurModel, OurDto&gt;()
                .IgnoreAllPropertiesWithAnInaccessibleSetter();
        }, assembly);
    }
</code></pre>
<p><strong>Controller</strong></p>
<p>This is our controller.</p>
<pre><code>[Route(&quot;api/[controller]&quot;)]
[ApiController]
public class OurController : ControllerBase
{
    private readonly OurContext _context;

    protected readonly ILogger&lt;OurController&gt; Logger;

    private readonly IMapper _mapper;

    public OurController(OurContext context, ILogger&lt;OurController&gt; logger, 
        IMapper mapper)
    {
        _context = context ??
            throw new ArgumentNullException(nameof(context));
        Logger = logger ??
                 throw new ArgumentNullException(nameof(logger));
        _mapper = mapper ??
                  throw new ArgumentNullException(nameof(mapper));
    }

    [HttpGet]
    public async Task&lt;ActionResult&lt;IEnumerable&lt;OurDto&gt;&gt;&gt; GetAll()
    {

        IQueryable&lt;OurModel&gt; models = _context.OurModel;

        IQueryable&lt;OurDto&gt; dtos = 
            _mapper.Map&lt;IQueryable&lt;OurDto&gt;&gt;(models);

        return await dtos.ToListAsync();
    }
}
</code></pre>
<p><strong>Profile, Model, and DTO</strong></p>
<p>Profile</p>
<pre><code>public class OurProfile : Profile
{
    public OurProfile()
    {
        CreateMap&lt;OurModel, OurDto&gt;();
    }
}
</code></pre>
<p>Model</p>
<pre><code>public partial class OurModel
{
    public string Number { get; set; }
    public string Name1 { get; set; }
    public string Name2 { get; set; }
    public string Status { get; set; }
    public DateTime? Date { get; set; }
    public string Description { get; set; }
    public string Comment { get; set; }
    public string District { get; set; }
}
</code></pre>
<p>DTO</p>
<pre><code>public class OurDto
{
    public string Number { get; set; }
    public string Name1 { get; set; }
    public string Name2 { get; set; }
    public string Status { get; set; }
    public DateTime? Date { get; set; }
    public string Description { get; set; }
    public string Comment { get; set; }
    public string District { get; set; }
}
</code></pre>
<p><strong>Test Fixture</strong></p>
<p>This is our test fixture.</p>
<pre><code>public abstract class ApiClientFixture : IClassFixture&lt;WebApplicationFactory&lt;Startup&gt;&gt;
{
    private readonly WebApplicationFactory&lt;Startup&gt; _factory;

    protected abstract string RelativeUrl { get; }

    protected ApiClientFixture(WebApplicationFactory&lt;Startup&gt; factory)
    {
        _factory = factory;
    }

    protected HttpClient CreateClient()
    {
        HttpClient client;
        var builder = new UriBuilder();

        client = _factory.CreateClient();
        builder.Host = client.BaseAddress.Host;
        builder.Path = $&quot;{RelativeUrl}&quot;;

        client.BaseAddress = builder.Uri;
        return client;
    }
}
</code></pre>
<p><strong>Test</strong></p>
<p>This is our test class. The single test in this test class fails.</p>
<pre><code>public class Tests : ApiClientFixture
{
    public Tests(WebApplicationFactory&lt;Startup&gt; factory) : base(factory)
    {
    }

    protected override string RelativeUrl =&gt; &quot;api/OurController/&quot;;

    [Fact]
    public async void GetAllReturnsSomething()
    {
        var response = await CreateClient().GetAsync(&quot;&quot;);

        Assert.True(response.IsSuccessStatusCode);
    }
}
</code></pre>
<p>When I debug the test I see that a 500 status code is returned from the URL provided to the in-memory API.</p>
<p>Does anybody have some suggestions? More than half of our tests currently fail, and I suspect that AutoMapper is not configured properly for integration testing.</p>
",https://stackoverflow.com/questions/63510427/integration-testing-in-net-core-3-1-with-automapper-webapplicationfactory-ent,"['entity-framework', '.net-core', 'automapper', 'dto']",754,True,0,2
ASP.Net Core Integration testing failing due to webapp startup using reklative folder path,"<p>I am completely new to integration testing in asp.net core.
I have a asp.net core webapi and trying to setup integration testing for this api project.
When i try to run the basic test it fails due to the following in the configure method inside startup.cs:</p>
<pre><code>RegisterExcelTemplate(app, &quot;Upload/ExposureRating/Global/Template/&quot;, &quot;/api/upload/exposureRating/global&quot;);

private static void RegisterExcelTemplate(IApplicationBuilder applicationBuilder, string relativeFolderPath, string apiPath)
{
    applicationBuilder.UseFileServer(new FileServerOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), relativeFolderPath)),
        RequestPath = new PathString(apiPath),
        EnableDirectoryBrowsing = false
    });
}
</code></pre>
<p>When i run the test, getting the following error message:</p>
<p><a href=""https://i.stack.imgur.com/fOB8u.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/fOB8u.png"" alt=""This is the error while creating httpClient object"" /></a></p>
<p>Can anyone help how to fix the folder path issue in test project?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/63282996/asp-net-core-integration-testing-failing-due-to-webapp-startup-using-reklative-f,"['c#', 'integration-testing', 'asp.net-core-webapi', 'xunit', 'asp.net-core-3.1']",94,False,-1,1
TransactionScope doesn&#39;t rollback in per-test TearDown for integration testing using NUnit and TestServer,"<h2>Scenario</h2>

<p>I have an API on ASP.NET Core 2.0 that integrates with MS SQL database using EF Core. Now I am trying to setup integration/api tests for it using NUnit and <code>TestServer</code>. The issue is that I need to configure every test to be 'isolated' so basically it should clean up (rollback) DB after self. I cannot use compensation transactions to achieve the desired result due to the complexity of DB (lots of legacy stuff to account for, e.g. triggers etc).</p>

<h2>SUT API Setup</h2>

<p>Here is an example of API I am trying to test:</p>

<pre class=""lang-cs prettyprint-override""><code>// GET api/values
[HttpGet]
public async Task&lt;IActionResult&gt; Get(string dataName1, string dataName2)
{
    using (var scope = CreateScope())
    {
        await _service.DoWork(dataName1);
        await _service.DoWork(dataName2);
        scope.Complete();
    }
    return Ok();
}
</code></pre>

<p>The <code>DoWork()</code> method basically looks up an entity given passed parameter and increments its another property. Then simply calls <code>SaveChanges()</code>.
The <code>CreateScope()</code> is here a helper method that returns an instance of <code>TransactionScope</code>:</p>

<pre class=""lang-cs prettyprint-override""><code>return new TransactionScope(
    TransactionScopeOption.Required,
    new TransactionOptions() { IsolationLevel = IsolationLevel.RepeatableRead },
    TransactionScopeAsyncFlowOption.Enabled
);
</code></pre>

<h2>Integration Test Setup</h2>

<pre class=""lang-cs prettyprint-override""><code>[TestFixture]
[SingleThreaded]
[NonParallelizable]
public class TestTest
{
    private TransactionScope _scope;

    [Test]
    public async Task Test11()
    {
        _scope = CreateScope();
        var result = await Client.GetAsync(""api/values?dataName1=Name1&amp;dataName2=Name2"");
        Assert.DoesNotThrow(() =&gt; result.EnsureSuccessStatusCode());

        _scope.Dispose();
        _scope = null;
    }
}
</code></pre>

<p>Here the <code>Client</code> is an instance of <code>HttpClient</code> created by utilizing <code>Microsoft.AspNetCore.TestHost.TestServer</code> and <code>CreateScope()</code> method is actually the same as in the API.
This simple case works fine - the changes made by my SUT API are rollbacked successfully by calling <code>_scope.Dispose()</code> and DB returns to its 'clean' state.</p>

<h2>Problem</h2>

<p>Now I want to move the logic related to create/rollback of scope outside of my test method and put it in SetUp/TearDown so all my tests are automatically handled.</p>

<pre class=""lang-cs prettyprint-override""><code>[SetUp]
public async Task SetupTest()
{
    _scope = TransactionHelper.CreateScope();
}

[TearDown]
public async Task TeardownTest()
{
    _scope.Dispose();
    _scope = null;
}

[Test]
public async Task Test11()
{
    var result = await OneTimeTestFixtureStartup.Client.GetAsync(""api/values?dataName1=Name1&amp;dataName2=Name2"");
    Assert.DoesNotThrow(() =&gt; result.EnsureSuccessStatusCode());
}
</code></pre>

<p>But it does NOT work (I can see modifications in DB after test run) for some reason and I cannot figure it out.</p>

<p><em>Why? What am I missing?</em></p>

<p><strong>Note:</strong> both tests versions pass successfully.</p>
",https://stackoverflow.com/questions/60661394/transactionscope-doesnt-rollback-in-per-test-teardown-for-integration-testing-u,"['c#', 'transactions', 'nunit', 'integration-testing', 'asp.net-core-2.0']",1222,True,2,2
XUnit Integration Testing with Identityserver: Token received from Identityserver is unable to match key,"<p>I'm currently trying to implement Integration Testing in an environment with 2 servers:</p>
<ul>
<li>A .NET Core API server</li>
<li>An IdentityServer4 Authentication Server</li>
</ul>
<p>Through much struggle, I've managed to get the two to communicate with eachother, however, IdentityServer throws the following error when trying to confirm the JWT token (Through the API):</p>
<blockquote>
<p>Bearer was not authenticated. Failure message: IDX10501: Signature
validation failed. Unable to match key:  kid:
'8C1D5950D083E20D4B20DE9B37AC71FAEF679469'.</p>
</blockquote>
<p>I'll try to keep the code sample brief:</p>
<p>In the XUnit startup, I configure and create clients for both TestServers.</p>
<pre><code>    public APITestBase(ITestOutputHelper output)
    {
        _output = output;

        var apicon = new ConfigurationBuilder()
            .AddJsonFile(&quot;apisettings.json&quot;, optional: true, reloadOnChange: true)
            .Build();

        var authcon = new ConfigurationBuilder()
            .AddJsonFile(&quot;authsettings.json&quot;, optional: true, reloadOnChange: true)
            .Build();

        _authServer = new TestServer(new WebHostBuilder()
            .UseConfiguration(authcon)
            .ConfigureLogging(x =&gt; x.AddXUnit(_output))
            .UseEnvironment(&quot;Development&quot;)
            .UseStartup&lt;Auth.Startup&gt;());

        _authClient = _authServer.CreateClient();

        _server = new TestServer(new WebHostBuilder()
            .UseConfiguration(apicon)
            .ConfigureLogging(x =&gt; x.AddXUnit(_output))
            .UseEnvironment(&quot;Test&quot;)
            .ConfigureServices(
                  services =&gt; {
//Here, I'm adding an httpclienthandler. In the application I will use this as JWTBackChannelHandler. This allows communication between the two servers
                      services.AddSingleton&lt;HttpMessageHandler&gt;(_authServer.CreateHandler());
                  })
            .UseStartup&lt;Api.Startup&gt;());

        _client = _server.CreateClient();

        APIConfig = new Cnfg();
         
        apicon.Bind(&quot;APIConfig&quot;, APIConfig);

        //Make users in api

    }
</code></pre>
<p>Here is the actual test I am trying to run</p>
<pre><code>        [Fact]
        public async Task ApplyTest()
        {
            _client.SetBearerToken(await GetAccessToken());

            // Act
            var response = await _client.GetAsync($&quot;{APIConfig.ApiBaseUrl}api/call/&quot;);
             response.EnsureSuccessStatusCode();
        }
</code></pre>
<p>And here is GetAccessToken, which returns the JWT token that the integration uses to identify itself as a user... At least that's the plan.</p>
<pre><code>        protected async Task&lt;string&gt; GetAccessToken()
    {
        var disco = await _authClient.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest()
        {
            Address = _authServer.BaseAddress.ToString(),
            Policy =
                {
                    ValidateIssuerName = false
                }
        });

        if (!String.IsNullOrEmpty(disco.Error))
        {
            throw new Exception(disco.Error);
        }
        var response = await _authClient.RequestPasswordTokenAsync(new PasswordTokenRequest
        {
            Address = disco.TokenEndpoint,
            GrantType = &quot;password&quot;,
            ClientId = &quot;api&quot;,

            UserName = &quot;test@test.nl&quot;,
            Password = &quot;test&quot;
        });

        return response.AccessToken;
    }
</code></pre>
<p>The only identifiable difference I can find between a JWT token generated through this function and that of a normal website request is that the Public Key is missing (according to jwt.io).</p>
<p>Finally, because I think this bit might be useful, here's the part of the API's Startup.cs where I enforce the use of the JWTBackChannelHandler</p>
<pre><code>if (Environment.EnvironmentName == &quot;Test&quot;)
            {
                services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
                    .AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme, o =&gt;
                    {
                        o.JwtBackChannelHandler = _identityServerMessageHandler;
                        o.RequireHttpsMetadata = false;
                    })
                    .AddApiKeyAuthenication(o =&gt;
                    {
                        o.Keys.Add(&quot;****&quot;.ToSha256());
                        o.Keys.Add(&quot;****&quot;.ToSha256());
                    });
            }
</code></pre>
<p>Thank you very much in advance for your help, I've kind of reached the end of my wits with this one. Please let me know if you want any more information and I'll be happy to provide.</p>
",https://stackoverflow.com/questions/64555221/xunit-integration-testing-with-identityserver-token-received-from-identityserve,"['asp.net-core', 'jwt', 'identityserver4', 'xunit', 'testserver']",316,True,1,1
VSCode Extension Integration Testing: Opening of folder in the test stops the test run,"<p>I am writing integration tests in which I have to clone a repo and open the folder using <code>vscode.commands.executeCommand('vscode.openFolder', uri);</code> in test window and then run tests against it. But as soon as the folder opens up, the test stops.
There are already few questions on stackoverflow, but none of them presents an answer.</p>
<p><a href=""https://stackoverflow.com/questions/55456193/testing-a-vscode-extension-that-involves-opening-a-folder-workspace/63830094#63830094"">Testing a VSCode extension that involves opening a folder/workspace</a></p>
<p><a href=""https://stackoverflow.com/questions/61889998/vscode-tests-wont-proceed-after-using-executecommand-to-open-a-sample-project"">VSCode: Tests won&#39;t proceed after using executeCommand to open a sample project</a></p>
<p>I don't want to use Cypress Library.</p>
",https://stackoverflow.com/questions/63832243/vscode-extension-integration-testing-opening-of-folder-in-the-test-stops-the-te,"['visual-studio-code', 'vscode-extensions']",182,False,1,0
How to Use FakeMongo and Ignore MongoDB socket connection on Controller level Integration testing,"<p>I am using spring boot 1.5.x for  application. Database is MONGO</p>
<p>Using MongoRepository for crud operations.</p>
<p>Earlier in our project we got dedicated test database instance so we have added mongodb properties of test db in src\test\resources\application.properties.</p>
<p>Now we dont have test db so we want to use embedded/fake db to test our classes Controller/Services/Repository etc..</p>
<p>Options are - embeded mongodb like <strong>flapdoodle</strong> and <strong>fongo</strong></p>
<p>I tried 1 of solution <a href=""https://stackoverflow.com/a/45597381/297907"">de.flapdoodle.embed.mongo</a>    from <a href=""https://stackoverflow.com/questions/45594056/ignore-mongodb-socket-connection-on-spring-test"">SO question</a> to use flapdoodle</p>
<p>de.flapdoodle.embed.mongo trying to download zip outside network : unable-to-download-embedded-mongodb-behind-proxy-using-automatic-configuration</p>
<p>I tried fakemongo but its not working for unit and integration testing of controller. Its picking mongo database details of test db using application.properties present in test/resources</p>
<p><strong>pom.xml</strong></p>
<pre><code>        &lt;dependency&gt;
            &lt;groupId&gt;com.github.fakemongo&lt;/groupId&gt;
            &lt;artifactId&gt;fongo&lt;/artifactId&gt;
            &lt;version&gt;${fongo.version}&lt;/version&gt;
            &lt;!--&lt;scope&gt;test&lt;/scope&gt; --&gt;// not working, if removed it says cannot find mongo
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;com.lordofthejars&lt;/groupId&gt;
            &lt;artifactId&gt;nosqlunit-mongodb&lt;/artifactId&gt;
            &lt;version&gt;0.7.6&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
</code></pre>
<p><strong>FakeMongo</strong> Configuration</p>
<pre><code>package com.myapp.config;

import com.github.fakemongo.Fongo;
import com.mongodb.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;


@Configuration
@EnableMongoRepositories
public class FakeMongo extends AbstractMongoConfiguration {

    @Override
    protected String getDatabaseName() {
        return &quot;mockDB&quot;;
    }

    @Bean
    public MongoClient mongo() {
        Fongo fongo = new Fongo(&quot;mockDB&quot;);
        return fongo.getMongo();
    }

}
</code></pre>
<p><strong>TestFakeMongo</strong> It works. Test executed properly  - Reference <a href=""http://springboot.gluecoders.com/testing-mongodb-springdata.html"" rel=""nofollow noreferrer"">http://springboot.gluecoders.com/testing-mongodb-springdata.html</a></p>
<pre><code>package com.myapp.config;

import com.myapp.domain.entitlement.User;
import com.myapp.repository.UserRepository;
import com.lordofthejars.nosqlunit.annotation.UsingDataSet;
import com.lordofthejars.nosqlunit.core.LoadStrategyEnum;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import static org.junit.Assert.assertTrue;

@RunWith(SpringRunner.class)
@Import(value = {FakeMongo.class})
public class TestFakeMongo {

    @Autowired
    private ApplicationContext applicationContext;

    @Rule
    public MongoDbRule embeddedMongoDbRule = newMongoDbRule().defaultSpringMongoDb(&quot;mockDB&quot;);

    @MockBean
    private UserRepository userRepository;

    @Test
    @UsingDataSet(loadStrategy = LoadStrategyEnum.DELETE_ALL)
    public void getAllUsers_NoUsers() {
        List&lt;User&gt; users = userRepository.findAll();
        assertTrue(&quot;users list should be empty&quot;, users.isEmpty());
    }
}
</code></pre>
<p><strong>UserRepositoryTest</strong>  - Unit testing for Repository also working using <strong>fongo</strong> Reference - <a href=""http://dontpanic.42.nl/2015/02/in-memory-mongodb-for-unit-and.html"" rel=""nofollow noreferrer"">http://dontpanic.42.nl/2015/02/in-memory-mongodb-for-unit-and.html</a></p>
<pre><code>package com.myapp.repository;

import com.myapp.config.SpringUnitTest;
import com.myapp.domain.User;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

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

import static org.junit.Assert.*;


public class UserRepositoryTest extends SpringUnitTest {


    @Autowired
    private UserRepository userRepository;


    @Before
    public void setup() {
        importJSON(&quot;user&quot;, &quot;user/user.json&quot;);
    }

    @Test
    //@UsingDataSet(loadStrategy = LoadStrategyEnum.CLEAN_INSERT, locations = &quot;/json-data/user/user.json&quot;) // test/resources/..
    public void findUser_should_return_user() {
        User user = userRepository.findByXYZId(&quot;XX12345&quot;);
        assertNotNull(user);
    }

    @Test
    public void findUser_should_return_null() {
        User user = userRepository.findByXYZId(&quot;XX99999&quot;);
        assertNull(user);
    }

    @Test
    public void deleteUser_should_return_null() {
        userRepository.delete(&quot;XX12345&quot;);
        User user = userRepository.findByXYZId(&quot;XX12345&quot;);
        assertNull(user);
    }

    @Test
    public void saveUser_should_return_user() {
        User user = new User();
        user.setXYZId(&quot;XX12345&quot;);
        user.setAck(true);
        List&lt;DateTime&gt; dateTimeList = new ArrayList&lt;&gt;();
        dateTimeList.add(DateTime.now(DateTimeZone.UTC));
        user.setAckOn(dateTimeList);
        User dbUser = userRepository.save(user);
        assertEquals(user, dbUser);
    }

    @Test
    public void findAllUser_should_return_users() {
        List&lt;User&gt; userList = userRepository.findAll();
        assertEquals(1, userList.size());
    }
}
</code></pre>
<p>Controller level testing not working.. Reference- <a href=""https://www.paradigmadigital.com/dev/tests-integrados-spring-boot-fongo/"" rel=""nofollow noreferrer"">https://www.paradigmadigital.com/dev/tests-integrados-spring-boot-fongo/</a></p>
<p><strong>UserControllerTest</strong> failed java.lang.IllegalStateException: Failed to load ApplicationContext - At this point test mongo db details fetech instead of fongo test\resources\application.properties test server db details are loading</p>
<pre><code>package com.myapp.config;

package com.myapp.controllers;

import com.myapp.config.FakeMongo;
import com.myapp.services.persistance.UserService;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;

import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import static org.hamcrest.CoreMatchers.containsString;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@ActiveProfiles(&quot;it&quot;)
@RunWith(SpringRunner.class)
@SpringBootTest(
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
    classes =  Application.class
)
@Import(value = {FakeMongo.class})
@AutoConfigureMockMvc
@TestPropertySource(locations = &quot;classpath:application-it.properties&quot;)
public class UserControllerTest {


    @Rule
    public MongoDbRule embeddedMongoDbRule = newMongoDbRule().defaultSpringMongoDb(&quot;mockDB&quot;);

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService service;

    @Before
    public void setUp() throws Exception {
    }

    @Test
    public void deleteUser() throws Exception {
        Mockito.when(this.service.deleteUser(Mockito.anyString())).thenReturn(true);
        this.mockMvc.perform(delete(&quot;/User&quot;)).andDo(print()).andExpect(status().isOk())
                .andExpect((ResultMatcher) content().string(containsString(&quot;true&quot;)));
    }
}
</code></pre>
<p><strong>UserControllerTest</strong> Not working, failing with error <em>java.lang.IllegalStateException: Failed to load ApplicationContext</em> as its tries to connect to test instance of mongo database using application.properties present in test/resources</p>
<p><strong>Appreciate working example to use fakemongo while running Integration test for Controller level</strong></p>
<p>What changes, I need to do in code level(Controller class or any other class) or application.properties of test\resources ?</p>
",https://stackoverflow.com/questions/63265674/how-to-use-fakemongo-and-ignore-mongodb-socket-connection-on-controller-level-in,"['java', 'mongodb', 'spring-boot', 'junit']",727,False,1,0
"How should I perform integration testing on a SpringBoot library, that isn&#39;t an application","<p>First up, a disclaimer, I'm not entirely happy with the architecture of what I'm about to ask about!</p>
<p>We have a Spring based project that produces a library as a jar. That library includes all the usual controller/service/jpa (repositories) layers you might expect but no boot application to start it all up.</p>
<p>The idea being various projects within our organisation can import the jar and get instant addition of a common (HTTP) API.</p>
<p>Unit tests work ok.</p>
<p>*IT.java tests are another matter.
Run in isolation by the IDE from the test/java/ hierarchy they run ok and pass.</p>
<p>However when running via maven as part of the build they fail.
[ERROR]   ControllerIT » IllegalState Unable to find a @SpringBootConfiguration...</p>
<p>We have a Boot configuration in the test hierarchy which the ITs must be using when run via the IDE, but when running the maven build it seems it can't be found to start up the application (understandably as it is in the test package tree).
The boot file we do have is intended to be no more than a test harness to run the lib, to run the ITs.</p>
<p>We have h2 in the Maven test scope, but it isn't wanted in the final library (that is up to the host application to provide a datasource/connection etc).</p>
<p><strong>Requirement</strong>:</p>
<ul>
<li>Start up the API library in an application for testing</li>
<li>Run the tests as part of Maven build</li>
<li>H2 should not end up in final jar</li>
</ul>
<p><strong>Symptoms when running mvn install</strong>
[ERROR]   ControllerIT » IllegalState Unable to find a @SpringBootConfiguration...</p>
<p>Presumably need some config somewhere in pom? Already using package.Boot in the Springboot maven plugin config.
Maybe just need to figure out the magic config to point it at the src/test/... Boot.class rather than src/main/...Boot.class</p>
<p><strong>Question(s)</strong>:</p>
<p>Does spring have a 'correct' way to achieve what we want (I'd go with MicroServices, but not an option because ... reasons)?</p>
<p>How should we go about implementing ITs against a H2 driven SpringBoot application when we don't want to include the bootable class (or H2 lib) in product jar?</p>
<p>Should we be creating a separate Maven module just for the ITs (with a dependency on the library module)?</p>
<p>Abbreviated Maven pom:</p>
<pre><code>   &lt;properties&gt;
      &lt;version.spring-boot&gt;2.1.13.RELEASE&lt;/version.spring-boot&gt;
   &lt;/properties&gt;
   &lt;dependencyManagement&gt;
        &lt;dependencies&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-dependencies&lt;/artifactId&gt;
                &lt;version&gt;${version.spring-boot}&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;dependencies&gt;
      &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-rest&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-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;exclusion&gt;
                    &lt;groupId&gt;junit&lt;/groupId&gt;
                    &lt;artifactId&gt;junit&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
           &lt;dependency&gt;
              &lt;groupId&gt;com.h2database&lt;/groupId&gt;
              &lt;artifactId&gt;h2&lt;/artifactId&gt;
              &lt;scope&gt;test&lt;/scope&gt;
           &lt;/dependency&gt;
           &lt;dependency&gt;
            &lt;groupId&gt;org.mockito&lt;/groupId&gt;
            &lt;artifactId&gt;mockito-core&lt;/artifactId&gt;
            &lt;version&gt;2.28.2&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
           &lt;/dependency&gt;
           &lt;dependency&gt;
            &lt;groupId&gt;org.mockito&lt;/groupId&gt;
            &lt;artifactId&gt;mockito-junit-jupiter&lt;/artifactId&gt;
            &lt;version&gt;2.28.2&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
           &lt;/dependency&gt;
           &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter&lt;/artifactId&gt;
            &lt;version&gt;5.4.0&lt;/version&gt;
            &lt;type&gt;pom&lt;/type&gt;
            &lt;scope&gt;test&lt;/scope&gt;
           &lt;/dependency&gt;
           &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&gt;
            &lt;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;!-- other dependencies excluded for brevity --&gt;
     &lt;/dependencies&gt;
     &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
                &lt;version&gt;${version.spring-boot}&lt;/version&gt;
                &lt;configuration&gt;
                    &lt;!-- file lives in test hierarchy --&gt;
                    &lt;mainClass&gt;org.my.packages.test.Boot&lt;/mainClass&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
      
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
                &lt;version&gt;3.0.0-M5&lt;/version&gt;
              &lt;configuration&gt;
                &lt;skip&gt;true&lt;/skip&gt;&lt;!-- Skipping unit tests while trying to sort ITs --&gt;
              &lt;/configuration&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt;
                &lt;version&gt;3.0.0-M5&lt;/version&gt;
                &lt;configuration&gt;
                  &lt;failIfNoTests&gt;true&lt;/failIfNoTests&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;/execution&gt;
             &lt;/plugin&gt;
        &lt;/plugins&gt;
&lt;/build&gt;
</code></pre>
<p>The Spring Boot config:</p>
<pre><code>@SpringBootApplication()
public class Boot extends SpringBootServletInitializer
{
    public static void main(String[] args)
    {
        SpringApplication.run(Boot.class, args);
    }
}
</code></pre>
<p>IT configuration:</p>
<pre><code>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ControllerIT
{

    @Autowired
    private TestRestTemplate restTemplate;
...
}
</code></pre>
<hr />
<p>Number 2 lead me to looking into params of @SpringBootTest.
I ended up with ...</p>
<pre><code>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
    classes = ITConfig.class)
</code></pre>
<p>Where ITConfig is:</p>
<pre><code>@SpringBootApplication()
public class ITConfig extends SpringBootServletInitializer
{
    public static void main(String[] args)
        {
            SpringApplication.run(org.lhasalimited.libraries.ITConfig.class, args);
        }
}
</code></pre>
<p>That appears to be working. Thanks for the hint.</p>
",https://stackoverflow.com/questions/64991293/how-should-i-perform-integration-testing-on-a-springboot-library-that-isnt-an,"['spring', 'spring-boot', 'maven']",1662,True,1,1
"Integration testing for spring cloud stream, how to ensure application resources are not used","<p>I'm trying to do some integration testing for my cloud streaming application. One of the main issues I'm observing so far is that the TestChannelBinderConfiguration keeps picking up the configuration specified in <code>src/main/java/resources/application.yml</code> instead of keeping it as blank (since there is no config file in <code>/src/test/resources/</code>).</p>
<p>If I delete the <code>application.yml</code> file or remove all spring-cloud-stream related configuration, the test passes. How can I ensure that the TestChannelBinderConfiguration does not pick up <code>application.yml</code> file.</p>
<pre><code>  @Test
  public void echoTransformTest() {
    try (ConfigurableApplicationContext context =
        new SpringApplicationBuilder(
              TestChannelBinderConfiguration.getCompleteConfiguration(DataflowApplication.class))
            .properties(new Properties())
            .run(&quot;--spring.cloud.function.definition=echo&quot;)) {
      InputDestination source = context.getBean(InputDestination.class);
      OutputDestination target = context.getBean(OutputDestination.class);

      GenericMessage&lt;byte[]&gt; inputMessage = new GenericMessage&lt;&gt;(&quot;hello&quot;.getBytes());

      source.send(inputMessage);
      assertThat(target.receive().getPayload()).isEqualTo(&quot;hello&quot;.getBytes());
    }
  }
</code></pre>
",https://stackoverflow.com/questions/64886688/integration-testing-for-spring-cloud-stream-how-to-ensure-application-resources,"['spring-cloud', 'spring-cloud-stream', 'spring-boot-test', 'spring-cloud-stream-binder-kafka']",1192,True,0,1
How to swap dependencies in Simple Injector for Integration Testing when conditional registrations exist,"<p>We are setting up integration tests and would like to be able to swap out some real implementations for stubs. It seems possible when looking at <a href=""https://stackoverflow.com/questions/60379940/how-to-dependency-swap-using-simple-injector-in-asp-net-core-3-1-for-integration"">How to Dependency Swap using Simple Injector in ASP.NET Core 3.1 for Integration Tests</a>, but we also have conditional registrations.</p>
<p>The setting <code>container.Options.AllowOverridingRegistrations = true;</code> does not work in combination with conditional registrations.</p>
<p>Is there a work around?</p>
<p>To clarify: the registrations that we would want to override are preferably not conditional, but having any conditional registrations disallows the setting <code>container.Options.AllowOverridingRegistrations</code> to be <code>true</code>.</p>
",https://stackoverflow.com/questions/63886380/how-to-swap-dependencies-in-simple-injector-for-integration-testing-when-conditi,"['dependency-injection', 'asp.net-core-3.1', 'simple-injector', '.net-core-3.1', '.net-4.8']",217,True,0,1
Application context throws error when using spock framework for integration testing in grails 2.5.5,"<p>I am using grails 2.5.5. In this when I am using spock framework to write integration tests then it is throwing a bug. The project is 7-8 years old and I also have little knowledge about the stack.Can anyone please throw some light on this?</p>

<pre><code> package gdbxt

import gdbxt.reagentrequest.CellLineGenerationTask
import grails.test.spock.IntegrationSpec

class RequestSetControllerStblIntegrationSpec extends IntegrationSpec {

    def proteinProductionService
    RequestSet rsOneDefunctPpt
    Ppt pptNoIsolates

    def setup() {
        given: ""A request set""
        rsOneDefunctPpt = new RequestSet(
                dateSubmitted: new Date(),
                description: ""first integration test"",
                requestType: RequestSetType.findByName('Cell Line Generation from existing vectors'),
                rationale: 6,
                userAccount: 'andera52',
                protPrdctGrp: ProtPrdctGrp.findByName('BMD-BEP STBL'),
                notebookReference: 'ewb://ctiewb.pfizer.com:5277/5a134630190d11e582b400059a3c7a00?action=OPEN',
                dateNeeded: new Date() + 15,
                productionDataset: ProductionDataset.findByProject(Project.findByVisibleId(1))  // PRJ-1 (Test)
        )
        and: ""A request for a defunct ppt, which we add to the request set""
        pptNoIsolates = Ppt.findByVisibleId(33987)
        def r = new Request(
                pptId: pptNoIsolates.id
        )
        r.addToVectorGroupIds( pptNoIsolates.vectorGroups.find{it.chainInfo.label == 'Heavy Chain'}.id.toInteger() )
        r.addToVectorGroupIds( pptNoIsolates.vectorGroups.find{it.chainInfo.label == 'Light Chain'}.id.toInteger() )
        rsOneDefunctPpt.addToRequests(r)
        rsOneDefunctPpt.save()

    }

    void ""test createCellLineGenerationTasks""() {
        given: ""A RequestSetController""
        def rsc = new RequestSetController()

        and: ""The id of a saved requestSet""
        rsc.params.id = rsOneDefunctPpt.id

        when: ""Create CellLine Generation Task is called""
        rsc.createCellLineGenerationTasks()

        then:""a cellLine generation task is created for the selected request""
        rsc.modelAndView.model.containsKey('cellLineGenerationTask')
        CellLineGenerationTask ct = rsc.modelAndView.model.cellLineGenerationTask
        println ""Saved new cellineGeneration task with id ${ct.id}""
    }
}

</code></pre>

<p>And this is the stack trace.</p>

<pre><code>java.lang.IllegalStateException: Could not find ApplicationContext, configure Grails correctly first

    at grails.util.Holders.getApplicationContext(Holders.java:97)
    at grails.test.spock.IntegrationSpec.$spock_initializeSharedFields(IntegrationSpec.groovy:41)
</code></pre>
",https://stackoverflow.com/questions/59746230/application-context-throws-error-when-using-spock-framework-for-integration-test,"['java', 'grails']",33,False,0,0
"How to automatically initialize the DB schema, on a spring boot + eclipselink + postgresql integration testing","<p>I'm trying to set up an integration testing framework for my Java 11, spring boot + eclipselink + postgresql application.
I use docker-maven-plugin to spin off a new postgresql DB container each time, and I'm running the integration tests using maven-failsafe-plugin. All good with this approach, except for the DB schema initialization: I'm not able to initialize that schema.</p>
<p>This is how my application-it.yaml looks like:</p>
<pre><code># Graceful shutdown delay            
application:
  shutdownhook:
    delay-msec: 500

# Spring Boot management endpoint configuration           
management:
  port: 9199
  info:
    git:
      mode: full
      
# Spring Boot enpoints Management endpoint        
endpoints:
  metrics:
    sensitive: false
  env:
    sensitive: false
  health:
    enabled: false

# short value just for testing 
estaGracefulShutdownWaitSeconds: 5

# Application-specific configuration
sample-application:
  server-name: Sample App Under Test

logging:
  config: classpath:log4j2-spring.xml

spring:
  datasource:
    platform: postgresql
    url: jdbc:postgresql://localhost:${it-database.port}/postgres
    username: postgres
    password: postgres
    schema: classpath:schema-it.sql
    data: classpath:data-it.sql
    driver-class-name: org.postgresql.Driver
    initialization-mode: always
</code></pre>
<p>The schema-it.sql and data-it.sql are ok and available in the class path. There are no errors reported on their execution during the IT run. But still the schema doesn't get created (I know that because first the IT test are failing complain that the task table is missing and I'm able to access that test DB and i can see there are no table created in there).</p>
<p>The unit test looks like this:</p>
<pre><code>@RunWith(SpringRunner.class)
@ActiveProfiles(&quot;it&quot;)
@SpringBootTest
public class TaskRepositoryIT {
    @Autowired
    private TaskRepository taskRepository;

    @Test
    public void testGetTasks() {
        List&lt;Task&gt; tasks = taskRepository.findAll();
        Assert.assertTrue(tasks.isEmpty());
    }
    
}
</code></pre>
<p>Any idea how I can instruct spring to generate that schema based on schema-it.sql content and then populated it with the data-it.sql data?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/63154318/how-to-automatically-initialize-the-db-schema-on-a-spring-boot-eclipselink,"['spring-boot', 'spring-data-jpa', 'eclipselink']",672,False,0,2
Why am I getting this error from NLog during integration testing: LayoutRenderer cannot be found,"<p>I added some aspnet layout renderers to my NLog configuration, and everything works fine for my website, but when I try to run my integration tests, they fail with this error message:</p>

<blockquote>
  <p>NLog.NLogConfigurationException : Error when setting property 'Layout' on NLog.Targets.DatabaseParameterInfo
    ----> System.ArgumentException : LayoutRenderer cannot be found: 'aspnet-request-cookie'. Is NLog.Web not included?</p>
</blockquote>

<p>My initial instinct was to follow their suggestion and add the NLog.Web.AspNetCore package to my integration Test project. That did not do anything.</p>

<p>Here's what my integration test setup looks like:</p>

<pre class=""lang-cs prettyprint-override""><code>[OneTimeSetUp]
public static void BaseOneTimeSetUp()
{
    var environment = Environment.GetEnvironmentVariable(""ASPNETCORE_ENVIRONMENT"") ?? ""Development"";
    Assume.That(environment, Is.AnyOf(""Development"", ""CI""), ""Integration tests can only run in one of those environments"");

    var serviceCollection = new ServiceCollection();
    serviceCollection.AddSingleton&lt;IHostingEnvironment&gt;(p =&gt;
    {
        var mock = new Mock&lt;IHostingEnvironment&gt;();
        mock.SetupGet(m =&gt; m.ContentRootPath).Returns(TestContext.CurrentContext.TestDirectory);
        mock.SetupGet(m =&gt; m.EnvironmentName).Returns(environment);
        return mock.Object;
    });

    Startup.AddConfiguration(serviceCollection);  //throws NLogConfigurationException
}
</code></pre>

<p>And here's my implementation for the Startup AddConfiguration method:</p>

<pre class=""lang-cs prettyprint-override""><code>public static void AddConfiguration(IServiceCollection services)
{
    services.AddSingleton&lt;IConfiguration&gt;(s =&gt;
    {
        var env = s.GetService&lt;IHostingEnvironment&gt;();

        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile(""appsettings.json"", false, true)
            .AddJsonFile($""appsettings.{env.EnvironmentName}.json"", optional: true)
            .AddEnvironmentVariables();

        var config = builder.Build();

        // This next line throws the NLogConfigurationException
        LogManager.Configuration = new NLogLoggingConfiguration(config.GetSection(""NLog""));

        return config;
    });
}
</code></pre>
",https://stackoverflow.com/questions/61112177/why-am-i-getting-this-error-from-nlog-during-integration-testing-layoutrenderer,"['asp.net-core', 'integration-testing', 'moq', 'nlog']",239,True,0,1
When testing end to end integration testing using TestCafe how to manage waiting for email receipt,"<p>With system under test, when adding a new user their initial password is emailed to them. </p>

<p>I could split my test into multiple sections with manual intervention but this is less than ideal.</p>

<p>Appreciate any suggestions on how to proceed using TestCafe as I am sure others have encountered this as well.</p>
",https://stackoverflow.com/questions/60459690/when-testing-end-to-end-integration-testing-using-testcafe-how-to-manage-waiting,"['testing', 'automated-tests', 'e2e-testing', 'testcafe', 'browser-automation']",187,True,2,1
Grails Integration Testing by default creating datasource using H2 instead of datasource config from TEST environment,"<p>I have tried everything and every suggestion so far available.</p>

<p>Problem:
I'm trying to write integration test cases for Grails based application but while running tests it's picking by default H2 db for creating datasource instead of using DB config from Test Environment inside application.yml</p>

<p><strong>Command used:</strong>
<em>grails -Dgrails-env=test tesp-app -integration</em></p>

<p><strong>Version:</strong>
<em>grails=4.0.1
gorm=7.0.2.RELEASE</em></p>

<p>application.yml</p>

<pre><code>---
grails:
  profile: web
  codegen:
    defaultPackage: myApp
  gorm:
    autowire: true
    reactor:
      # Whether to translate GORM events into Reactor events
      # Disabled by default for performance reasons
      events: false
info:
  app:
    name: ""my-grails-app""
    version: ""0.0.10""
    grailsVersion: '4.0.1'
spring:
  jmx:
    unique-names: true
  main:
    banner-mode: ""off""
  groovy:
    template:
      check-template-location: false
  devtools:
    restart:
      additional-exclude:
        - '*.gsp'
        - '**/*.gsp'
        - '*.gson'
        - '**/*.gson'
        - 'logback.groovy'
        - '*.properties'
management:
  endpoints:
    enabled-by-default: false

---
grails:
  mime:
    disable:
      accept:
        header:
          userAgents:
            - Gecko
            - WebKit
            - Presto
            - Trident
    types:
      all: '*/*'
      atom: application/atom+xml
      css: text/css
      csv: text/csv
      form: application/x-www-form-urlencoded
      html:
        - text/html
        - application/xhtml+xml
      js: text/javascript
      json:
        - application/json
        - text/json
      multipartForm: multipart/form-data
      pdf: application/pdf
      rss: application/rss+xml
      text: text/plain
      hal:
        - application/hal+json
        - application/hal+xml
      xml:
        - text/xml
        - application/xml
  urlmapping:
    cache:
      maxsize: 1000
  controllers:
    defaultScope: singleton
  converters:
    encoding: UTF-8
  views:
    default:
      codec: html
    gsp:
      encoding: UTF-8
      htmlcodec: xml
      codecs:
        expression: html
        scriptlet: html
        taglib: none
        staticparts: none
management:
  endpoints:
    jmx:
      unique-names: true

---
hibernate:
  cache:
    queries: false
    use_second_level_cache: false
    use_query_cache: false
  #        cache.provider_class: 'org.hibernate.cache.EhCacheProvider'
  lazy: false
  max_fetch_depth: '5'

environments:
  development:
    datasource:
      pooled: true
      dbCreate: update
      driverClassName: 'com.mysql.jdbc.Driver'
      url: 'jdbc:mysql://127.0.0.1:3306/mysqlDB_dev?useLegacyDatetimeCode=false&amp;serverTimezone=UTC'
      username: 'root'
      password: 'root'
      logSql: true
    validationQuery: ""SELECT 1""
  test:
    datasource:
      pooled: true
      dbCreate: create-drop
      driverClassName: 'com.mysql.jdbc.Driver'
      url: 'jdbc:mysql://127.0.0.1:3306/mysqlDB_test?useLegacyDatetimeCode=false&amp;serverTimezone=UTC'
      username: 'root'
      password: 'root'
      logSql: true
  production:
    datasource:
      pooled: true
      dbCreate: update
      driverClassName: 'com.mysql.jdbc.Driver'
      url: 'jdbc:mysql://127.0.0.1:3306/mysqlDB_prod?useLegacyDatetimeCode=false&amp;serverTimezone=UTC'
      username: 'xxxxx'
      password: 'xxxxx'
      logSql: true
      validationQuery: ""SELECT 1""
      properties:
        jmxEnabled: true
        initialSize: 5
        maxActive: 50
        minIdle: 5
        maxIdle: 25
        maxWait: 10000
        maxAge: 600000
        timeBetweenEvictionRunsMillis: 5000
        minEvictableIdleTimeMillis: 60000
        validationQuery: SELECT 1
        validationQueryTimeout: 3
        validationInterval: 15000
        testOnBorrow: true
        testWhileIdle: true
        testOnReturn: false
        jdbcInterceptors: ConnectionState
        defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED


</code></pre>
",https://stackoverflow.com/questions/61241375/grails-integration-testing-by-default-creating-datasource-using-h2-instead-of-da,"['spring', 'hibernate', 'integration-testing', 'grails-4']",216,False,1,0
How can I prevent a React state update on an unmounted component in my integration testing?,"<p>I'm using the testing-library to write my tests.  I'm writing integration tests that load the  component and then trying to walk through the UI in the test to mimic what a user might do and then testing the results of these steps.  In my test output, I get the following warning when both tests run but do not get the following warning when only one test is run.  All tests that run pass successfully.</p>
<pre><code>  console.error node_modules/react-dom/cjs/react-dom.development.js:88
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
    in Unknown (at Login.integration.test.js:12)
</code></pre>
<p>The following is my integration test written in jest.  if I comment out either one of the tests, the warning goes away but if they both run then I get the warning.</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import React from 'react';
import { render, screen, waitForElementToBeRemoved, waitFor } from '@testing-library/react';
import userEvent from ""@testing-library/user-event"";
import { login } from '../../../common/Constants';
import ""@testing-library/jest-dom/extend-expect"";
import { MemoryRouter } from 'react-router-dom';
import App from '../../root/App';
import { AuthProvider } from '../../../middleware/Auth/Auth';

function renderApp() {
  render(
    &lt;AuthProvider&gt;
      &lt;MemoryRouter&gt;
        &lt;App /&gt;
      &lt;/MemoryRouter&gt;
    &lt;/AuthProvider&gt;
  );

  //Click the Login Menu Item
  const loginMenuItem = screen.getByRole('link', { name: /Login/i });
  userEvent.click(loginMenuItem);

  //It does not display a login failure alert
  const loginFailedAlert = screen.queryByRole('alert', { text: /Login Failed./i });
  expect(loginFailedAlert).not.toBeInTheDocument();

  const emailInput = screen.getByPlaceholderText(login.EMAIL);
  const passwordInput = screen.getByPlaceholderText(login.PASSWORD);
  const buttonInput = screen.getByRole('button', { text: /Submit/i });

  expect(emailInput).toBeInTheDocument();
  expect(passwordInput).toBeInTheDocument();
  expect(buttonInput).toBeInTheDocument();

  return { emailInput, passwordInput, buttonInput }
}

describe('&lt;Login /&gt; Integration tests:', () =&gt; {

  test('Successful Login', async () =&gt; {
    const { emailInput, passwordInput, buttonInput } = renderApp();

    Storage.prototype.getItem = jest.fn(() =&gt; {
      return JSON.stringify({ email: 'asdf@asdf.com', password: 'asdf' });
    });

    // fill out and submit form with valid credentials
    userEvent.type(emailInput, 'asdf@asdf.com');
    userEvent.type(passwordInput, 'asdf');
    userEvent.click(buttonInput);

    //It does not display a login failure alert
    const noLoginFailedAlert = screen.queryByRole('alert', { text: /Login Failed./i });
    expect(noLoginFailedAlert).not.toBeInTheDocument();

    // It hides form elements
    await waitForElementToBeRemoved(() =&gt; screen.getByPlaceholderText(login.EMAIL));
    expect(emailInput).not.toBeInTheDocument();
    expect(passwordInput).not.toBeInTheDocument();
    expect(buttonInput).not.toBeInTheDocument();
  });


  test('Failed Login - invalid password', async () =&gt; {
    const { emailInput, passwordInput, buttonInput } = renderApp();

    Storage.prototype.getItem = jest.fn(() =&gt; {
      return JSON.stringify({ email: 'brad@asdf.com', password: 'asdf' });
    });

    // fill out and submit form with invalid credentials
    userEvent.type(emailInput, 'brad@asdf.com');
    userEvent.type(passwordInput, 'invalidpw');
    userEvent.click(buttonInput);

    //It displays a login failure alert
    await waitFor(() =&gt; expect(screen.getByRole('alert', { text: /Login Failed./i })).toBeInTheDocument())

    // It still displays login form elements
    expect(emailInput).toBeInTheDocument();
    expect(passwordInput).toBeInTheDocument();
    expect(buttonInput).toBeInTheDocument();
  });
});</code></pre>
</div>
</div>
</p>
<p>The following is the  component:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import React, { useContext } from 'react';
import { Route, Switch, withRouter } from 'react-router-dom';
import Layout from '../../hoc/Layout/Layout';
import { paths } from '../../common/Constants';
import LandingPage from '../pages/landingPage/LandingPage';
import Dashboard from '../pages/dashboard/Dashboard';
import AddJob from '../pages/addJob/AddJob';
import Register from '../pages/register/Register';
import Login from '../pages/login/Login';
import NotFound from '../pages/notFound/NotFound';
import PrivateRoute from '../../middleware/Auth/PrivateRoute';
import { AuthContext } from '../../middleware/Auth/Auth';

function App() {

  let authenticatedRoutes = (
    &lt;Switch&gt;
      &lt;PrivateRoute path={'/dashboard'} exact component={Dashboard} /&gt;
      &lt;PrivateRoute path={'/add'} exact component={AddJob} /&gt;
      &lt;PrivateRoute path={'/'} exact component={Dashboard} /&gt;
      &lt;Route render={(props) =&gt; (&lt;NotFound {...props} /&gt;)} /&gt;
    &lt;/Switch&gt;
  )

  let publicRoutes = (
    &lt;Switch&gt;
      &lt;Route path='/' exact component={LandingPage} /&gt;
      &lt;Route path={paths.LOGIN} exact component={Login} /&gt;
      &lt;Route path={paths.REGISTER} exact component={Register} /&gt;
      &lt;Route render={(props) =&gt; (&lt;NotFound {...props} /&gt;)} /&gt;
    &lt;/Switch&gt;
  )

  const { currentUser } = useContext(AuthContext);
  let routes = currentUser ? authenticatedRoutes : publicRoutes;

  return (
    &lt;Layout&gt;{routes}&lt;/Layout&gt;
  );
}

export default withRouter(App);</code></pre>
</div>
</div>
</p>
<p>The following is the AuthProvider component that wraps  in the renderApp() function.  It takes advantadge of the React useContext hook to manage the state of a users authentication for the app:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import React, { useEffect, useState } from 'react'
import { AccountHandler } from '../Account/AccountHandler';

export const AuthContext = React.createContext();

export const AuthProvider = React.memo(({ children }) =&gt; {
  const [currentUser, setCurrentUser] = useState(null);
  const [pending, setPending] = useState(true);

  useEffect(() =&gt; {
    if (pending) {
      AccountHandler.getInstance().registerAuthStateChangeObserver((user) =&gt; {
        setCurrentUser(user);
        setPending(false);
      })
    };
  })

  if (pending) {
    return &lt;&gt;Loading ... &lt;/&gt;
  }
  return (
    &lt;AuthContext.Provider value={{ currentUser }}&gt;
      {children}
    &lt;/AuthContext.Provider&gt;
  )
});</code></pre>
</div>
</div>
</p>
<p>It seems as though the first test mounts the component under test but that the second test is somehow trying to reference the first mounted component rather than the newly mounted component but I can't seem to figure out exactly what's happening here to correct these warnings.  Any help would be greatly appreciated!</p>
",https://stackoverflow.com/questions/64144143/how-can-i-prevent-a-react-state-update-on-an-unmounted-component-in-my-integrati,"['reactjs', 'jestjs', 'react-testing-library']",1281,True,0,2
TestRestTemplate vs WebTestClient vs RestAssured : What is the best approach for integration testing of Spring Boot Rest API,"<p>Which of the 3 APIs: TestRestTemplate, WebTestClient, RestAssured  is the most efficient for integration testing of Spring Boot Rest API (non-reactive) with respect to the following:</p>

<ol>
<li>Ensures compatibility with Spring boot for incremental versions.</li>
<li>Easy-to-use and extensive assertions for checking status codes, headers, both JSON/XML payload validation, response time, etc.</li>
<li>Has the possibility to test spring container configuration.</li>
<li>Features to reuse specific checks across all end points.</li>
<li>Is the most stable and therefore an Industry common practice.</li>
</ol>

<p>Few initial findings which sort of prevent one of them to be marked as clear winner are:</p>

<ul>
<li><p>TestRestTemplate &amp; WebTestClient are Spring built-in APIs so are auto-configurable with Spring Boot. Latest versions of RestAssured (4.0.0 onwards) can    have problems with spring    boot(<a href=""https://stackoverflow.com/questions/44993615"">java.lang.NoClassDefFoundError: io/restassured/mapper/factory/GsonObjectMapperFactory</a>)    and require explicit dependencies addition.</p></li>
<li><p>WebTestClient (a Fluent API) seems to have nice and easy to use syntax as compared to TestRestTemplate but is very new and there are    not enough examples showing its usage for non-reactive Rest APIs and    availability of extensive assertion API</p></li>
<li><p>RestTemplate (API on which TestRestTemplate is based) will be deprecated in future Spring Boot version.</p></li>
</ul>

<p>Feedbacks from experienced developers will be a great help.</p>
",https://stackoverflow.com/questions/61318756/testresttemplate-vs-webtestclient-vs-restassured-what-is-the-best-approach-for,"['spring-boot', 'rest', 'testing']",3466,True,9,2
Integration Testing with ASP.NET Core and Entity Framework Core - How to Restore Test Data in Database Per Test?,"<p>I am a new .NET Core user. I am trying to perform integration testing on a ASP.NET.Core WebAPI that uses <strong>EF Core</strong> for managing data. Architecture is based on <a href=""https://github.com/dotnet-architecture/eShopOnContainers"" rel=""nofollow noreferrer"">eShopContainers</a> DDD sample. I am using Xunit for testing and have considered three approaches for resetting the database running in a docker-compose stack, to an initial state prior to running each test:</p>

<ol>
<li><strong>Test Setup</strong>: Create and seed database with test data, <strong>TearDown</strong>: Remove database.</li>
<li><strong>Test Setup</strong>: Seed database table with test data, <strong>TearDown</strong>: Clear test data.</li>
<li><strong>Test Setup</strong>: Create a transaction, <strong>TearDown</strong>: Abort transaction. </li>
</ol>

<p>The System Under Test executes create/delete/update operations within a transaction using BeginTransaction(). Not sure if EF Core can use nested transactions so have tried performing options 1 and 2 when testing.</p>

<p>The code below uses WebApiTestFactory as a class derived from <code>WebApplicationFactory</code>. This is provided as a class fixture to create a TestServer instance for testing.</p>

<pre class=""lang-cs prettyprint-override""><code>    public class CoursesScenarios : CoursesScenarioBase, IClassFixture&lt;WebApiTestFactory&gt;, IDisposable
    {
        /// &lt;summary&gt; 
        /// With Xunit constructor gets run before every test
        /// Code in the Dispose method gets run after every test completed
        /// &lt;/summary&gt;
        public CoursesScenarios(WebApiTestFactory factory) : base(factory)
        {
            Console.WriteLine(""CoursesScenario test setup..."");

            Server.Host
                .MigrateDbContext&lt;CourseContext&gt;((context, services) =&gt;
                {
                    Console.WriteLine(""Seeding lookup data"");
                    var env = services.GetService&lt;IWebHostEnvironment&gt;();
                    var settings = services.GetService&lt;IOptions&lt;CourseSettings&gt;&gt;();
                    var logger = services.GetService&lt;ILogger&lt;CoursesContextSeed&gt;&gt;();

                    new CoursesContextSeed()
                        .SeedAsync(context, env, settings, logger)
                        .Wait();
                });

            // load the test data
            Server.Host
                .MigrateDbContext&lt;CourseContext&gt;((context, services) =&gt;
                {
                    Console.WriteLine(""Seeding the test data"");
                    var env = services.GetService&lt;IWebHostEnvironment&gt;();
                    var settings = services.GetService&lt;IOptions&lt;CourseSettings&gt;&gt;();
                    var logger = services.GetService&lt;ILogger&lt;CoursesContextTestSeed&gt;&gt;();

                    new CoursesContextTestSeed()
                        .SeedAsync(context, env, settings, logger)
                        .Wait();
                });

            foreach(Course c in Context.Courses)
            {
                Console.WriteLine($""Course {c.Id}"");
            }

        }

        // tests here
        [Fact]
        ...
        //

        ///
        /// &lt;summary&gt;
        /// This gets called after every test by XUnit
        /// &lt;/summary&gt;
        ///
        public void Dispose()
        {
            // using (var command = Context.Database.GetDbConnection().CreateCommand())
            // {
            //     command.CommandText = @""DELETE FROM CourseManagement.Course;
            //         ALTER SEQUENCE coursemanagement.""""unit_UnitID_seq"""" RESTART WITH 1;"";
            //     Context.Database.OpenConnection();
            //     int result = command.ExecuteNonQuery();
            //     Console.WriteLine($""{result} records deleted from course table"");
            //     how to reload entities to match deleted state of rows in table?
            //     currently entities in memory are saved back to database
            // }
            Context.Database.EnsureDeleted();
        }
</code></pre>

<p>The following exception is raised on the server and received during testing. This is as a result of deleting the database, so the connection is lost. </p>

<pre class=""lang-cs prettyprint-override""><code>Npgsql.NpgsqlException (0x80004005): Exception while connecting
 ---&gt; System.Net.Sockets.SocketException (111): Connection refused
   at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.&lt;&gt;c__DisplayClass32_0.&lt;&lt;Open&gt;g__OpenLong|0&gt;d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.NpgsqlConnection.Open()
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
   at Microsoft.AspNetCore.Hosting.IWebHostExtensions.InvokeSeeder[TContext](Action`2 seeder, TContext context, IServiceProvider services) in /src/BuildingBlocks/WebHost.Customization/IWebHostExtensions.cs:line 76
   at Microsoft.AspNetCore.Hosting.IWebHostExtensions.&lt;&gt;c__DisplayClass1_0`1.&lt;MigrateDbContext&gt;b__2() in /src/BuildingBlocks/WebHost.Customization/IWebHostExtensions.cs:line 54
   at Polly.Policy.&lt;&gt;c__DisplayClass108_0.&lt;Execute&gt;b__0(Context ctx, CancellationToken ct)
   at Polly.Policy.&lt;&gt;c__DisplayClass138_0.&lt;Implementation&gt;b__0(Context ctx, CancellationToken token)
   at Polly.Retry.RetryEngine.Implementation[TResult](Func`3 action, Context context, CancellationToken cancellationToken, ExceptionPredicates shouldRetryExceptionPredicates, ResultPredicates`1 shouldRetryResultPredicates, Action`4 onRetry, Int32 permittedRetryCount, IEnumerable`1 sleepDurationsEnumerable, Func`4 sleepDurationProvider)
</code></pre>

<p>Has anyone managed to successfully reset database state with EF Core for integration testing, either using delete database approach or seeding/unseeding table state? Have also tried the seed data/unseed data approach, resetting identity key and deleting records using raw SQL query, but then encountered difficulty resynchronising EF Core with the state of the deleted rows in the underlying table, EF Core sees them as new entities and adds them back. Maybe best way is to resort to using test data sql scripts and ADO.NET to initialise test data state?</p>
",https://stackoverflow.com/questions/60510597/integration-testing-with-asp-net-core-and-entity-framework-core-how-to-restore,"['c#', 'asp.net-core', 'entity-framework-core']",5016,True,2,2
Handling secrets at build time for the purposes of unit &amp; integration testing containers deployed to Cloud Run,"<h1>Use case</h1>
<p>[For docker containers deployed to Cloud Run], run unit tests at build time, some of which require secrets and some level of google authentication. The unit tests might require authentication in order to interact with google services such as cloud storage, or retrieve secret keys from google KMS in order to test interactions with other authenticated APIs. Based on my understanding of <a href=""https://cloud.google.com/docs/authentication/production"" rel=""nofollow noreferrer"">gcloud authentication</a>, the only way to provide credentials <em>at build time</em> is by a credentials json file for your service account (whereas when the deployed service is triggered, ADC can use the service account provided by Cloud Run).</p>
<h1>Current Approach</h1>
<p>Assuming we have generated a credentials file for our service account locally</p>
<ol>
<li>Check whether the build is initiated locally or by a github trigger. If the build is triggered by a github trigger, only run unit tests that don't require authentication, as I have yet to discover a way to get credentials at build time in this case.</li>
<li>[Proceed only if this is a locally triggered build]. Copy credentials file contents as base64 encoded string into the dockerfile via build argument</li>
<li>Create temporary credentials file during build by decoding the base64 encoded build argument</li>
<li>Run all unit tests using that credentials file</li>
<li>Delete the credentials file as it is not needed in the deployed container</li>
</ol>
<h1>Current Implementation</h1>
<p><strong>[Gross and probably unsafe code trigger warning]</strong></p>
<pre><code>$cloud-build-local --config=build_config/cloudbuild_manual.json \
--dryrun=false \
--push \
--substitutions=\
_JSON_CONTENTS=&quot;$$(cat $(CREDENTIALS_PATH) | base64)&quot;,\
_CONTAINER_ID=&quot;$(CONTAINER_ID)&quot; \
.
</code></pre>
<p>cloudbuild_manual.json</p>
<pre><code>{
    &quot;name&quot;: &quot;gcr.io/cloud-builders/docker&quot;,
    &quot;args&quot;: [
        &quot;build&quot;,
        &quot;--build-arg&quot;,
        &quot;JSON_CONTENTS=${_JSON_CONTENTS}&quot;,
        &quot;--build-arg&quot;,
        &quot;PROJECT_ID=${PROJECT_ID}&quot;,
        &quot;--build-arg&quot;,
        &quot;RUN_AUTHENTICATED_TESTS=true&quot;,
        &quot;-t&quot;,
        &quot;gcr.io/${PROJECT_ID}/${_CONTAINER_ID}&quot;,
        &quot;.&quot;
    ],
    &quot;env&quot;:[],
    &quot;timeout&quot;: &quot;500s&quot;
}
...
</code></pre>
<p>Dockerfile</p>
<pre><code>ARG RUN_AUTHENTICATED_TESTS=false
ENV CREDENTIALS_TEMP_LOCATION credentials_temp.json
ARG JSON_CONTENTS
...
RUN if [ &quot;$RUN_AUTHENTICATED_TESTS&quot; = &quot;true&quot; ] ; then \
    echo &quot;${JSON_CONTENTS}&quot; | base64 -d &gt; $CREDENTIALS_TEMP_LOCATION &amp;&amp; \
PYTHONPATH=$PYTHONPATH:`pwd`/ pytest -v --run-auth &amp;&amp; \
    rm $CREDENTIALS_TEMP_LOCATION ; \
else \
    PYTHONPATH=$PYTHONPATH:`pwd`/ pytest -v ; \
fi;
...
</code></pre>
<h1>Problems with this approach</h1>
<ol>
<li>It makes me feel gross inside</li>
<li>Doesn't provide a solution that works for continuous deployment via github triggers</li>
<li>Possibly unsafe?</li>
</ol>
<h1>Possible Solution</h1>
<p>Use <a href=""https://vcrpy.readthedocs.io/en/latest/usage.html"" rel=""nofollow noreferrer"">vcrpy</a> or a similar data mocking library to intercept all unit tested interactions and replace them with <em>recorded</em> versions, thus eliminating the need to have any sort of authentication at build time. Ensure that all tokens and secret keys are censored from the recordings for security (avoiding storing API keys in plaintext in the git repo).</p>
<p>I would love to hear your thoughts on my current approach, alternative approach, and any other solutions you may have. Feel free to trash talk my trash solution :)</p>
",https://stackoverflow.com/questions/62732900/handling-secrets-at-build-time-for-the-purposes-of-unit-integration-testing-co,"['google-cloud-platform', 'google-cloud-build', 'google-cloud-run']",948,True,2,2
How to do integration testing on an app depending on injected service with a Mock for the service?,"<p>I don't think it matters what the application is - Asp.NET, Blazor, WPF ... whatever -- if dependency injection is implemented, say:</p>
<pre><code>class Foo {
    public void ConfigureServices(IServiceCollection services) {
        services.AddSingleton&lt;IDispatcher, DispatchProvider&gt;();
        services.AddSingleton&lt;IAuthenticator, AuthenticationProvider&gt;();
    }
}
</code></pre>
<p>... then:</p>
<pre><code>class Bar {
    public Bar (IDispatcher dispatcher) {
        // do something with dispatcher...
    }
}
</code></pre>
<p>... the dependency creates a <em>not-so-straight-forward-approach</em> to unit testing.</p>
<p>Obviously, if I'm going to perform integration testing on <code>Bar</code> (with a dependency on <code>IDispatcher</code>), I don't necessarily want to fire up the relevant resources.</p>
<p>If <code>Bar</code> is a standalone object, I can create a <code>Mock&lt;IDispatcher&gt;</code> and manually inject into <code>Bar</code>; however, in my case, I am developing a Blazor component. The component has a dependency on <code>IDispatch</code> and another component on <code>IAuthenticator</code>.</p>
<p>The only thing I can come up with to alternatively inject a <em>mock</em> is to do the following:</p>
<pre><code>if (!isTest)) {
    services.AddSingleton&lt;IDispatcher, DispatchProvider&gt;();
    services.AddSingleton&lt;IAuthenticator, AuthenticationProvider&gt;();
} else {
    services.AddSingleton&lt;IDispatcher, MockDispatchProvider&gt;();
    services.AddSingleton&lt;IAuthenticator, MockAuthenticationProvider&gt;();
}

</code></pre>
<p>Here, I have a separate class library with just the <em>mocks</em> in it. My web app has to reference that .DLL which really stinks.</p>
<p>Is there a more practical solution? I really don't like having to do this.</p>
",https://stackoverflow.com/questions/63585343/how-to-do-integration-testing-on-an-app-depending-on-injected-service-with-a-moc,"['c#', 'unit-testing', 'dependency-injection', 'blazor-server-side']",231,False,1,0
How to write CI/CD pipeline to run integration testing of java micro services on Google kubernetes cluster?,"<p><strong>Background:</strong>
I have 8-9 private clusterIP spring based microservices in a GKE cluster. All of the microservices are having integration tests bundled with them. I am using bitbucket and using maven as build tool.</p>

<p>All of the microservices are talking to each other via rest call with url: http://:8080/rest/api/fetch</p>

<p><strong>Requirement:</strong> I have testing enviroment ready with all the docker images up on GKE Test cluster. I want that as soon as I merge the code to master for service-A, pipeline should deploy image to tes-env and run integration test cases. If test cases passes, it should deploy to QA-environment, otherwise rollback the image of service-A back to previous one.</p>

<p><strong>Issue:</strong> On every code merge to master, I am able to run JUNIT test cases of service-A, build its docker image, push it on GCR and deploy it on test-env cluster. But how can I trigger integration test cases after the deployment and rollback to previously deployed image back if integration test cases fails? Is there any way? </p>

<p><strong>TIA</strong> </p>
",https://stackoverflow.com/questions/59612496/how-to-write-ci-cd-pipeline-to-run-integration-testing-of-java-micro-services-on,"['kubernetes', 'google-cloud-platform', 'google-kubernetes-engine', 'bitbucket-pipelines', 'google-cloud-build']",1726,True,0,4
How to handle xml file path given using regular expression to support multiple environment for Integration Testing by Spring?,"<p>I have following configuration in my test-appContext.xml file for supporting execution of spring integration testing.</p>

<pre class=""lang-xml prettyprint-override""><code>&lt;bean id=""cacheManagerConfig"" class=""org.springframework.cache.ehcache.EhCacheManagerFactoryBean""&gt; 
    &lt;property name=""configLocation"" value=""file:/web/${websphere.env}/${websphere.Domain}/${websphere.Name}/myportal/config/ehcache.xml""/&gt;
&lt;/bean&gt;
</code></pre>

<p>I am using junit 4.12 with spring 4 for Integration Testing of MVC flow.<br/>
<strong><em>How to handle ehcache.xml file path in spring integration testing.</em></strong></p>

<p>Thanks :)</p>
",https://stackoverflow.com/questions/60374907/how-to-handle-xml-file-path-given-using-regular-expression-to-support-multiple-e,"['java', 'spring', 'integration-testing', 'junit4']",56,True,1,1
how to create a Mock database and add data in mock db for integration testing using postgres db and java,"<p>I want to perform the Integration test for which I want to create a test DB and add some data.
how should I point to the test DB while doing an integration test?</p>

<p>Thanks for Help......</p>
",https://stackoverflow.com/questions/61013260/how-to-create-a-mock-database-and-add-data-in-mock-db-for-integration-testing-us,"['java', 'testing', 'integration']",1268,True,1,1
How to handle xml file path given using regular expression to support multiple environment for Integration Testing by Spring?,"<p>I have following configuration in my test-appContext.xml file for supporting execution of spring integration testing.</p>

<pre class=""lang-xml prettyprint-override""><code>&lt;bean id=""cacheManagerConfig"" class=""org.springframework.cache.ehcache.EhCacheManagerFactoryBean""&gt; 
    &lt;property name=""configLocation"" value=""file:/web/${websphere.env}/${websphere.Domain}/${websphere.Name}/myportal/config/ehcache.xml""/&gt;
&lt;/bean&gt;
</code></pre>

<p>I am using junit 4.12 with spring 4 for Integration Testing of MVC flow.<br/>
<strong><em>How to handle ehcache.xml file path in spring integration testing.</em></strong></p>

<p>Thanks :)</p>
",https://stackoverflow.com/questions/60374907/how-to-handle-xml-file-path-given-using-regular-expression-to-support-multiple-e,"['java', 'spring', 'integration-testing', 'junit4']",56,True,1,1
Integration testing involving rabbitmq,"<p>I need help on how to write integration testing involving the rabbitMQ message broker.</p>

<p>This is the overall system architecture</p>

<p>Service(Producer) --> Message Borker(Environment 1) --> Controllers(Our Application) --> Message Broker(Environment 2) --> Consumer Devices</p>

<p>I am planning to place my integration testing programs at the service level wherein I will mimic a message to be sent to a Message broker. Later I will listen for the response and assert it.</p>

<p>Though its an asynchronous system, testing synchronous way seems to be an easy approach.</p>

<p>Is there any better approach to do the integration testing for my application flow. Could you please give me pointers for integration testing. </p>

<p>Thanks
Bala.</p>
",https://stackoverflow.com/questions/60076615/integration-testing-involving-rabbitmq,"['java', 'spring', 'rabbitmq']",768,False,0,1
Flutter Integartion testing using Gitlab ci,"<p>I am trying to do integration testing of an app built with flutter. I am using cirrusci/flutter docker image for unit testing. I am unable to find any tutorials for integration testing. can anyone help me? Thanks</p>
",https://stackoverflow.com/questions/61712256/flutter-integartion-testing-using-gitlab-ci,"['android', 'docker', 'flutter', 'gitlab-ci', 'gitlab-ci-runner']",245,False,2,0
ASP.Net Core Integration testing failing due to webapp startup using reklative folder path,"<p>I am completely new to integration testing in asp.net core.
I have a asp.net core webapi and trying to setup integration testing for this api project.
When i try to run the basic test it fails due to the following in the configure method inside startup.cs:</p>
<pre><code>RegisterExcelTemplate(app, &quot;Upload/ExposureRating/Global/Template/&quot;, &quot;/api/upload/exposureRating/global&quot;);

private static void RegisterExcelTemplate(IApplicationBuilder applicationBuilder, string relativeFolderPath, string apiPath)
{
    applicationBuilder.UseFileServer(new FileServerOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), relativeFolderPath)),
        RequestPath = new PathString(apiPath),
        EnableDirectoryBrowsing = false
    });
}
</code></pre>
<p>When i run the test, getting the following error message:</p>
<p><a href=""https://i.stack.imgur.com/fOB8u.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/fOB8u.png"" alt=""This is the error while creating httpClient object"" /></a></p>
<p>Can anyone help how to fix the folder path issue in test project?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/63282996/asp-net-core-integration-testing-failing-due-to-webapp-startup-using-reklative-f,"['c#', 'integration-testing', 'asp.net-core-webapi', 'xunit', 'asp.net-core-3.1']",94,False,-1,1
Seperating ConnectionString from source control and be able to perform integrating testing in Azure CI/CD pipeline,"<p>I've a WebAPI project and I'm using Azure CI/CD pipeline to deploy it in azure. The project contains unit testing and integration testing. And for integration testing it needs to access database.  But since I don't want to check in my connectionstring to source control, the build pipeline will always fail.</p>

<p>So, the question is what solutions/features or workaround exist that can help me accomplish this scenario?</p>
",https://stackoverflow.com/questions/61496963/seperating-connectionstring-from-source-control-and-be-able-to-perform-integrati,"['azure', 'azure-devops', 'database-connection', 'azure-pipelines']",248,True,0,2
&quot;Tracking Information Not Found&quot; error with UPS RESTful Integration Testing URI,"<p>I tried to get the result of UPS RESTful API with my valid track number and API key. I get the following error: &quot;TW0001, Tracking Information Not Found&quot;. This happens if I use this Integration Testing URI (<code>https://wwwcie.ups.com/track/v1/details/</code>). When I replaced it with Production URI, I got track information without any errors:</p>
<p><code>https://onlinetools.ups.com/track/v1/details/</code>.</p>
<p>I don’t think it’s normal, because the Integration Testing URI should have returned valid information, not an error.</p>
<p>My HTTP GET request example:</p>
<pre><code>GET https://wwwcie.ups.com/track/v1/details/1ZXXXXXXXXXXXXXXXX HTTP/1.1
transId: 12345
transactionSrc: TestTrack
AccessLicenseNumber: MY_KEY
Content-Type: application/json
Accept: application/json
Username: MY_USERNAME
Password: MY_PASSWORD
</code></pre>
",https://stackoverflow.com/questions/62626015/tracking-information-not-found-error-with-ups-restful-integration-testing-uri,"['json', 'rest', 'http', 'get', 'ups']",1026,True,1,1
how can i add test-balance to stripe test account for testing API integration,"<p>There is any way to add balance to stripe account in test-mode immediately for API integration testing?</p>
",https://stackoverflow.com/questions/62721796/how-can-i-add-test-balance-to-stripe-test-account-for-testing-api-integration,['stripe-payments'],574,True,-1,2
Integration testing Blazor apps,"<p>With Razor Pages, we had the TestServer class which we would use to write <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1"" rel=""nofollow noreferrer"">Integration tests in ASP.NET Core</a>.</p>

<p>How would one go about testing a <a href=""https://learn.microsoft.com/en-us/aspnet/core/blazor/hosting-models?view=aspnetcore-3.1#blazor-server"" rel=""nofollow noreferrer"">Blazor Server</a> app? When I say integration testing, I mean testing the whole app: sending a request to the TestServer which runs the app, getting an HTML page back, and checking its contents.</p>

<p>Is this possible with Blazor Server? If not, what is the recommended approach for integration testing Blazor Server apps?</p>
",https://stackoverflow.com/questions/62267112/integration-testing-blazor-apps,['blazor-server-side'],1837,True,1,2
Using a common test utility file for projects built in SBT,"<p>Given a project using a <code>build.sbt</code> file, I would like to have a common <code>TestUtils.scala</code> file which the integration and unit tests both rely upon.</p>
<p>I have my src folder at <code>src/scala</code> and my integration testing folder at <code>it/scala</code>. My unit testing folder is at <code>test/scala</code>, and contains the common <code>TestsUtils.scala</code> file.</p>
<p>Currently I am running my tests through ScalaTest in Intellij. When I run it this way Intellij is able to determine the dependency from the integration testing folder on the unit testing folder. I am attempting to switch over to using a <code>test</code>, <code>it:test</code> and <code>unit:test</code> set of SBT tasks. When I do so the integration testing folder fails to compile since it can't find the common <code>TestUtils.scala</code> file. If I copy the <code>TestUtils.scala</code> file over to my integration testing folder then it does compile but I don't want to have the same code in 2 locations.</p>
<p>Here are the approaches I see to resolve this:</p>
<ol>
<li>Copy the file into both test folders (bad)</li>
<li>Move the file into the <code>src</code> folder (introduces <code>src</code> reliance on <code>scalatest</code> which I would prefer to avoid)</li>
<li>Find a way for the <code>integration</code> folder to use the file from the <code>test</code> folder (don't know how to do this)</li>
</ol>
<p>Ideally I would like to use the third approach but don't know how to actually implement it. How do you get one folder to use another folder as a dependency in SBT? Is there a better approach I'm unaware of?</p>
",https://stackoverflow.com/questions/63272825/using-a-common-test-utility-file-for-projects-built-in-sbt,"['scala', 'unit-testing', 'sbt', 'integration-testing']",269,True,5,1
Flutter drive: How to only run one group or test,"<p>So in the <a href=""https://flutter.dev/docs/cookbook/testing/integration/introduction"" rel=""nofollow noreferrer"">introduction to integration testing</a> you're supposed to run your tests with</p>
<pre><code>flutter drive --target=test_driver/app.dart
</code></pre>
<p>However I can't find anything about running only a specific group or test.</p>
<pre><code>flutter drive --help
</code></pre>
<p>also doesn't help.</p>
",https://stackoverflow.com/questions/59926987/flutter-drive-how-to-only-run-one-group-or-test,"['flutter', 'dart', 'integration-testing', 'flutter-test']",1804,True,6,2
How to do integration testing using Fongo (Fake mongo) in Spring Boot,"<p>I am working on spring boot application with mongodb as backend.</p>
<p>mongorepository for crud operation</p>
<p>I want to do integration testing using fake mongo (fongo)</p>
<p>I have taken reference from following link to do integration testing using fongo but no luck.</p>
<p><a href=""https://www.paradigmadigital.com/dev/tests-integrados-spring-boot-fongo/"" rel=""nofollow noreferrer"">https://www.paradigmadigital.com/dev/tests-integrados-spring-boot-fongo/</a></p>
<p>INTEGRATION test is trying to connect to real database and IT fails</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { ConfigServerWithFongoConfiguration.class }, properties = {
        &quot;server.port=8980&quot; }, webEnvironment = WebEnvironment.DEFINED_PORT)
@AutoConfigureMockMvc
@TestPropertySource(properties = { &quot;spring.data.mongodb.database=test&quot; })
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class PersonControllerITest {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private MockMvc mockMvc;

    private ObjectMapper jsonMapper;

    @Before
    public void setUp() {
        jsonMapper = new ObjectMapper();
    }

    @Test
    public void testGetPerson() throws Exception {

        Person personFongo = new Person();
        personFongo.setId(1);
        personFongo.setName(&quot;Name1&quot;);
        personFongo.setAddress(&quot;Address1&quot;);
        mongoTemplate.createCollection(&quot;person&quot;);
        mongoTemplate.insert(personFongo);

        ResultActions resultAction = mockMvc.perform(MockMvcRequestBuilders.get(&quot;http://localhost:8090/api/person/1&quot;));
        resultAction.andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
        MvcResult result = resultAction.andReturn();
        Person personResponse = jsonMapper.readValue(result.getResponse().getContentAsString(), Person.class);
        Assert.assertEquals(1, personResponse.getId());
        Assert.assertEquals(&quot;Name1&quot;, personResponse.getName());
        Assert.assertEquals(&quot;Address1&quot;, personResponse.getAddress());

    }

    @Test
    public void testCreatePerson() throws Exception {

        Person personRequest = new Person();
        personRequest.setId(1);
        personRequest.setName(&quot;Name1&quot;);
        personRequest.setAddress(&quot;Address1&quot;);

        String body = jsonMapper.writeValueAsString(personRequest);

        ResultActions resultAction = mockMvc.perform(MockMvcRequestBuilders.post(&quot;http://localhost:8090/api/person&quot;)
                .contentType(MediaType.APPLICATION_JSON).content(body));
        resultAction.andExpect(MockMvcResultMatchers.status().isCreated());

        Person personFongo = mongoTemplate.findOne(new Query(Criteria.where(&quot;id&quot;).is(1)), Person.class);
        Assert.assertEquals(personFongo.getName(), &quot;Name1&quot;);
        Assert.assertEquals(personFongo.getAddress(), &quot;Address1&quot;);
    }
}
</code></pre>
<p>I am getting following error while executing Integration test</p>
<pre><code>   java.lang.IllegalStateException: Failed to load ApplicationContext
    
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
        at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
        at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
        at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig': Unsatisfied dependency expressed through field 'entitlementsRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entitlementsRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        ... 25 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entitlementsRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1531)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1276)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        
        ... 44 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
        
        ... 57 more
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 66 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        
        ... 67 more
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 89 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.obtainBeanInstanceFromFactory(ConfigurationClassEnhancer.java:389)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.mongoClient(&lt;generated&gt;)
        at com.company.myapp.configs.MongoConfig.mongoDbFactory(MongoConfig.java:73)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.CGLIB$mongoDbFactory$1(&lt;generated&gt;)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08$$FastClassBySpringCGLIB$$50ee8948.invoke(&lt;generated&gt;)
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.mongoDbFactory(&lt;generated&gt;)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
        ... 90 more
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 112 more
    Caused by: java.lang.NullPointerException
        at java.util.Hashtable.put(Hashtable.java:460)
        at java.util.Properties.setProperty(Properties.java:166)
        at java.lang.System.setProperty(System.java:796)
        at com.company.myapp.configs.MongoConfig.mongoClient(MongoConfig.java:78)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.CGLIB$mongoClient$3(&lt;generated&gt;)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08$$FastClassBySpringCGLIB$$50ee8948.invoke(&lt;generated&gt;)
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.mongoClient(&lt;generated&gt;)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
        ... 113 more
</code></pre>
<p>My main Application.java</p>
<pre><code>@SpringBootApplication(exclude = {MongoDataAutoConfiguration.class, MongoAutoConfiguration.class})
@EntityScan(basePackageClasses = Jsr310Converters.class)
@ComponentScan(basePackages = {&quot;com.company.myapp&quot;, &quot;com.company.myapp.repository&quot;})
@AutoConfigureAfter(MongoConfig.class)
@EnableSwagger2
@EnableScheduling
public class Application
{
public class Application
{
    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    @Value(&quot;${http.port}&quot;)
    int httpPort;

    @Value(&quot;${ssl.port}&quot;)
    int sslPort;

    @Value(&quot;${ssl.keystore.file}&quot;)
    String keyStoreFile;

    @Value(&quot;${ssl.keystore.password}&quot;)
    String keyStorePassword;

    @Autowired
    FileUtil fileUtil;

    public static void main(String[] args)
    {
        Runtime.getRuntime().addShutdownHook(new Thread() {                       
            @Override
            public void run() {
                logger.info(&quot;myapp server shutdown initiated&quot;);
                LogManager.shutdown();
                logger.info(&quot;myapp server shutdown completed&quot;);
            }
        });
        SpringApplication.run(Application.class, args);                          
    }

    @Bean
    public CompressingFilter compressingFilter()
    {
        return new CompressingFilter();
    }

    @Bean
    public EmbeddedServletContainerFactory servletContainer()
    {
        String keystore = &quot;dev&quot;;

        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) con -&gt; {
                    //if (&quot;true&quot;.equalsIgnoreCase(sslEnabled)) {
                    logger.info(&quot;----------------------------------------- Initialising ssl endpoint -------------------------------------&quot;);
                    Http11NioProtocol proto = (Http11NioProtocol) con.getProtocolHandler();
                    proto.setSSLEnabled(true);
                    con.setScheme(&quot;https&quot;);
                    con.setSecure(true);
                    con.setPort(sslPort);
                    proto.setKeystoreFile(fileUtil.getConfigFilePath(keyStoreFile));
                    proto.setKeystorePass(keystore);
                    proto.setKeyPass(keystore);
                    logger.info(&quot;---------------------------------------- Initialised ssl endpoint ----------------------------------------&quot;);
                    //}
                });

        tomcat.addAdditionalTomcatConnectors(createStandardConnector());
        return tomcat;
    }

    private Connector createStandardConnector()
    {
        Connector connector = new Connector(&quot;org.apache.coyote.http11.Http11NioProtocol&quot;);
        connector.setPort(httpPort);
        return connector;
    }
}
</code></pre>
<p><strong>AbstractFongoBaseConfiguration.java</strong></p>
<pre><code>@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public abstract class AbstractFongoBaseConfiguration extends AbstractMongoConfiguration{

    @Autowired
    private Environment env;

    @Override
    protected String getDatabaseName() {
        return env.getRequiredProperty(&quot;spring.data.mongodb.database&quot;);
    }

    @Override
    public Mongo mongo() throws Exception {
        return new Fongo(getDatabaseName()).getMongo();
    }
}
</code></pre>
<p><strong>ConfigServerWithFongoConfiguration.java</strong></p>
<pre><code>@EnableAutoConfiguration(exclude = { EmbeddedMongoAutoConfiguration.class, MongoAutoConfiguration.class,
        MongoDataAutoConfiguration.class })
@Configuration
@ComponentScan(basePackages = { &quot;com.company.myapp&quot; }, excludeFilters = {
        @ComponentScan.Filter(classes = { SpringBootApplication.class }) })
public class ConfigServerWithFongoConfiguration extends AbstractFongoBaseConfiguration {

}
</code></pre>
<p>Could you please suggest , what needs to be done to resolve this issue ?</p>
",https://stackoverflow.com/questions/63347525/how-to-do-integration-testing-using-fongo-fake-mongo-in-spring-boot,"['java', 'mongodb', 'integration-testing', 'fongo']",2568,True,0,3
Send header in subsequent URL visits through cypress,"<p>I am using Cypress for website integration testing and I am overwriting visit method such that it includes specific attribute in header but <a href=""https://docs.cypress.io/api/commands/visit.html#Arguments"" rel=""nofollow noreferrer"">this</a> doc says that <code>headers will only be sent for the initial cy.visit() request, not for any subsequent requests</code>.</p>

<p>Is there any workaround for this?</p>
",https://stackoverflow.com/questions/61091131/send-header-in-subsequent-url-visits-through-cypress,['cypress'],257,False,2,1
"Integration Testing in .NET Core 3.1 with AutoMapper, WebApplicationFactory, Entity Framework, and DTOs","<p>We have an API with about a dozen integration tests. All the tests passed until I added some DTOs and used AutoMapper. Now, all the tests that test methods that use AutoMapper and the DTOs are failing. I have provided all the code needed to understand one of the failing tests. Also, I read a lot about AutoMapper and the following StackOverflow posts:</p>
<ol>
<li><a href=""https://stackoverflow.com/questions/43630620/integration-testing-with-automapper-fails-to-initialise-configuration"">Integration Testing with AutoMapper fails to initialise configuration</a></li>
<li><a href=""https://stackoverflow.com/questions/50944862/a-kind-of-integration-testing-in-asp-net-core-with-ef-and-automapper"">A kind of integration testing in ASP.NET Core, with EF and AutoMapper</a></li>
</ol>
<p><strong>Startup.cs</strong></p>
<p>This is our Startup.ConfigureServices(). I have tried every code block commented out and/or marked &quot;ATTEMPTED&quot;.</p>
<pre><code> public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddDbContext&lt;OurContext&gt;(options =&gt;
                options.UseSqlServer(Configuration[&quot;ConnectionString&quot;]))
            .AddDbContext&lt;OurContext&gt;()
            .AddRazorPages()
            .AddMvcOptions(options =&gt; options.EnableEndpointRouting = false)
            .AddNewtonsoftJson(options =&gt; options.SerializerSettings.ContractResolver = new DefaultContractResolver());
        services
            .AddControllersWithViews();

        //ATTEMPTED
        //services
        //    .AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

        //ATTEMPTED
        //MapperConfiguration mapperConfiguration = new MapperConfiguration(mc =&gt;
        //{
        //    mc.AddProfile(new OurProfile());
        //});
        //IMapper mapper = mapperConfiguration.CreateMapper();
        //services
        //    .AddSingleton(mapper);

        //ATTEMPTED
        //services
        //    .AddAutoMapper(typeof(Startup));

        //ATTEMPTED
        //var assembly = typeof(Program).GetTypeInfo().Assembly;
        //services
        //    .AddAutoMapper(assembly);

        //ATTEMPTED
        var assembly = typeof(Program).GetTypeInfo().Assembly;
        services.AddAutoMapper(cfg =&gt;
        {
            cfg.AllowNullDestinationValues = true;
            cfg.CreateMap&lt;OurModel, OurDto&gt;()
                .IgnoreAllPropertiesWithAnInaccessibleSetter();
        }, assembly);
    }
</code></pre>
<p><strong>Controller</strong></p>
<p>This is our controller.</p>
<pre><code>[Route(&quot;api/[controller]&quot;)]
[ApiController]
public class OurController : ControllerBase
{
    private readonly OurContext _context;

    protected readonly ILogger&lt;OurController&gt; Logger;

    private readonly IMapper _mapper;

    public OurController(OurContext context, ILogger&lt;OurController&gt; logger, 
        IMapper mapper)
    {
        _context = context ??
            throw new ArgumentNullException(nameof(context));
        Logger = logger ??
                 throw new ArgumentNullException(nameof(logger));
        _mapper = mapper ??
                  throw new ArgumentNullException(nameof(mapper));
    }

    [HttpGet]
    public async Task&lt;ActionResult&lt;IEnumerable&lt;OurDto&gt;&gt;&gt; GetAll()
    {

        IQueryable&lt;OurModel&gt; models = _context.OurModel;

        IQueryable&lt;OurDto&gt; dtos = 
            _mapper.Map&lt;IQueryable&lt;OurDto&gt;&gt;(models);

        return await dtos.ToListAsync();
    }
}
</code></pre>
<p><strong>Profile, Model, and DTO</strong></p>
<p>Profile</p>
<pre><code>public class OurProfile : Profile
{
    public OurProfile()
    {
        CreateMap&lt;OurModel, OurDto&gt;();
    }
}
</code></pre>
<p>Model</p>
<pre><code>public partial class OurModel
{
    public string Number { get; set; }
    public string Name1 { get; set; }
    public string Name2 { get; set; }
    public string Status { get; set; }
    public DateTime? Date { get; set; }
    public string Description { get; set; }
    public string Comment { get; set; }
    public string District { get; set; }
}
</code></pre>
<p>DTO</p>
<pre><code>public class OurDto
{
    public string Number { get; set; }
    public string Name1 { get; set; }
    public string Name2 { get; set; }
    public string Status { get; set; }
    public DateTime? Date { get; set; }
    public string Description { get; set; }
    public string Comment { get; set; }
    public string District { get; set; }
}
</code></pre>
<p><strong>Test Fixture</strong></p>
<p>This is our test fixture.</p>
<pre><code>public abstract class ApiClientFixture : IClassFixture&lt;WebApplicationFactory&lt;Startup&gt;&gt;
{
    private readonly WebApplicationFactory&lt;Startup&gt; _factory;

    protected abstract string RelativeUrl { get; }

    protected ApiClientFixture(WebApplicationFactory&lt;Startup&gt; factory)
    {
        _factory = factory;
    }

    protected HttpClient CreateClient()
    {
        HttpClient client;
        var builder = new UriBuilder();

        client = _factory.CreateClient();
        builder.Host = client.BaseAddress.Host;
        builder.Path = $&quot;{RelativeUrl}&quot;;

        client.BaseAddress = builder.Uri;
        return client;
    }
}
</code></pre>
<p><strong>Test</strong></p>
<p>This is our test class. The single test in this test class fails.</p>
<pre><code>public class Tests : ApiClientFixture
{
    public Tests(WebApplicationFactory&lt;Startup&gt; factory) : base(factory)
    {
    }

    protected override string RelativeUrl =&gt; &quot;api/OurController/&quot;;

    [Fact]
    public async void GetAllReturnsSomething()
    {
        var response = await CreateClient().GetAsync(&quot;&quot;);

        Assert.True(response.IsSuccessStatusCode);
    }
}
</code></pre>
<p>When I debug the test I see that a 500 status code is returned from the URL provided to the in-memory API.</p>
<p>Does anybody have some suggestions? More than half of our tests currently fail, and I suspect that AutoMapper is not configured properly for integration testing.</p>
",https://stackoverflow.com/questions/63510427/integration-testing-in-net-core-3-1-with-automapper-webapplicationfactory-ent,"['entity-framework', '.net-core', 'automapper', 'dto']",754,True,0,2
Integration Test Azure TimerTrigger Function,"<p>What is the best approach for integration testing an Azure TimerTrigger Function?</p>

<p>I have an Azure Function that copies data from an Oracle table to Azure SQL table and sends an email via SendGrid. Here is the pseudo code:</p>

<pre><code>public static void Run(TimerInfo myTimer, ILogger log)
{
    Fecth_Data_From_Oracle_table()
    Insert_Data_To_AzureSQL_table()
    Send_StatusEmail_Via_SendGrid()
}
</code></pre>

<p>As seen the Function doesn't return anything, so how would I approach Integration Testing this function? </p>

<p>Do I modify the return type to something like <code>Task&lt;IActionResult&gt;</code>, but then I am modifying some already running code and returning some HTTP codes based on results from the methods?</p>

<p>Do I just call the timer trigger function from Visual Studio with the api key and HttpClient class f.x. <code>GET https://myfunc01.azurewebsites.net/admin/functions/TimerTriggereFunc?code={key}</code> and assert on its return value? (This requires that the Function returns something.)</p>

<p>Jeff Holan has examples of integration testing an Azure Function locally by using the System.Diagnostics.Process class to start and stop the .NET Core CLI (dotnet.exe), which in turn starts the Azure Functions host through the func.dll, but this seems overly complicated. Is it a wrong approach to integration test the Azure Function where it is hosted in Azure or is it a must to test it locally?</p>

<p>I can't seem to find clear guidelines around this.</p>
",https://stackoverflow.com/questions/59880389/integration-test-azure-timertrigger-function,"['azure-functions', 'integration-testing']",344,False,0,1
Is unit testing just testing methods?,"<p>I'm a new software developer and the devs are going over the importance of Java Unit Testing. Is Unit Testing just testing the individual java methods? And what is integration testing in relation to unit testing in Java?</p>
",https://stackoverflow.com/questions/63362515/is-unit-testing-just-testing-methods,"['java', 'unit-testing', 'testing']",47,True,-1,1
How can I reduce code repetition in these before/after actions?,"<p>I'm trying to do integration testing against a real database and I'm new to jest and knex..</p>

<p>Here's what I have so far:</p>

<pre><code>describe('FooRepository', () =&gt; {
  let dbName;
  let conn;

  beforeAll(async () =&gt; {
    conn = getConnection();
    dbName = cryptoRandomString({ length: 5, characters: 'abcdefghijklmnopqrstuvwxyz' });
    await conn.raw(`CREATE DATABASE ${dbName}`);
    Model.knex(conn);
  });

  afterAll(async () =&gt; {
    await conn.raw(`DROP DATABASE ${dbName}`);
    await conn.destroy();
  });

  beforeEach(async () =&gt; {
    await conn.migrate.latest();
  });

  afterEach(async () =&gt; {
    await conn.migrate.rollback();
  });

  describe('getFooByID', () =&gt; {
    // test getFooByID()
  })
})
</code></pre>

<p>How can I put this dbName, conn, and those before/after actions into somewhere reusable?  Thanks</p>
",https://stackoverflow.com/questions/59777449/how-can-i-reduce-code-repetition-in-these-before-after-actions,"['node.js', 'jestjs', 'knex.js', 'objection.js']",90,False,0,1
Mocking S3 but not SQS from aws-sdk,"<p>I'm trying to use jest to mock only S3 from the aws-sdk, but not SQS for integration testing. How can I mock some parts of aws-sdk but not others?</p>
<p>Here's an example I'm trying:</p>
<pre><code>jest.mock('aws-sdk')

const AWS = require('aws-sdk')
const { SQS } = jest.requireActual('aws-sdk')
const { transactions } = require('functions/transactions/handler')
const path = require('path')
const fs = require('fs')

const s3GetObject = jest.fn().mockReturnValue({
  createReadStream: jest.fn().mockReturnValue(
    fs.createReadStream(path.resolve('__tests__/fixtures/data/transactions/example_with_lines.csv'))
  )
})

AWS.S3.mockImplementation(() =&gt; ({
  getObject: s3GetObject
}))

test('Integration Test: Send Large transaction file to QUEUE_TRANSACTION_URL SQS Queue', async () =&gt; {
  //const sqsSpy = jest.spyOn(SQS, 'sendMessageBatch')

  const testRecords = {
    Records: [{
      s3: {
        object: {
          key: 'testfile.csv'
        }
      }
    }]
  }

  await transactions(testRecords)
  expect(s3GetObject.mock.calls.length).toBe(1)
  expect(s3GetObject.mock.calls[0][0].Key).toBe('testFile.csv')
})
</code></pre>
<p>And I get back:</p>
<pre><code>&quot;sqs.sendMessageBatch is not a function&quot;,
&quot;stack&quot;:
&quot;TypeError: sqs.sendMessageBatch is not a function
    at sendMessageBatch (/app/app/services/aws/sendMessageToQueue.js:18:14)
    at sendBatch (/app/app/services/aws/sendMessageToQueue.js:26:25)
    at sendMessages (/app/app/services/handler.js:30:37)
    at Array.map (&lt;anonymous&gt;)
    at map (/app/app/services/handler.js:29:44)
    at Object.&lt;anonymous&gt; (/app/__tests__/integration/transaction.test.js:32:
</code></pre>
",https://stackoverflow.com/questions/63619262/mocking-s3-but-not-sqs-from-aws-sdk,['jestjs'],536,True,0,1
.Net Core 3 Worker Integration Tests,"<p>For integration testing Asp.Net Core application we have <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1#basic-tests-with-the-default-webapplicationfactory"" rel=""noreferrer"">WebApplicationFactory</a>. But how to test <code>Worker</code> (<code>HostedService</code>) that is not web application? I don't want to copy the whole DI configuration in SUT like in <a href=""https://stackoverflow.com/questions/51224146/integration-test-for-hosted-service-net-core"">this question</a>. Is it possible to use original configuration and override some of dependencies like we do for web application in <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1#customize-the-client-with-withwebhostbuilder"" rel=""noreferrer"">WebApplicationFactory.WithWebHostBuilder</a>?</p>
",https://stackoverflow.com/questions/60796678/net-core-3-worker-integration-tests,"['asp.net-core', '.net-core', '.net-core-3.0']",2302,True,9,1
Integration testing of a Spring Cloud application with the AWS Parameter Store,"<p>How to perform integration testing of a Spring Boot application reading properties from the AWS Parameter Store (dependency <code>org.springframework.cloud:spring-cloud-starter-aws-parameter-store-config</code>).</p>

<p>Should the AWS Parameter Store integration be disabled in integration tests?</p>

<p>How to use local server (or mock) instead of the real AWS Parameter Store in integration tests?</p>
",https://stackoverflow.com/questions/60915364/integration-testing-of-a-spring-cloud-application-with-the-aws-parameter-store,"['spring', 'amazon-web-services', 'spring-boot', 'spring-cloud', 'aws-parameter-store']",2058,True,3,1
Integration testing with Testcontainers + Quarkus + MongoDB,"<p>Trying out testcontainers for integration testing. I am testing rest api endpoint. Here is the technology stack - 
quarkus, RESTEasy and mongodb-client</p>

<p>I am able to see MongoDB container is started successfully but getting exception. Exception: ""com.mongodb.MongoSocketOpenException: Exception opening socket""</p>

<pre><code>2020-04-26 15:13:18,330 INFO  [org.tes.doc.DockerClientProviderStrategy] (main) Loaded org.testcontainers.dockerclient.UnixSocketClientProviderStrategy from ~/.testcontainers.properties, will try it first
2020-04-26 15:13:19,109 INFO  [org.tes.doc.UnixSocketClientProviderStrategy] (main) Accessing docker with local Unix socket
2020-04-26 15:13:19,109 INFO  [org.tes.doc.DockerClientProviderStrategy] (main) Found Docker environment with local Unix socket (unix:///var/run/docker.sock)
2020-04-26 15:13:19,258 INFO  [org.tes.DockerClientFactory] (main) Docker host IP address is localhost
2020-04-26 15:13:19,305 INFO  [org.tes.DockerClientFactory] (main) Connected to docker: 
  Server Version: 19.03.8
  API Version: 1.40
  Operating System: Docker Desktop
  Total Memory: 3940 MB
2020-04-26 15:13:19,524 INFO  [org.tes.uti.RegistryAuthLocator] (main) Credential helper/store (docker-credential-desktop) does not have credentials for quay.io
2020-04-26 15:13:20,106 INFO  [org.tes.DockerClientFactory] (main) Ryuk started - will monitor and terminate Testcontainers containers on JVM exit
2020-04-26 15:13:20,107 INFO  [org.tes.DockerClientFactory] (main) Checking the system...
2020-04-26 15:13:20,107 INFO  [org.tes.DockerClientFactory] (main) ✔︎ Docker server version should be at least 1.6.0
2020-04-26 15:13:20,230 INFO  [org.tes.DockerClientFactory] (main) ✔︎ Docker environment should have more than 2GB free disk space
2020-04-26 15:13:20,291 INFO  [🐳 .2]] (main) Creating container for image: mongo:4.2
2020-04-26 15:13:20,420 INFO  [🐳 .2]] (main) Starting container with ID: d8d142bcdef8e2ebe9c09f171845deffcda503d47aa4893cd44e72d7067f0cdd
2020-04-26 15:13:20,756 INFO  [🐳 .2]] (main) Container mongo:4.2 is starting: d8d142bcdef8e2ebe9c09f171845deffcda503d47aa4893cd44e72d7067f0cdd
2020-04-26 15:13:22,035 INFO  [🐳 .2]] (main) Container mongo:4.2 started in PT3.721S
2020-04-26 15:13:24,390 INFO  [org.mon.dri.cluster] (main) Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2020-04-26 15:13:24,453 INFO  [org.mon.dri.cluster] (main) Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2020-04-26 15:13:24,453 INFO  [org.mon.dri.cluster] (cluster-ClusterId{value='5ea5dd542fb66c613dc74629', description='null'}-127.0.0.1:27017) Exception in monitor thread while connecting to server 127.0.0.1:27017: com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.internal.connection.SocketChannelStream.open(SocketChannelStream.java:63)
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:126)
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:714)
    at sun.nio.ch.SocketAdaptor.connect(SocketAdaptor.java:122)
    at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:64)
    at com.mongodb.internal.connection.SocketChannelStream.initializeSocketChannel(SocketChannelStream.java:72)
    at com.mongodb.internal.connection.SocketChannelStream.open(SocketChannelStream.java:60)
    ... 3 more

</code></pre>

<p>If I use docker run then my test case works properly.</p>

<pre><code>docker run -p 27017:27017 --name mongodb mongo:4.2
</code></pre>

<p>using testcontainer as mentioned @ <a href=""https://www.testcontainers.org/quickstart/junit_5_quickstart/"" rel=""noreferrer"">https://www.testcontainers.org/quickstart/junit_5_quickstart/</a></p>

<pre><code>@Container
    static GenericContainer mongodb = new GenericContainer&lt;&gt;(""mongo:4.2"").withExposedPorts(27017);
</code></pre>
",https://stackoverflow.com/questions/61447252/integration-testing-with-testcontainers-quarkus-mongodb,"['mongodb', 'docker', 'quarkus', 'testcontainers']",5906,True,10,5
How to unit test a [System.Web.Http.Authorize] filter in ASP.net with Xunit,"<p>I need to check the ModelState of controller method which has AUTHORIZE filter, because of that it is not accessible.</p>

<pre><code>    [Microsoft.AspNetCore.Mvc.Produces(""application/json"")]
    [System.Web.Http.Authorize]
    public Microsoft.AspNetCore.Mvc.ActionResult&lt;HttpResponseMessage&gt; CrowdSourcedData([FromBody] List&lt;Apps&gt; Apps)
    {
        if (!ModelState.IsValid)
        {
            return null;
        }
        return _dataProcessor.CrowdSourcedData(Apps);
    }
</code></pre>

<p>How can I unit test this method, I have tried other given options but nothing worked and I don't want to do Integration testing.</p>
",https://stackoverflow.com/questions/62046615/how-to-unit-test-a-system-web-http-authorize-filter-in-asp-net-with-xunit,['c#'],136,True,0,1
Integration testing on Shiny apps,"<p>I'm trying to use integration testing on this shiny app, but after reading up on it, I'm not sure what I'm doing wrong. I keep getting this error: Error in isModuleServer(app) : object 'session' not found
I'm also getting this error: Error: object 'output' not found</p>
<p>Any help is appreciated.</p>
<pre><code>library(shiny)
displayColoredBox&lt;- function(color, riskMessage){
  sidebarPanel(style=sprintf(&quot;background-color: %s; width: 300px; height: 300px;&quot;, color),
               h3(sprintf(&quot;%s&quot;, riskMessage)) )  }
shinyApp(
  ui = fluidPage(
    
    div(
      id = &quot;form&quot;,
      sliderInput(&quot;count1&quot;, &quot;First Slider Input&quot;, value=0, min=0, max=5000),
      sliderInput(&quot;count2&quot;, &quot;Second Slider Input&quot;, value=0, min=0, max=5000),
      uiOutput(&quot;coloredBox&quot;)
    )),
  
  server &lt;- function(input, output) {
    
    output$coloredBox&lt;-renderUI({
      req(input$count1)
      req(input$count2)
      
      count1 &lt;- input$count1;
      count2 &lt;- input$count2;
      
      likelihood &lt;- (count1*count2)/5000000
      
      
      if (likelihood&gt;1) {
        color=&quot;red&quot;
        riskMessage=&quot;Extreme risk!&quot;
        
      } else if (likelihood&gt;.65){
        color=&quot;orange&quot;
        riskMessage=&quot;Very high risk!&quot;
      }
      else if (likelihood&gt;.35){
        color=&quot;yellow&quot;
        riskMessage=&quot;High risk!&quot;
      }
      else if (likelihood&gt;.10){
        color=&quot;blue&quot;
        riskMessage=&quot;Moderate risk!&quot;
      } else {
        color=&quot;green&quot;
        riskMessage=&quot;Low risk!&quot;
      }
      
      displayColoredBox(color, riskMessage)
      
    })
  }
)

testServer({
  session$setInputs(count1 = 1500)
  session$setInputs(count2 = 2500)
  
  stopifnot(output$likelihood == 0.75)
  stopifnot(output$riskMessage == &quot;Very high risk!&quot;)
  stopifnot(output$color == &quot;orange&quot;)
  
})
</code></pre>
",https://stackoverflow.com/questions/63575035/integration-testing-on-shiny-apps,"['r', 'shiny', 'shiny-server', 'shinyapps', 'shiny-reactivity']",300,True,2,1
Pass list object in Mockmvc using JUint5,"<p>I'm using JUnit5 for my integration testing. I have a list of objects which needs to be passed to the endpoint. The content parameter of Mockmvc takes an only string. How can I pass this object? Any idea would be greatly appreciated.</p>
<p>Here is my code:</p>
<pre><code>    Customer cust1 = Customer.builder().name(&quot;Syed&quot;)
            .location(&quot;India&quot;).build();
Customer cust2 = Customer.builder().name(&quot;Ali&quot;)
            .location(&quot;India&quot;).build();

    
    List&lt;Customer&gt; customers = Arrays.asList(cust1, cust2); --&gt; This needs to be passed. 
    
    MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post(&quot;/process&quot;)
            
            .content(customers) --&gt; Compilation error here
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andReturn();
</code></pre>
<p>How can I solve it?</p>
",https://stackoverflow.com/questions/60484695/pass-list-object-in-mockmvc-using-juint5,"['java', 'mockito', 'junit5']",2551,True,1,2
GraphQL Test returns 404 not found,"<p>I have a Spring Boot application that uses GraphQL. I would like to add integration testing using Spring Boot GraphQL Test library. I am trying the following test:</p>
<pre><code>@GraphQLTest
public class UserTest {
  @Autowired
  private GraphQLTestTemplate graphQLTestTemplate;

  @Test
  public void createUser() throws IOException {
    GraphQLResponse response = graphQLTestTemplate.postForResource(&quot;graphql/register.graphql&quot;);
    assertNotNull(response);
    assertTrue(response.isOk());
    assertEquals(&quot;1&quot;, response.get(&quot;$.data.post.id&quot;));
  }
}
</code></pre>
<p>and I get the following response:</p>
<pre><code>&lt;404,&lt;!doctype html&gt;&lt;html lang=&quot;en&quot;&gt;&lt;head&gt;&lt;title&gt;HTTP Status 404 – Not Found&lt;/title&gt;&lt;style type=&quot;text/css&quot;&gt;body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;HTTP Status 404 – Not Found&lt;/h1&gt;&lt;hr class=&quot;line&quot; /&gt;&lt;p&gt;&lt;b&gt;Type&lt;/b&gt; Status Report&lt;/p&gt;&lt;p&gt;&lt;b&gt;Message&lt;/b&gt; The requested resource [&amp;#47;api&amp;#47;graphql] is not available&lt;/p&gt;&lt;p&gt;&lt;b&gt;Description&lt;/b&gt; The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.&lt;/p&gt;&lt;hr class=&quot;line&quot; /&gt;&lt;h3&gt;Apache Tomcat/9.0.37&lt;/h3&gt;&lt;/body&gt;&lt;/html&gt;,[Content-Type:&quot;text/html;charset=utf-8&quot;, Content-Language:&quot;en&quot;, Content-Length:&quot;766&quot;, Date:&quot;Sun, 08 Nov 2020 00:18:11 GMT&quot;, Keep-Alive:&quot;timeout=60&quot;, Connection:&quot;keep-alive&quot;]&gt;
</code></pre>
<p>Here is the related GitHub issue:
<a href=""https://github.com/graphql-java-kickstart/graphql-spring-boot/issues/267"" rel=""nofollow noreferrer"">https://github.com/graphql-java-kickstart/graphql-spring-boot/issues/267</a></p>
<p>Any help is appreciated ...</p>
",https://stackoverflow.com/questions/64752857/graphql-test-returns-404-not-found,"['spring-boot', 'graphql-java']",1659,True,4,1
Extend/Custom IApplicationBuilder when running TestServer in a .NET Core 3.1 Web API unit test,"<p>I want to use a TestServer in a unit test for integration testing.</p>

<p>I'm currently using this code:</p>

<pre><code>var hostBuilder = new HostBuilder()
            .ConfigureWebHost(webHost =&gt;
            {
                // Add TestServer
                webHost.UseTestServer();
                webHost.UseStartup&lt;Startup&gt;();

            });
</code></pre>

<p>which uses my default Startup implementation.</p>

<p>I want to call an additional function of IApplicationBuilder (in Startup.Configure) for my unit test.
What would be the best way to achieve this without boilerplate code?</p>
",https://stackoverflow.com/questions/61155626/extend-custom-iapplicationbuilder-when-running-testserver-in-a-net-core-3-1-web,"['c#', 'asp.net-core', 'asp.net-web-api', 'asp.net-core-webapi']",514,False,0,1
Jest Node.js Not able to call beforeAll and afterAll properly using separate file,"<p>I have defined <code>beforAll</code> and <code>afterAll</code> in a separate file <code>bootstrap.js</code> but I am not able to do integration testing. I am using serverless stack. I took help from github but that example was written in mocha so I tried to transform it to jest.</p>

<p><code>bootstrap.js</code></p>

<pre><code>beforeAll(async () =&gt; {
    console.log('[Tests Bootstrap] Start');

    await startSlsOffline((err) =&gt; {
        if (err) {
            console.log(err);
        }

        console.log('[Tests Bootstrap] Done');
    });
}, 30000);

afterAll(async () =&gt; {
    console.log('[Tests Teardown] Start');

    await stopSlsOffline();

    console.log('[Tests Teardown] Done');
});

</code></pre>

<p><code>handler.test.js</code></p>

<pre><code>describe('get Endpoints', () =&gt; {
    const server = request(`http://localhost:3005`);
    test('should run get example', async () =&gt; {
        const res = await server.get('/example');
        console.log('res', res.body);
    });
});
</code></pre>

<p>My jest configuration is</p>

<pre><code>module.exports = {
    verbose: true,
    bail: true,
    coverageDirectory: 'output/coverage/jest',
    setupFilesAfterEnv: [ './bootstrap.js' ]
};
</code></pre>

<p>The output I get is </p>

<pre><code>&gt; jest --config test/jest.config.js

 FAIL  test/handler.test.js
  get Endpoints
    ✕ should run get example (38ms)

  ● get Endpoints › should run get example

    connect ECONNREFUSED 127.0.0.1:3005



  console.log test/bootstrap.js:6
    [Tests Bootstrap] Start

  console.log test/bootstrap.js:30
    Serverless: Offline started with PID : 5587 and PORT: 3005

  console.log test/bootstrap.js:18
    [Tests Teardown] Start

  console.log test/bootstrap.js:47
    Serverless Offline stopped

  console.log test/bootstrap.js:22
    [Tests Teardown] Done

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.825s
Ran all test suites.
npm ERR! Test failed.  See above for more details.
</code></pre>
",https://stackoverflow.com/questions/59676343/jest-node-js-not-able-to-call-beforeall-and-afterall-properly-using-separate-fil,"['javascript', 'node.js', 'jestjs', 'serverless-framework']",1885,True,0,2
Mule Flow only for Integration Testing,"<p>I have got the Mule 4 application which is driven by Scheduler to schedule every 30 minutes. I have added http listener under the file test-listener.xml just for invoking it for building the integration testing.</p>
<p>I want the test-listener.xml to be deployed only into non-production environment. How can I achieve it in Mule 4.3.0 Runtime</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/65069092/mule-flow-only-for-integration-testing,['mule'],313,True,2,1
Spring Data JPA - Unit Testing with H2,"<p>My app is calling Oracle DB using Spring data JPA, and one of the operations is calling a Stored Procedure.</p>
<p>When it come to integration testing, I'm using H2 DB, but I found difficulties to call the SP.</p>
<p>Below is the way I'm calling the SP</p>
<pre><code>final StoredProcedureQuery query = entityManager
            .createStoredProcedureQuery(&quot;MY_SP_HERE&quot;)
            .registerStoredProcedureParameter(&quot;PARAM_1&quot;, String.class, ParameterMode.IN)
            .setParameter(&quot;PARAM_1&quot;, &quot;VALUE_PARAM_1&quot;)
            .registerStoredProcedureParameter(&quot;V_CURSOR_OUT&quot;, CustomClass.class,
                    ParameterMode.REF_CURSOR);

query.execute();

final List&lt;Object[]&gt; obj = query.getResultList();
</code></pre>
<p>Is it possible to call the SP from H2 ?</p>
",https://stackoverflow.com/questions/62594362/spring-data-jpa-unit-testing-with-h2,"['spring', 'unit-testing', 'spring-data-jpa', 'h2']",202,False,0,0
Embedding Apache FTP Server : Not able to login with 40 user Concurrently,"<p>I am using this Embedded server for integration testing of <strong>Spring-integration-ftp</strong>.
I have to connect this ftp server to 40 spring integration ftp service I have also added ConcurrentLoginPermission to 50 still I am getting
<strong>SENT: 421 Maximum login limit has been reached.</strong> Error
Here is the code Which I have written for the embedded server.</p>
<pre><code>
   protected static final Integer FTP_PORT = 2221;
       protected static final String FTP_USER = &quot;admin&quot;;
       protected static final String FTP_PASSWORD = &quot;admin&quot;;
       protected static final String FTP_HOME_DIRECTORY = &quot;src/test/resources/xml/checkpoint&quot;;```
   
   ```PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
           UserManager userManager = userManagerFactory.createUserManager();
           BaseUser user = new BaseUser();
           user.setName(FTP_USER);
           user.setPassword(FTP_PASSWORD);
           user.setHomeDirectory(FTP_HOME_DIRECTORY);
           List&lt;Authority&gt; authorities = new ArrayList&lt;&gt;();
           authorities.add(new WritePermission());
           authorities.add(new TransferRatePermission(50, 50));
           authorities.add(new ConcurrentLoginPermission(50, 50));
           user.setAuthorities(authorities);
           try {
               userManager.save(user);
           } catch (FtpException e) {
               e.printStackTrace();
           }
           ListenerFactory listenerFactory = new ListenerFactory();
           listenerFactory.setPort(FTP_PORT);
           FtpServerFactory factory = new FtpServerFactory();
           factory.setUserManager(userManager);
           factory.addListener(&quot;default&quot;, listenerFactory.createListener());
           FtpServer server = factory.createServer();
           try {
               server.start();
           } catch (FtpException e) {
               e.printStackTrace();
           }
           FakeFtpServer fakeFtpServer = new FakeFtpServer();
           fakeFtpServer.setServerControlPort(2222);
           FileSystem fileSystem = new UnixFakeFileSystem();
           fileSystem.add(new DirectoryEntry(&quot;/FTP_TEST&quot;));
           fakeFtpServer.setFileSystem(fileSystem);
           UserAccount userAccount = new UserAccount(&quot;vioohcentral&quot;, &quot;vioohcentral&quot;, &quot;/FTP_TEST&quot;);
           fakeFtpServer.addUserAccount(userAccount);
           fakeFtpServer.start();

</code></pre>
",https://stackoverflow.com/questions/64226196/embedding-apache-ftp-server-not-able-to-login-with-40-user-concurrently,"['spring', 'integration-testing', 'spring-integration-ftp']",140,False,1,0
do not create spring bean during integration testing,"<p>I have a Spring Config class which I want to have it loaded when the application is running.</p>
<pre><code>@Configuration
public class EventHubConfiguration {


    @Bean
    @ConfigurationProperties(...)
    public EventHubClient someClient(final String namespace,
                                     final String eventHubName,
                                     final String sasKeyName,
                                     final String sasKey) throws IOException, EventHubException {
        ConnectionStringBuilder connStr = new ConnectionStringBuilder()
                .setNamespaceName(namespace)
                .setEventHubName(eventHubName)
                .setSasKeyName(sasKeyName)
                .setSasKey(sasKey);
        return EventHubClient.createSync(connStr.toString(), Executors.newSingleThreadScheduledExecutor());
    }
}
</code></pre>
<p>But how can I prevent it from loading when my integration tests are running. For example when I do <code>mvn clean test</code> or as part of my build. I don't wish the eventhub client to be created during my integration testing.</p>
",https://stackoverflow.com/questions/64008070/do-not-create-spring-bean-during-integration-testing,"['java', 'spring', 'spring-boot']",242,False,-1,1
Different possibilities of Firebase Test Labs for flutter,"<p>I have a flutter app developed and now I need to integrate automated UI testing, upon some research, I came to know about Firebase Test Lab (<a href=""https://firebase.google.com/docs/test-lab"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/test-lab</a>)</p>
<p>Then I learned that it is not supported for Flutter (<a href=""https://stackoverflow.com/a/61779777"">https://stackoverflow.com/a/61779777</a>)</p>
<p>On further digging I found Flutter Test (<a href=""https://flutter.dev/docs/testing"" rel=""nofollow noreferrer"">https://flutter.dev/docs/testing</a>) and to be specific I was in need of Integration Testing (<a href=""https://flutter.dev/docs/testing#integration-tests"" rel=""nofollow noreferrer"">https://flutter.dev/docs/testing#integration-tests</a>), but the problem I see here is this integration testing can not be automated (using CI/CD or using other third party services) or I may be wrong in this understanding.</p>
<p>Hence I wanted to ask to the Flutter and Firebase community that</p>
<ol>
<li>Is there any way I can use Test Labs of Firebase for Flutter Project</li>
<li>Or some other service provider where I can get near to similar service / functionality what Firebase Test labs offers for Android / iOS</li>
</ol>
<p>Thanks.</p>
",https://stackoverflow.com/questions/64898800/different-possibilities-of-firebase-test-labs-for-flutter,"['firebase', 'flutter', 'flutter-test', 'firebase-test-lab']",228,False,0,0
Getting MappingException when reading TINYINT value from H2 database as boolean/Boolean,"<p>I am using R2DBC H2 for integration testing my reactive application (which is based on Spring Webflux , Java).</p>
<p>Versions</p>
<ul>
<li>Driver: io.r2dbc:r2dbc-h2:0.8.4.RELEASE (Spring boot 2.3.2.RELEASE)</li>
<li>Java: 11</li>
<li>OS: Mac</li>
</ul>
<p>I have a table defined like this:</p>
<pre class=""lang-sql prettyprint-override""><code>CREATE TABLE `prep_task` (
  `id` SERIAL,
  `external_id` VARCHAR(45) NOT NULL,
  `name` VARCHAR(45) NOT NULL,
  `description` VARCHAR(100) NULL,
  `is_active` TINYINT,
  PRIMARY KEY (`id`)
);
</code></pre>
<p>And corresponding entity:</p>
<pre class=""lang-java prettyprint-override""><code>@Table(&quot;prep_task&quot;)
public class PrepTaskEntity implements Persistable&lt;Long&gt; {
  @Id
  @Column(&quot;id&quot;)
  private Long id;

  @Column(&quot;external_id&quot;)
  private String externalId;

  @Column(&quot;name&quot;)
  private String name;

  @Column(&quot;description&quot;)
  private String description;

  @Column(&quot;is_active&quot;)
  private boolean isActive;

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getExternalId() {
    return externalId;
  }

  public void setExternalId(String externalId) {
    this.externalId = externalId;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public boolean isActive() {
    return isActive;
  }

  public void setActive(boolean active) {
    isActive = active;
  }

  @Override
  public boolean isNew() {
    return id == null;
  }


}
</code></pre>
<p><strong>No issue when saving <code>PrepTaskEntity</code> but when trying to read, getting the following error</strong>:</p>
<pre><code>org.springframework.data.mapping.MappingException: Could not read property @org.springframework.data.relational.core.mapping.Column(value=&quot;is_active&quot;)private java.lang.Boolean com.example.demosvc.persistence.entities.PrepTaskEntity.isActive from result set!
    at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.readFrom(MappingR2dbcConverter.java:172) ~[spring-data-r2dbc-1.1.2.RELEASE.jar:1.1.2.RELEASE]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
    |_ checkpoint ⇢ Handler com.example.demosvc.controllers.PrepTaskController#getPrepTasksForGivenBU(String) [DispatcherHandler]
    |_ checkpoint ⇢ com.example.demosvc.filters.TenancyContextFilter [DefaultWebFilterChain]
    |_ checkpoint ⇢ HTTP GET &quot;/sites/BU-002/prepTasks&quot; [ExceptionHandlingWebHandler]
Stack trace:
        at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.readFrom(MappingR2dbcConverter.java:172) ~[spring-data-r2dbc-1.1.2.RELEASE.jar:1.1.2.RELEASE]
        at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.read(MappingR2dbcConverter.java:133) ~[spring-data-r2dbc-1.1.2.RELEASE.jar:1.1.2.RELEASE]
        at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.read(MappingR2dbcConverter.java:116) ~[spring-data-r2dbc-1.1.2.RELEASE.jar:1.1.2.RELEASE]
        at org.springframework.data.r2dbc.convert.EntityRowMapper.apply(EntityRowMapper.java:46) ~[spring-data-r2dbc-1.1.2.RELEASE.jar:1.1.2.RELEASE]
        at org.springframework.data.r2dbc.convert.EntityRowMapper.apply(EntityRowMapper.java:29) ~[spring-data-r2dbc-1.1.2.RELEASE.jar:1.1.2.RELEASE]
        at io.r2dbc.h2.H2Result.lambda$map$0(H2Result.java:67) ~[r2dbc-h2-0.8.4.RELEASE.jar:0.8.4.RELEASE]
        at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:100) ~[reactor-core-3.3.8.RELEASE.jar:3.3.8.RELEASE]
        at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:73) ~[reactor-core-3.3.8.RELEASE.jar:3.3.8.RELEASE]
...
Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.Byte] to type [java.lang.Boolean]
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:321) ~[spring-core-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:194) ~[spring-core-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:174) ~[spring-core-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.getPotentiallyConvertedSimpleRead(MappingR2dbcConverter.java:263) ~[spring-data-r2dbc-1.1.2.RELEASE.jar:1.1.2.RELEASE]
    at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.readValue(MappingR2dbcConverter.java:187) ~[spring-data-r2dbc-1.1.2.RELEASE.jar:1.1.2.RELEASE]
    at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.readFrom(MappingR2dbcConverter.java:169) ~[spring-data-r2dbc-1.1.2.RELEASE.jar:1.1.2.RELEASE]
    at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.read(MappingR2dbcConverter.java:133) ~[spring-data-r2dbc-1.1.2.RELEASE.jar:1.1.2.RELEASE]
    at org.springframework.data.r2dbc.convert.MappingR2dbcConverter.read(MappingR2dbcConverter.java:116) ~[spring-data-r2dbc-1.1.2.RELEASE.jar:1.1.2.RELEASE]
    at org.springframework.data.r2dbc.convert.EntityRowMapper.apply(EntityRowMapper.java:46) ~[spring-data-r2dbc-1.1.2.RELEASE.jar:1.1.2.RELEASE]
    at org.springframework.data.r2dbc.convert.EntityRowMapper.apply(EntityRowMapper.java:29) ~[spring-data-r2dbc-1.1.2.RELEASE.jar:1.1.2.RELEASE]
    at io.r2dbc.h2.H2Result.lambda$map$0(H2Result.java:67) ~[r2dbc-h2-0.8.4.RELEASE.jar:0.8.4.RELEASE]
</code></pre>
<p>Just FYI I am using MySQL as connection mode for H2.</p>
<pre class=""lang-java prettyprint-override""><code>@Configuration
@Profile(Application.Profiles.INTEGRATION_TEST)
public class H2ConnectionConfig extends AbstractR2dbcConfiguration {

  private final R2dbcConfigProperties r2dbcConfigProperties;

  @Autowired
  public H2ConnectionConfig(R2dbcConfigProperties r2dbcConfigProperties) {
    this.r2dbcConfigProperties = r2dbcConfigProperties;
  }

  @Override
  @Bean
  public ConnectionFactory connectionFactory() {
    RoutingConnectionFactory connectionFactory = new RoutingConnectionFactory();
    Map&lt;String, ConnectionFactory&gt; factories = new HashMap&lt;&gt;();
    H2ConnectionConfiguration.Builder configurationBuilder = H2ConnectionConfiguration.builder()
        .property(H2ConnectionOption.MODE, &quot;MySQL&quot;)
        .property(H2ConnectionOption.DB_CLOSE_DELAY, &quot;-1&quot;)
        .property(H2ConnectionOption.DB_CLOSE_ON_EXIT, &quot;false&quot;);
    for (String tenant : r2dbcConfigProperties.getTenants()) {
      String databaseName = r2dbcConfigProperties.getDbPrefix() + tenant;
      factories.put(tenant, new H2ConnectionFactory(configurationBuilder.inMemory(databaseName).build()));
    }
    connectionFactory.setTargetConnectionFactories(factories);
    connectionFactory.setDefaultTargetConnectionFactory(factories.get(&quot;default&quot;));
    return connectionFactory;
  }

}
</code></pre>
",https://stackoverflow.com/questions/63390995/getting-mappingexception-when-reading-tinyint-value-from-h2-database-as-boolean,"['java', 'spring-boot', 'h2', 'spring-webflux', 'spring-data-r2dbc']",2492,True,4,1
Snowflake Integration Testing Implementation,"<p>I have a service(Java + Springboot) which uses PostgreSQL database, the service will be migrated to <strong>Snowflake</strong> (cloud-based data-warehousing) so I would like to know what is the best way to implement integration testing</p>

<p>I tried to find a <strong>snowflake docker image</strong> (docker hub) or a <strong>testcontainer</strong> but so far I have not found anything useful, any suggestions?</p>

<p><a href=""https://www.testcontainers.org/"" rel=""nofollow noreferrer"">https://www.testcontainers.org/</a></p>

<p><a href=""https://hub.docker.com/"" rel=""nofollow noreferrer"">https://hub.docker.com/</a></p>
",https://stackoverflow.com/questions/60419383/snowflake-integration-testing-implementation,"['java', 'spring-boot', 'integration-testing', 'snowflake-cloud-data-platform']",4339,False,4,2
Integration testing in .net core api 3.1,"<p>I am trying to implement integration testing for each API that i have developed in .Net core 3.1 and have followed   <a href=""https://learn.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/test-aspnet-core-services-web-apps"" rel=""nofollow noreferrer"">this link</a>      to create test cases for it.        </p>

<p>Please find the below test class that i have created for my API.</p>

<p><a href=""https://i.stack.imgur.com/V84Xg.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/V84Xg.png"" alt=""enter image description here""></a></p>

<p>But while executing i am getting error in this line <code>_server = new TestServer(new WebHostBuilder()
           .UseStartup&lt;Startup&gt;());</code>  which is as below :</p>

<p><a href=""https://i.stack.imgur.com/KDFhW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/KDFhW.png"" alt=""Error""></a></p>

<p>Am i missing anything here ?</p>
",https://stackoverflow.com/questions/61577778/integration-testing-in-net-core-api-3-1,"['.net', 'asp.net-core', '.net-core', 'integration-testing', 'asp.net-core-testhost']",220,True,0,1
Corda - How do you implement expectEvents parallel predicates using Java,"<p>I'm looking for a Java example similar to the Kotlin code shown in the following example (taken from the Corda integration testing tutorial at: <a href=""https://docs.corda.net/releases/release-M6.0/tutorial-integration-testing.html"" rel=""nofollow noreferrer"">https://docs.corda.net/releases/release-M6.0/tutorial-integration-testing.html</a>)</p>

<pre><code>bobVaultUpdates.expectEvents {
     parallel(
         (1 .. 10).map { i -&gt;
             expect(
                 match = { update: Vault.Update -&gt;
                                    (update.produced.first().state.data as Cash.State).amount.quantity == i * 100L
                 }
             ) { update -&gt;
                 println(""Bob vault update of $update"")
             }
         }
     )
}
</code></pre>

<p>I'm also curious if this technique is still recommended, as it seems to have been removed from the latest version of this tutorial (<a href=""https://docs.corda.net/releases/release-V4.3/tutorial-integration-testing.html"" rel=""nofollow noreferrer"">https://docs.corda.net/releases/release-V4.3/tutorial-integration-testing.html</a>).</p>
",https://stackoverflow.com/questions/60084745/corda-how-do-you-implement-expectevents-parallel-predicates-using-java,['corda'],59,True,-1,1
Get body of response in Superoak,"<p>I'm doing integration testing on Deno with Superoak and my application has one time password, for test a feature I need to know the one time password but for it I need its secret, which is informed on the body of the response of a POST.</p>
<p>I want to know how to get the response of this POST on Superoak.</p>
",https://stackoverflow.com/questions/65444557/get-body-of-response-in-superoak,"['integration-testing', 'deno']",97,True,0,1
SqlConnection/SqlCommand keeps database in use after Close and Dispose,"<p>I am trying to create a temporary database for the purpose of integration testing in Xunit, but when I try to drop the temporary database, I get an error:</p>
<blockquote>
<p>Cannot drop database &quot;TempDatabase_[numbers]&quot; because it is currently in use.</p>
</blockquote>
<p>Simply closing and disposing the command and connection does not seem to cut it.</p>
<p>This is a trimmed-down version of my test that is failing:</p>
<pre><code>using System;
using System.Data.SqlClient;
using Xunit;

namespace Test
{
    public class Test_Raw_Spec
    {
        [Fact]
        public void PerformWorkInTemporaryDatabase()
        {
            string connectionStringTemplate = &quot;Data Source=SQLEXPRESS;Initial Catalog={0};Integrated Security=SSPI;Connection Timeout=10&quot;;
            int dbNum = (new Random()).Next() % 1000000;
            int tblNum = (new Random()).Next() % 1000000;

            string nameTempDb = $&quot;TempDatabase_{dbNum}&quot;;
            string nameTempTable = $&quot;TempTable_{tblNum}&quot;;

            var sqlConnection1 = new SqlConnection(string.Format(connectionStringTemplate, &quot;master&quot;));
            var sqlCommand1 = new SqlCommand($&quot;CREATE DATABASE {nameTempDb}&quot;, sqlConnection1);
            sqlConnection1.Open();
            sqlCommand1.ExecuteNonQuery();
            sqlCommand1.Dispose();
            sqlConnection1.Close();
            sqlConnection1.Dispose();

            var sqlConnection2 = new SqlConnection(string.Format(connectionStringTemplate, nameTempDb));
            var sqlCommand2 = new SqlCommand($&quot;CREATE TABLE {nameTempTable}(id int)&quot;, sqlConnection2);
            sqlConnection2.Open();
            sqlCommand2.ExecuteNonQuery();
            sqlCommand2.Dispose();
            sqlConnection2.Close();
            sqlConnection2.Dispose();

            var sqlConnection3 = new SqlConnection(string.Format(connectionStringTemplate, &quot;master&quot;));
            var sqlCommand3 = new SqlCommand($&quot;DROP DATABASE {nameTempDb}&quot;, sqlConnection3);
            sqlConnection3.Open();
            sqlCommand3.ExecuteNonQuery();
            sqlCommand3.Dispose();
            sqlConnection3.Close();
            sqlConnection3.Dispose();
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/65384069/sqlconnection-sqlcommand-keeps-database-in-use-after-close-and-dispose,"['c#', '.net', 'sql-server', 'sqlconnection', 'sqlcommand']",731,True,3,2
Spring Boot integration test fails with &quot;No qualifying bean&quot; for MockMvc,"<p>I'd like to create an integration test for my Spring Boot application checking that a controller returns the correct HTTP status when sending an email.</p>
<p>This is how my test looks like:</p>
<pre><code>@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@Profile(&quot;test&quot;)
public class EmailControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

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

    private static final String RESOURCE_PATH = &quot;/mail&quot;;

    @Test
    public void whenValidInput_thenReturns200() throws Exception {
        final EmailNotification emailNotification = EmailNotification.builder()
                .emailAddress(&quot;foo@bar.com&quot;)
                .subject(&quot;TEST_SUBJECT&quot;)
                .content(&quot;TEST_CONTENT&quot;)
                .build();
        mockMvc.perform(post(RESOURCE_PATH)
                .contentType(APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(emailNotification))
        ).andExpect(status().isOk());
    }
}
</code></pre>
<p>However it fails with the following excetpion:</p>
<pre><code>No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code></pre>
<p>I looked at the Spring Boot tutorials on integration testing but cannot see what's wrong.</p>
<p>This is the controller under test:</p>
<pre><code>@RestController
public class EmailController {

    private static final Logger LOG = LoggerFactory.getLogger(EmailController.class.getName());

    private final EmailService emailService;

    @Autowired
    public EmailController(EmailService emailService) {
        this.emailService = emailService;
    }

    @PostMapping(value = &quot;/mail&quot;, consumes = MediaType.APPLICATION_JSON_VALUE)
    public void send(@Valid @RequestBody EmailNotification emailNotification) {
        try {
            emailService.sendEmail(emailNotification);
        } catch (MailException | MessagingException e) {
            LOG.error(&quot;Error sending email: (recipient address: {}): {}&quot;, emailNotification.getEmailAddress(), e.getMessage());
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/63686057/spring-boot-integration-test-fails-with-no-qualifying-bean-for-mockmvc,"['spring-boot', 'mockmvc', 'spring-test-mvc']",459,True,0,1
How to use Dependency Injection with Spring Boot Unit Testing?,"<p>Is it possible to use dependency injection with unit tests using Spring Boot? For integration testing <code>@SpringBootTest</code> start the whole application context and container services. But is it possible to enable dependency injection functionality at unit test granularity?</p>
<p>Here's the example code</p>
<pre><code>@ExtendWith(SpringExtension.class)
public class MyServiceTest {
    
    @MockBean
    private MyRepository repo;
    
    @Autowired
    private MyService service; // &lt;-- this is null
    
    @Test
    void getData() {
        MyEntity e1 = new MyEntity(&quot;hello&quot;);
        MyEntity e2 = new MyEntity(&quot;world&quot;);
        
        Mockito.when(repo.findAll()).thenReturn(Arrays.asList(e1, e2));
        
        List&lt;String&gt; data = service.getData();
        
        assertEquals(2, data.size());
    }
}

@Service
public class MyService {
    
    private final MyRepository repo; // &lt;-- this is null
    
    public MyService(MyRepository repo) {
        this.repo = repo;
    }
    
    public List&lt;String&gt; getData() {
        return repo.findAll().stream()
                .map(MyEntity::getData)
                .collect(Collectors.toList());
    }
}
</code></pre>
<p>Or should I just manage the SUT (service class) as POJO and manually inject the mocked dependencies? I want to keep tests fast but minimize boilerplate code.</p>
",https://stackoverflow.com/questions/65247432/how-to-use-dependency-injection-with-spring-boot-unit-testing,"['java', 'spring', 'spring-boot', 'unit-testing', 'mockito']",3099,True,4,2
Date format in the spring boot repository testing,"<p>I am using the following codes to do the integration testing for repository functions. However, it will fail because of the date formart. The output from SimpleDateFormat is 'Wed Jan 01 10:10:10 MST 2020', but the date from database is '2020-01-01 10:10:10.0'. Is their any easy way to handle this issue?</p>

<pre><code>      Optional&lt;TestBean&gt; testBean = testBeanRepository.findById(1L);
      TestBean toReturn = new TestBean();
      toReturn.setAccountNumber(123456789);
      toReturn.setId(1L);
      toReturn.setCustomerName(""Peter"");
      toReturn.setModifiedDate(new SimpleDateFormat(""yyyy-mm-dd HH:mm:ss"").parse(""2020-01-01 10:10:10""));
      assertThat(testBean)
         .isPresent()
         .hasValue(toReturn);
</code></pre>

<p>This is how I defined modified date(java.util.date):</p>

<pre><code>@Column(name = ""MODIFIED_DATE_TIME"") 
@NotNull 
@Temporal(TemporalType.TIMESTAMP) 
private Date modifiedDate;
</code></pre>
",https://stackoverflow.com/questions/60179101/date-format-in-the-spring-boot-repository-testing,"['java', 'spring-boot', 'integration-testing', 'simpledateformat', 'assertj']",3628,True,0,2
Any examples of Pact testing with Kafka in .net,"<p>We have a project where we are consuming data from a compacted Kafka topic.
The business is keen to use pact to cover integration testing across the suite of microservices.
However as of yet we have been unable to find anyone who has achieved this using .net.
Bearing in mind there is a relatively tight deadline for this is this a path worth pursuing?</p>
",https://stackoverflow.com/questions/64858746/any-examples-of-pact-testing-with-kafka-in-net,"['.net', 'apache-kafka', 'pact']",407,False,0,1
Switching between Databricks Connect and local Spark environment,"<p>I am looking to use Databricks Connect for developing a pyspark pipeline. DBConnect is really awesome because I am able to run my code on the cluster where the actual data resides, so it's perfect for integration testing, but I also want to be able to, during development and unit testing (<code>pytest</code> with <code>pytest-spark</code>), simply using a local Spark environment.</p>

<p>Is there any way to configure DBConnect so for one use-case I simply use a local Spark environment, but for another it uses DBConnect?</p>
",https://stackoverflow.com/questions/61734742/switching-between-databricks-connect-and-local-spark-environment,"['apache-spark', 'pyspark', 'databricks', 'databricks-connect']",907,False,11,1
Indexing a variable twice in R shiny,"<p>I'm trying to do some integration testing on my Shiny app, but I don't know what I'm doing wrong. I suspect it has to do with the fact I used the &quot;$&quot; twice when trying to access the likelihood, color, and riskMessage variables.
I keep running into this error:</p>
<pre><code>Error in checkEqualsNumeric(output$coloredBox$likelihoodOfHarm, 0.75) : 
  Modes: NULL, numeric
Lengths: 0, 1
target is NULL, current is numeric
</code></pre>
<p>Here is my Shiny app code, with my attempt to test the Shiny app at the bottom. Any help is greatly appreciated!</p>
<pre><code>displayColoredBox&lt;- function(color, riskMessage){
  sidebarPanel(style=sprintf(&quot;background-color: %s; width: 300px; height: 300px;&quot;, color),
               h3(sprintf(&quot;%s&quot;, riskMessage)) )  }

app &lt;- shinyApp(
  ui = fluidPage(
    
    div(
      id = &quot;form&quot;,
      sliderInput(&quot;count1&quot;, &quot;First Slider Input&quot;, value=0, min=0, max=5000),
      sliderInput(&quot;count2&quot;, &quot;Second Slider Input&quot;, value=0, min=0, max=5000),
      uiOutput(&quot;coloredBox&quot;)
    )),
  
  server &lt;- function(input, output, session) {
    
    output$coloredBox&lt;-renderUI({
      req(input$count1)
      req(input$count2)
      
      count1 &lt;- input$count1;
      count2 &lt;- input$count2;
      
      likelihood &lt;- (count1*count2)/5000000
      
      if (likelihood&gt;1) {
        color=&quot;red&quot;
        riskMessage=&quot;Extreme risk!&quot;
        
      } else if (likelihood&gt;.65){
        color=&quot;orange&quot;
        riskMessage=&quot;Very high risk!&quot;
      }
      else if (likelihood&gt;.35){
        color=&quot;yellow&quot;
        riskMessage=&quot;High risk!&quot;
      }
      else if (likelihood&gt;.10){
        color=&quot;blue&quot;
        riskMessage=&quot;Moderate risk!&quot;
      } else {
        color=&quot;green&quot;
        riskMessage=&quot;Low risk!&quot;
      }
      
      coloredBox=displayColoredBox(color, riskMessage)
      
    })
  }
)

testServer(app, {
  session$setInputs(count1 = 1500)
  session$setInputs(count2 = 2500)

  checkEqualsNumeric(output$coloredBox$likelihood, 0.75)
  checkEquals(output$coloredBox$riskMessage, &quot;Very high risk!&quot;)
  checkEquals(output$coloredBox$color, &quot;orange&quot;)

  
})
</code></pre>
",https://stackoverflow.com/questions/63588975/indexing-a-variable-twice-in-r-shiny,"['r', 'shiny', 'integration-testing', 'shiny-server', 'shiny-reactivity']",116,True,1,1
Error: Expected spy navigate to have been called with: [ [ &#39;/client/register&#39; ] ] but it was never called,"<p><strong>Error</strong>
Expected spy navigate to have been called with:   [ [ '/client/register' ] ] but it was never called. This is the error I'm getting. Also i don't know how to test a cookie value since it's a thirt party package.
I tried this link <a href=""https://stackoverflow.com/questions/46335028/expected-spy-navigate-to-have-been-called-with-users-but-it-was-never"">Expected spy navigate to have been called with [ [ &#39;users&#39; ] ] but it was never called in integration testing angular CLI</a> but it doesn't work for me.</p>

<p><strong>Signup.component.spec.ts</strong></p>

<pre><code>import { RegisterComponent } from './../register/register.component';
import { MockAuthService } from './../../../mock/mockAuth.service';
import { AuthService } from './../../../services/auth/auth.service';
import { HttpClient } from '@angular/common/http';
import { MockProjectService } from './../../../mock/mockProject.service';
import { MustMatchDirective } from './../../../directive/must-match.directive';
import { FormsModule } from '@angular/forms';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { SignupComponent } from './signup.component';
import { RouterTestingModule } from '@angular/router/testing';
import { Router } from '@angular/router';

describe('SignupComponent', () =&gt; {
  let component: SignupComponent;
  let fixture: ComponentFixture&lt;SignupComponent&gt;;

  let service:MockAuthService;

  let mockRouter 
  beforeEach(async(() =&gt; {
    mockRouter = { navigate: jasmine.createSpy('navigate') };
    TestBed.configureTestingModule({
      declarations: [ RegisterComponent, SignupComponent, MustMatchDirective],
      imports: [

        RouterTestingModule.withRoutes([
          { path: 'client/register', component: RegisterComponent }
      ]),
        FormsModule

    ],
    providers: [
      {
        provide: AuthService,
        useClass: MockAuthService
      },
      { provide: Router, useValue: mockRouter},
    ]
    })
    .compileComponents();
  }));

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

    service = TestBed.get(AuthService);

    fixture.detectChanges();
  });

  it('should navigate to register pgae when server return success message', () =&gt; {

    component.onSubmit();

    expect(mockRouter.navigate).toHaveBeenCalledWith(['/client/register']); 

  })


});
</code></pre>

<p><strong>Signup.component.ts</strong></p>

<pre><code>import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { AuthService } from './../../../services/auth/auth.service';


@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.scss']
})
export class SignupComponent implements OnInit {

  model: any = {};

  constructor(public router: Router, private cookieService: CookieService, private authService: AuthService) { }

  ngOnInit(): void { }

  onSubmit() {

    this.authService.signup(this.model).subscribe((response)=&gt;{ 
      this.cookieService.set( 'token', response['token'],1 );
      console.log(response)

      this.router.navigate['/client/register'];
     })

  }

}

</code></pre>
",https://stackoverflow.com/questions/61430363/error-expected-spy-navigate-to-have-been-called-with-client-register,"['angular', 'typescript', 'unit-testing']",1263,True,0,1
Flutter driver: cant find element (text) on the screen,"<p>The element I need to find is situated (in the child element):</p>
<pre><code> static Widget _buildProjectCategoryWidget(BuildContext context, String name) {
final themeData = Theme.of(context);
final primaryTextTheme = themeData.primaryTextTheme;
return Container(
  padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 5.0),
  decoration: BoxDecoration(borderRadius: BorderRadius.circular(13.0), color: FlAppStyles.altButtonColor),
  child: Text(name, style: primaryTextTheme.textSmall),
);
</code></pre>
<p>I tried to find the child element with this, but I have DriverError: Failed to fulfill Tap due to remote error:</p>
<pre><code>SerializableFinder message = find.text(&quot;mytext&quot;);
    await driver.waitFor(message);
    expect(await driver.getText(message), &quot;mytext&quot;); await driver.tap(buttonChangeProfession);
    
</code></pre>
<p>Im a beginner to flutter integration testing, dont know what is wrong, please help. I also tried adding a key and find element by it, but the point is I need to find the text of that element.</p>
",https://stackoverflow.com/questions/65331016/flutter-driver-cant-find-element-text-on-the-screen,"['flutter', 'testing', 'integration', 'flutter-test', 'flutterdriver']",1251,True,0,1
Testing synchronized method/blocks in spring,"<p>I have the following method:</p>

<pre><code>@Transactional
@Override
public Ticket buyTicketFor(String user) {
    Ticket ticket = null;

    synchronized (MUTEX) {
        List&lt;Ticket&gt; availableTickets = ticketRepo.findAllTickets();
        Collections.shuffle(availableTickets);
        ticket = availableTickets.get(0);
    }

    return ticket;
}
</code></pre>

<p>I want to create a test that allows me to test two users getting two tickets, but they must not access the DB at the same time. How can i create a test to allow me to do this. I wanted to use mockito and junit 5, but im thinking that it will only be possible using integration testing, where i spin up an actual server and DB.</p>
",https://stackoverflow.com/questions/60779126/testing-synchronized-method-blocks-in-spring,"['spring-boot', 'mockito', 'junit5']",257,False,1,0
HttpClient not sending post data to NancyFX endpoint,"<p>I am doing some integration testing of my web API that uses NancyFX end points. I have the xUnit test create a test server for the integration test</p>
<pre><code> private readonly TestServer _server;
    private readonly HttpClient _client;

    public EventsModule_Int_Tester()
    {
        //Server setup
        _server = new TestServer(new WebHostBuilder()
      .UseStartup&lt;Startup&gt;());
        _server.AllowSynchronousIO = true;//Needs to be overriden in net core 3.1
        _client = _server.CreateClient();
    }
</code></pre>
<p>Inside a Test Method I tried the following</p>
<pre><code>   [Fact]
    public async Task EventTest()
    {
        // Arrange
        HttpResponseMessage expectedRespone = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
        var data = _server.Services.GetService(typeof(GenijalnoContext)) as GenijalnoContext;

        //Get come random data from the DBcontext
        Random r = new Random();
        List&lt;Resident&gt; residents = data.Residents.ToList();
        Resident random_residnet = residents[r.Next(residents.Count)];

        List&lt;Apartment&gt; apartments = data.Apartments.ToList();
        Apartment random_Apartment = apartments[r.Next(apartments.Count)];



        EventModel model = new EventModel()
        {
            ResidentId = random_residnet.Id,
            ApartmentNumber = random_Apartment.Id

        };

        //Doesnt work
        IList&lt;KeyValuePair&lt;string, string&gt;&gt; nameValueCollection = new List&lt;KeyValuePair&lt;string, string&gt;&gt; {
        { new KeyValuePair&lt;string, string&gt;(&quot;ResidentId&quot;, model.ResidentId.ToString()) },
        { new KeyValuePair&lt;string, string&gt;(&quot;ApartmentNumber&quot;, model.ApartmentNumber.ToString())}
        };

        var result = await _client.PostAsync(&quot;/Events/ResidentEnter&quot;, new FormUrlEncodedContent(nameValueCollection));



        //Also Doesnt work 
        string json = JsonConvert.SerializeObject(model, Formatting.Indented);
        var httpContent = new StringContent(json, Encoding.UTF8, &quot;application/json&quot;);
        var response = await _client.PostAsync(&quot;/Events/ResidentEnter&quot;, httpContent);

        //PostAsJsonAsync also doesnt work 

        // Assert
        Assert.Equal(response.StatusCode, expectedRespone.StatusCode);
    }
</code></pre>
<p>The NancyFX module does trigger the endpoint and receives the request but without the body</p>
<p><a href=""https://i.stack.imgur.com/BWB3R.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/BWB3R.png"" alt=""Img1"" /></a></p>
<p>What am I doing wrong? Note that the NancyFX endpoint has no issue transforming a Postman call into a valid model.</p>
<p>The NancyFX endpoint
<a href=""https://i.stack.imgur.com/lQSGw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/lQSGw.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/63727193/httpclient-not-sending-post-data-to-nancyfx-endpoint,"['api', 'asp.net-core', 'data-binding', 'httpclient', 'nancy']",67,True,0,1
"React testing library, firebase, mocked functions","<p>I started studying integration testing and I am struggling with mocking.
I have a signup form that onSubmit calls firebase.auth.createUserWithEmailAndPassword, after that it initializes a document with the returned user uid and initialize it with default values.</p>
<p>I managed to check if createCserWithEmailAndPassword is correctly called but when I try to check if the collection set has been called I receive as error:</p>
<pre class=""lang-js prettyprint-override""><code>    expect(received).toHaveBeenCalled()

    Matcher error: received value must be a mock or spy function

    Received has value: undefined
</code></pre>
<p>I am struggling here.</p>
<p>Here is my test implementation:</p>
<pre class=""lang-js prettyprint-override""><code>import React from &quot;react&quot;;
import &quot;@testing-library/jest-dom&quot;;
import { ThemeProvider } from &quot;styled-components&quot;;
import { defaultTheme } from &quot;../../styles&quot;;
import { createMemoryHistory } from &quot;history&quot;;
import { Router, Switch, Route } from &quot;react-router-dom&quot;;
import { render, fireEvent, wait } from &quot;@testing-library/react&quot;;
import { SignUp } from &quot;../../sections&quot;;
import { User } from &quot;../../types&quot;;
import { auth, firestore } from &quot;../../lib/api/firebase&quot;;
jest.mock(&quot;../../lib/api/firebase&quot;, () =&gt; {
  return {
    auth: {
      createUserWithEmailAndPassword: jest.fn(() =&gt; {
        return {
          user: {
            uid: &quot;fakeuid&quot;,
          },
        };
      }),
      signOut: jest.fn(),
    },
    firestore: {
      collection: jest.fn(() =&gt; ({
        doc: jest.fn(() =&gt; ({
          collection: jest.fn(() =&gt; ({
            add: jest.fn(),
          })),
          set: jest.fn(),
        })),
      })),
    },
  };
});

const defaultUser: User = {
  isActive: false,
  accountName: &quot;No balance&quot;,
  startingBalance: 0.0,
  monthlyBudget: 0.0,
};

const history = createMemoryHistory({ initialEntries: [&quot;/signup&quot;] });
const renderWithRouter = () =&gt;
  render(
    &lt;ThemeProvider theme={defaultTheme}&gt;
      &lt;Router history={history}&gt;
        &lt;Switch&gt;
          &lt;Route exact path=&quot;/signup&quot;&gt;
            &lt;SignUp /&gt;
          &lt;/Route&gt;
          &lt;Route exact path=&quot;/&quot;&gt;
            &lt;div data-testid=&quot;GenericComponent&quot;&gt;&lt;/div&gt;
          &lt;/Route&gt;
        &lt;/Switch&gt;
      &lt;/Router&gt;
    &lt;/ThemeProvider&gt;
  );

describe(&quot;&lt;SignUp/&gt;&quot;, () =&gt; {
  it(&quot;correctly renders the signup form&quot;, () =&gt; {
    const { getByTestId } = renderWithRouter();
    const form = getByTestId(&quot;SignupForm&quot;);
    expect(form).toBeInTheDocument();
  });
  it(&quot;correctly renders the signup form&quot;, () =&gt; {
    const { getByTestId } = renderWithRouter();
    const form = getByTestId(&quot;SignupForm&quot;);
    expect(form).toBeInTheDocument();
  });

  it(&quot;let user signup with valid credentials&quot;, async () =&gt; {
    const { getByPlaceholderText, getByTestId } = renderWithRouter();
    const emailField = getByPlaceholderText(&quot;yourname@company.com&quot;);
    const passwordField = getByPlaceholderText(&quot;Password&quot;);
    const confirmPasswordField = getByPlaceholderText(&quot;Confirm Password&quot;);
    const submitButton = getByTestId(&quot;Button&quot;);

    fireEvent.change(emailField, {
      target: { value: &quot;test@test.com&quot; },
    });

    fireEvent.change(passwordField, { target: { value: &quot;Lampone01!&quot; } });
    fireEvent.change(confirmPasswordField, {
      target: { value: &quot;Lampone01!&quot; },
    });
    fireEvent.click(submitButton);

    expect(submitButton).not.toBeDisabled();

    await wait(() =&gt; {
      expect(auth.createUserWithEmailAndPassword).toHaveBeenCalled();
      expect(
        firestore.collection(&quot;users&quot;).doc(&quot;fakeUid&quot;).set(defaultUser)
      ).toHaveBeenCalled();
      expect(history.location.pathname).toBe(&quot;/dashboard&quot;);
    });
  });
});

</code></pre>
<p>What am I doing wrong?
Thanks guys.</p>
",https://stackoverflow.com/questions/63881883/react-testing-library-firebase-mocked-functions,"['reactjs', 'firebase', 'testing', 'jestjs', 'react-testing-library']",350,False,3,0
Spring Integration Testing Oracle Native SQL,"<p>I have a legacy application that has recently been ported from Struts to Spring MVC. The data layer is written with native Oracle SQL. I'd like to introduce some integration testing but would like to avoid using an actual Oracle database for obvious reasons. Is there an in-memory DB that can deal with Oracle native SQL? Is this just a dream? Am I just going to end up with Oracle XE in a VM?</p>
",https://stackoverflow.com/questions/60352905/spring-integration-testing-oracle-native-sql,"['spring', 'oracle', 'testing', 'integration', 'in-memory-database']",456,True,0,2
"Integration testing for spring cloud stream, how to ensure application resources are not used","<p>I'm trying to do some integration testing for my cloud streaming application. One of the main issues I'm observing so far is that the TestChannelBinderConfiguration keeps picking up the configuration specified in <code>src/main/java/resources/application.yml</code> instead of keeping it as blank (since there is no config file in <code>/src/test/resources/</code>).</p>
<p>If I delete the <code>application.yml</code> file or remove all spring-cloud-stream related configuration, the test passes. How can I ensure that the TestChannelBinderConfiguration does not pick up <code>application.yml</code> file.</p>
<pre><code>  @Test
  public void echoTransformTest() {
    try (ConfigurableApplicationContext context =
        new SpringApplicationBuilder(
              TestChannelBinderConfiguration.getCompleteConfiguration(DataflowApplication.class))
            .properties(new Properties())
            .run(&quot;--spring.cloud.function.definition=echo&quot;)) {
      InputDestination source = context.getBean(InputDestination.class);
      OutputDestination target = context.getBean(OutputDestination.class);

      GenericMessage&lt;byte[]&gt; inputMessage = new GenericMessage&lt;&gt;(&quot;hello&quot;.getBytes());

      source.send(inputMessage);
      assertThat(target.receive().getPayload()).isEqualTo(&quot;hello&quot;.getBytes());
    }
  }
</code></pre>
",https://stackoverflow.com/questions/64886688/integration-testing-for-spring-cloud-stream-how-to-ensure-application-resources,"['spring-cloud', 'spring-cloud-stream', 'spring-boot-test', 'spring-cloud-stream-binder-kafka']",1192,True,0,1
In Docker.DotNet how do you build an image by specifying the directory of the Dockerfile?,"<p>I am trying to build an image and start a container, for the purposes of integration testing, in a C# xunit test. I currently have the code below, but can't find away to specify the path to the docker file. The client does have <code>Images.BuildImageFromDockerfileAsync</code> but that deals with unpacking TAR files.</p>

<pre><code>        using(var client = new DockerClientConfiguration(
            new Uri(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) 
                ? ""npipe://./pipe/docker_engine""
                : ""unix:/var/run/docker.sock"")).CreateClient())
        {
            await client
                .Images
                .CreateImageAsync(
                    new ImagesCreateParameters(),
                    new AuthConfig(),
                    new Progress&lt;JSONMessage&gt;());

        }
</code></pre>

<p>I want to do the equivalent of <code>docker build -t yyyy -f ./zzzzzz/Dockerfile .</code> using the Docker.DotNet api but I can't work out a way to do it. Any help would be kindly appreciated.</p>
",https://stackoverflow.com/questions/61856360/in-docker-dotnet-how-do-you-build-an-image-by-specifying-the-directory-of-the-do,"['c#', 'docker', '.net-core']",1007,True,2,1
java.lang.NoSuchMethodError: org.springframework.util.Assert.isTrue(ZLjava/util/function/Supplier;)V,"<p>I have pure old legacy spring app (non spring-boot). I am trying to create some integration tests.<br> First of all, how can I setup application for integration testing when there is no main class like <code>@SpringBootApplcation</code> type?</p>
<p>The annotation <code>@ExtendWith(SpringExtension.class)</code> gives an exception like:</p>
<pre><code>java.lang.NoSuchMethodError: org.springframework.util.Assert.isTrue(ZLjava/util/function/Supplier;)V
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.processContextConfiguration(AbstractDelegatingSmartContextLoader.java:153)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:360)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:312)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:265)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:108)
    at org.springframework.test.context.TestContextManager.&lt;init&gt;(TestContextManager.java:137)
    at org.springframework.test.context.TestContextManager.&lt;init&gt;(TestContextManager.java:122)
    at org.junit.jupiter.engine.execution.ExtensionValuesStore.lambda$getOrComputeIfAbsent$0(ExtensionValuesStore.java:81)
    at org.junit.jupiter.engine.execution.ExtensionValuesStore$MemoizingSupplier.get(ExtensionValuesStore.java:182)
    at org.junit.jupiter.engine.execution.ExtensionValuesStore.getOrComputeIfAbsent(ExtensionValuesStore.java:84)
    at org.junit.jupiter.engine.execution.ExtensionValuesStore.getOrComputeIfAbsent(ExtensionValuesStore.java:88)
    at org.junit.jupiter.engine.execution.NamespaceAwareStore.getOrComputeIfAbsent(NamespaceAwareStore.java:61)
    at org.springframework.test.context.junit.jupiter.SpringExtension.getTestContextManager(SpringExtension.java:213)
    at org.springframework.test.context.junit.jupiter.SpringExtension.beforeAll(SpringExtension.java:77)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeBeforeAllCallbacks$7(ClassBasedTestDescriptor.java:353)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeBeforeAllCallbacks(ClassBasedTestDescriptor.java:353)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:187)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:77)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:132)
    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:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    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: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:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    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:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
    Suppressed: java.lang.NoSuchMethodError: org.springframework.util.Assert.isTrue(ZLjava/util/function/Supplier;)V
        at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.processContextConfiguration(AbstractDelegatingSmartContextLoader.java:153)
        at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:360)
        at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:312)
        at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:265)
        at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:108)
        at org.springframework.test.context.TestContextManager.&lt;init&gt;(TestContextManager.java:137)
        at org.springframework.test.context.TestContextManager.&lt;init&gt;(TestContextManager.java:122)
        at org.junit.jupiter.engine.execution.ExtensionValuesStore.lambda$getOrComputeIfAbsent$0(ExtensionValuesStore.java:81)
        at org.junit.jupiter.engine.execution.ExtensionValuesStore$MemoizingSupplier.get(ExtensionValuesStore.java:182)
        at org.junit.jupiter.engine.execution.ExtensionValuesStore.remove(ExtensionValuesStore.java:98)
        at org.junit.jupiter.engine.execution.NamespaceAwareStore.remove(NamespaceAwareStore.java:73)
        at org.springframework.test.context.junit.jupiter.SpringExtension.afterAll(SpringExtension.java:89)
        at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeAfterAllCallbacks$13(ClassBasedTestDescriptor.java:419)
        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
        at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeAfterAllCallbacks$14(ClassBasedTestDescriptor.java:419)
        at java.util.ArrayList.forEach(ArrayList.java:1257)
        at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeAfterAllCallbacks(ClassBasedTestDescriptor.java:419)
        at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.after(ClassBasedTestDescriptor.java:211)
        at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.after(ClassBasedTestDescriptor.java:77)
        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:145)
        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:145)
        ... 29 more
</code></pre>
<p>I am trying to set up app by</p>
<pre><code>@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = { &quot;...&quot; })     
public class SQLTest { }
</code></pre>
<p>Application is using Spring 4.3.17.RELEASE, there is no embedded Tomcat. Can this error causes of dependency version mismatch? Since spring-test is of version 5.2.8.RELEASE.</p>
<p>pom.xml</p>
<pre><code>&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 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;groupId&gt;...&lt;/groupId&gt;
    &lt;artifactId&gt;...&lt;/artifactId&gt;
    &lt;version&gt;1.0.2&lt;/version&gt;
    &lt;packaging&gt;war&lt;/packaging&gt;
    &lt;name&gt;...&lt;/name&gt;
    &lt;description&gt;...&lt;/description&gt;

    &lt;properties&gt;
        &lt;jdk.level&gt;1.8&lt;/jdk.level&gt;
        &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
        &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt;
        &lt;spring.version&gt;4.3.17.RELEASE&lt;/spring.version&gt;
        &lt;maven.build.timestamp.format&gt;yyyy-MM-dd-HH:mm&lt;/maven.build.timestamp.format&gt;
        &lt;warfile&gt;...&lt;/warfile&gt;
        &lt;junit.jupiter.version&gt;5.5.0&lt;/junit.jupiter.version&gt;
        &lt;junit.commons.version&gt;1.5.2&lt;/junit.commons.version&gt;
        &lt;powermock.version&gt;1.6.6&lt;/powermock.version&gt;
    &lt;/properties&gt;

    &lt;dependencies&gt;
        
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-core&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-beans&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-web&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-aop&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-jms&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-ws&lt;/artifactId&gt;
            &lt;version&gt;1.3.3.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.ws&lt;/groupId&gt;
            &lt;artifactId&gt;spring-ws-security&lt;/artifactId&gt;
            &lt;version&gt;3.0.7.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.ws.security&lt;/groupId&gt;
            &lt;artifactId&gt;wss4j&lt;/artifactId&gt;
            &lt;version&gt;1.6.19&lt;/version&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter&lt;/artifactId&gt;
            &lt;version&gt;${junit.jupiter.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter-engine&lt;/artifactId&gt;
            &lt;version&gt;${junit.jupiter.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&gt;
            &lt;version&gt;${junit.jupiter.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
            &lt;version&gt;5.2.8.RELEASE&lt;/version&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-all&lt;/artifactId&gt;
            &lt;version&gt;1.10.19&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.powermock&lt;/groupId&gt;
            &lt;artifactId&gt;powermock-module-junit4&lt;/artifactId&gt;
            &lt;version&gt;${powermock.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.powermock&lt;/groupId&gt;
            &lt;artifactId&gt;powermock-api-mockito&lt;/artifactId&gt;
            &lt;version&gt;${powermock.version}&lt;/version&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;version&gt;1.4.1.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;profiles&gt;
         ...
    &lt;/profiles&gt;
    &lt;build&gt;
       ...
    &lt;/build&gt;
&lt;/project&gt;
</code></pre>
",https://stackoverflow.com/questions/64100472/java-lang-nosuchmethoderror-org-springframework-util-assert-istruezljava-util,"['java', 'spring', 'junit', 'integration-testing']",3881,False,2,0
Reactor&#39;s StepVerifier: assertion fails in nondeterministic way on various step,"<p>I want to use StepVerifier in integration testing save operations in Mongo repository.</p>
<p>I prepared a method for inserting multiple UserItems for further verification:</p>
<pre><code>Flux&lt;UserItems&gt; saveMultiple(int numberOfItems) {
    return Flux.range(0, numberOfItems)
            .flatMap { userItemsRepository.save(new UserItem(it)) }
}
</code></pre>
<p><code>userItemsRepository.save</code> returns Mono&lt;UserItem&gt;</p>
<p>I prepared a test method:</p>
<pre><code>def &quot;Should save all UserItems&quot;() {
    given:
    def numberOfItems = 3

    when:
    def saveResult = saveMultiple(numberOfItems)

    then:
    StepVerifier.create(saveResult)
            .expectNextMatches {it.itemNo == 0 }
            .expectNextMatches {it.itemNo == 1 }
            .expectNextMatches {it.itemNo == 2 }
            .expectComplete()
            .verify()
}
</code></pre>
<p>And I expect that next items will emerge in the order {0,1,2}. Unfortunately, the test fails because of <code>java.lang.AssertionError</code> in non deterministic way, on various step. I cannot figure out how to do it properly. It's my first approach to test Reactor flow. Anyone has an idea, how to handle such situations?</p>
",https://stackoverflow.com/questions/64927130/reactors-stepverifier-assertion-fails-in-nondeterministic-way-on-various-step,"['java', 'testing', 'integration-testing', 'project-reactor']",180,True,2,1
ASP.NET Core 3.1 - Programmatically invoke http request pipeline,"<p>This question had a similar situation but the guy ended up using <code>HttpClient</code> as a hack: <a href=""https://stackoverflow.com/questions/50407760/programmatically-invoking-the-asp-net-core-request-pipeline"">Programmatically invoking the ASP.NET Core request pipeline</a></p>
<p>Is there a way to trigger the http pipeline (simulate a full request) by providing the payload, headers, verb and url route programmatically WITHOUT using the <code>HttpClient</code>?</p>
<p>I also saw you could do something similar with the <code>TestServer</code> for integration testing but this feels like a hack as well for what I want</p>
<p><a href=""https://stackoverflow.com/questions/44010173/simulate-post-request-in-a-unit-test-using-asp-net-core"">Simulate POST request in a unit test using ASP.NET Core</a></p>
",https://stackoverflow.com/questions/62800902/asp-net-core-3-1-programmatically-invoke-http-request-pipeline,"['c#', 'asp.net-core', 'asp.net-web-api']",275,False,1,0
How to optimize Dockerfile for Oracle?,"<p>I would like my Dockerfile to create an image with Oracle and my database.
The image will be used for integration testing during the build.
So it should be small and fast.</p>
<p>The Dockerfile:</p>
<pre><code>FROM valspace/oracle:18.4.0-xe

# Environment variables required for this build (do NOT change)
# -------------------------------------------------------------
ENV ORACLE_BASE=/opt/oracle \
    ORACLE_HOME=/opt/oracle/product/18c/dbhomeXE \
    ORACLE_SID=XE \
    PATH=.:${JAVA_HOME}/bin:${PATH}:$HOME/bin:$ORACLE_HOME/bin

# download my.dmp
ARG USERNAME
ARG PASSWORD
RUN yum install curl
RUN curl -u &quot;$USERNAME:$PASSWORD&quot; https://myrepo/my.dmp -o /docker-entrypoint-initdb.d/my.dmp

RUN chmod a+rxw /docker-entrypoint-initdb.d/my.dmp

# copy initialization scripts
ADD init.sql /docker-entrypoint-initdb.d/
ADD script.sh /docker-entrypoint-initdb.d/
</code></pre>
<p>script.sh:</p>
<pre><code>impdp system/oracle DUMPFILE=/docker-entrypoint-initdb.d/my.dmp
</code></pre>
<p>init.sql:</p>
<pre><code>--  Creates:
--  tablespaces ...
--  users...

EXIT
</code></pre>
<p>Problems with the scripts:</p>
<ol>
<li>Files like.DMP, .SH, .SQL inside of the final image.</li>
<li>It creates the image that imports DMP file on every start-up. Instead, it should do it during the build-time.</li>
<li>Is it possible to run Oracle in a minimal configuration?</li>
</ol>
",https://stackoverflow.com/questions/65371301/how-to-optimize-dockerfile-for-oracle,"['oracle', 'docker']",69,False,0,0
JUnit End to End Integration Testing,"<p>I am doing an End To End integration testing with JUnit and Spring (not Boot). I would like to test from a POST request all the way to the db. Here is my test:</p>

<pre><code>@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy({
    @ContextConfiguration(classes = TestConfig.class),
    @ContextConfiguration(classes = OrderHdrController.class)
})
@ActiveProfiles(""Test"")
public class FilterActivityTest4 {

    MockMvc mockMvc;
    @Autowired
    private WebApplicationContext wac;
    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).dispatchOptions(true).build();
    }

    @Test
    public void testActivity() {

        OrderSearchDto orderSearchDto = new OrderSearchDto();
        OrderSearchPanelDto orderSearchPanelDto = new OrderSearchPanelDto();
        orderSearchPanelDto.setActivityTypes(Arrays.asList(""TAKEOVER"",""DELIVERY""));
        orderSearchDto.setOrderSearchPanelDto(orderSearchPanelDto);

        try {
            MvcResult result = this.mockMvc.perform(post(""/orders/getOrderList"")
                    .content(asJsonString(orderSearchDto))).andDo(MockMvcResultHandlers.print())
                    .andExpect(status().isOk())
                    .andReturn();
            String content = result.getResponse().getContentAsString();
            System.out.print(content);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static String asJsonString(final Object obj) {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            final String jsonContent = mapper.writeValueAsString(obj);
            return jsonContent;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }  
}
</code></pre>

<p>And here is my TestConfig.class:</p>

<pre><code>    @Autowired
    private OrderManager orderManager;

    @Bean
    public OrderManager OrderManager() {
        return orderManager;
    }
</code></pre>

<p>And in my OrderHdr controller class:</p>

<pre><code>@Controller
@RequestMapping(""/orders"")
public class OrderHdrController {
    @Autowired
    private OrderManager orderManager;

    @RequestMapping(value = ""/getOrderList"", method = RequestMethod.POST)
    @ResponseBody
    public Map&lt;String, Object&gt; getOrderTables(OrderSearchDto orderSearchDto) {
         ...
         orderHdrTables = orderManager.findAllOrders(orderSearchDto);
         ...
    }
}
</code></pre>

<p>But my orderManager object is null in my controller, causing a Null Pointer Exception when I run the test. </p>

<p>Question is: How to I instantiate the orderManager object? Is it by ""Autowired""?</p>

<p>Please help. Thanks.</p>
",https://stackoverflow.com/questions/59572437/junit-end-to-end-integration-testing,"['java', 'spring', 'junit']",517,False,0,2
Multi-module gradle project: Unable to make calls to other module methods,"<p><a href=""https://i.stack.imgur.com/YXWyC.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/YXWyC.png"" alt=""My Multi-ModuleProjectStructure looks like this""></a></p>

<p>My setting.gradle looks like this</p>

<pre><code>rootProject.name = 'MainProject'
include 'ModuleA'
include 'ModuleB'
include 'ModuleC'
</code></pre>

<p>MainProject build.gradle  looks like this</p>

<pre><code> plugins {
   ................
}

subprojects {
    group = 'com.example'
    version = '0.0.1-SNAPSHOT'

    apply plugin: ""java""

    apply plugin: 'java-library'

    repositories {
        mavenCentral()
        jcenter()       
    }

    configurations {
        compileOnly {
            extendsFrom annotationProcessor
        }
    }

    dependencies {
       ...........
    }

    dependencyManagement {
        imports {  
        .............
        }
    }

    compileJava {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }

    tasks.withType(JavaCompile) {
        options.encoding = 'UTF-8'
    }
}
</code></pre>

<p>ModuleA build.gradle is like</p>

<pre><code>dependencies {
    .............
    compile("":ModuleB"")
    compile("":ModuleC"")
}
</code></pre>

<p>ModuleB build.gradle</p>

<pre><code>dependencies {
    .............
}
</code></pre>

<p>Modulec build.gradle</p>

<pre><code>dependencies {
    .............
}
</code></pre>

<p>So ModuleA has dependency on ModuleB
My requirement is like in ModuleA test class , i want to use ModuleB class to create object and make a call to ModuleB methods. So as do integration testing.</p>

<p>Issue i am facing is like , unable to import classes of ModuleB and ModuleC in ModuleA and create object to call their methods.Even after doing project level clean build.</p>
",https://stackoverflow.com/questions/61687109/multi-module-gradle-project-unable-to-make-calls-to-other-module-methods,"['java', 'gradle', 'build.gradle']",224,False,0,0
I&#39;m getting &quot;Content type not set&quot; error from my Integration test on Spring Boot app,"<p>Im using integration tests in my small application. . Its simple CRUD. Everything is ok, except Save and Update mappings. tests give me &quot;Content type not set
java.lang.AssertionError: Content type not set&quot; error</p>
<p>This is controller class</p>
<pre><code>package com.ilkin.simpletodo.controller;

import com.ilkin.simpletodo.exception.generic.EntityNotFoundException;
import com.ilkin.simpletodo.models.TodoItem;
import com.ilkin.simpletodo.services.TodoItemService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.ilkin.simpletodo.constant.Constant.TODO_ITEM_URL;

@RestController
@RequestMapping(TODO_ITEM_URL)
@RequiredArgsConstructor
public class TodoController {

    private final TodoItemService itemService;

    @GetMapping()
    public List&lt;TodoItem&gt; findAll() {
        return itemService.getAllItems();
    }

    @GetMapping(&quot;{itemId}&quot;)
    public TodoItem findByItemId(
            @PathVariable(&quot;itemId&quot;) long id
    ) throws EntityNotFoundException {
        return itemService.getItemById(id);
    }

    @PostMapping
    public TodoItem saveItem(
            @RequestBody TodoItem todoItem
    ) {
        return itemService.saveItem(todoItem);
    }

    @PutMapping(&quot;{itemId}&quot;)
    public TodoItem updateItem(
            @PathVariable long itemId,
            @RequestBody TodoItem todoItem
    ) throws EntityNotFoundException {
        return itemService.updateItem(itemId, todoItem);
    }

    @DeleteMapping(&quot;{itemId}&quot;)
    public TodoItem deleteItem(
            @PathVariable(&quot;itemId&quot;) long id
    ) throws EntityNotFoundException {
        return itemService.deleteItemById(id);
    }

    @PostMapping(&quot;{itemId}&quot;)
    public TodoItem changeItemStatus(
            @PathVariable(&quot;itemId&quot;) long id
    ) throws EntityNotFoundException {
        return itemService.changeItemStatus(id);
    }
}

</code></pre>
<p>This is Integration Tests:</p>
<pre><code>package com.ilkin.simpletodo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ilkin.simpletodo.TestsConfiguration;
import com.ilkin.simpletodo.exception.generic.EntityNotFoundException;
import com.ilkin.simpletodo.models.TodoItem;
import com.ilkin.simpletodo.services.TodoItemService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.ilkin.simpletodo.constant.Constant.TODO_ITEM_URL;
import static com.ilkin.simpletodo.utils.Utils.getJsonString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;


public class TodoControllerTests extends TestsConfiguration {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    TodoItemService itemService;

    private TodoItem requestObject;
    private String requestBody;

    private TodoItem responseObject;
    private String responseBody;

    private List&lt;TodoItem&gt; responseObjectList;
    private String responseBodyList;

    @BeforeEach
    public void init() throws JsonProcessingException {

//        mockMvc = standaloneSetup(new TodoController(itemService)).build();

        requestObject = new TodoItem();
        requestObject.setDone(false);
        requestObject.setTaskName(&quot;task&quot;);
        requestObject.setCreatedTime(LocalDateTime.now());
        requestObject.setUpdateTime(LocalDateTime.now());

        requestBody = getJsonString(requestObject);

        responseObject = new TodoItem();
        responseObject.setItemId(requestObject.getItemId());
        responseObject.setUpdateTime(requestObject.getUpdateTime());
        responseObject.setCreatedTime(requestObject.getCreatedTime());
        responseObject.setTaskName(requestObject.getTaskName());
        responseObject.setDone(requestObject.isDone());
        responseObject.setItemId(1);

        responseBody = getJsonString(responseObject);

        responseObjectList = new ArrayList&lt;&gt;();
        responseObjectList.add(responseObject);

        responseBodyList = getJsonString(responseObjectList);
    }

    @Test
    @DisplayName(&quot;GET &quot; + TODO_ITEM_URL)
    public void find_all() throws Exception {

        when(itemService.getAllItems()).thenReturn(responseObjectList);

        mockMvc.perform(
                get(TODO_ITEM_URL)
                        .accept(MediaType.APPLICATION_JSON)
        )
                .andExpect(status().isOk())
                .andExpect(content().json(responseBodyList));

        verify(itemService).getAllItems();
    }

    @Test
    @DisplayName(&quot;GET &quot; + TODO_ITEM_URL + &quot;/itemId&quot;)
    public void find_by_item_id_when_exist() throws Exception {

        when(itemService.getItemById(1)).thenReturn(responseObject);

        mockMvc.perform(
                get(TODO_ITEM_URL + &quot;/1&quot;)
                        .accept(MediaType.APPLICATION_JSON)
        )
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(content().json(responseBody));

        verify(itemService).getItemById(1);
    }

    @Test
    @DisplayName(&quot;GET &quot; + TODO_ITEM_URL + &quot;/&quot; + Long.MAX_VALUE)
    public void find_by_item_id_when_not_exist() throws Exception {

        when(itemService.getItemById(Long.MAX_VALUE)).thenThrow(EntityNotFoundException.class);

        mockMvc.perform(
                get(TODO_ITEM_URL + &quot;/&quot; + Long.MAX_VALUE)
                        .accept(MediaType.APPLICATION_JSON)
        )
                .andExpect(status().isNotFound());

        verify(itemService).getItemById(Long.MAX_VALUE);
    }

    @Test
    @DisplayName(&quot;POST &quot; + TODO_ITEM_URL)
    public void save_item() throws Exception {

        when(itemService.saveItem(responseObject)).thenReturn(responseObject);

        mockMvc.perform(
                post(TODO_ITEM_URL)
                        .accept(MediaType.APPLICATION_JSON)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(requestBody)
        )
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(content().json(responseBody));

        verify(itemService).saveItem(responseObject);
    }

    @Test
    @DisplayName(&quot;PUT &quot; + TODO_ITEM_URL + &quot;/itemId&quot;)
    public void update_item_when_id_exist() throws Exception {

        when(itemService.updateItem(1, requestObject)).thenReturn(responseObject);

        mockMvc.perform(
                put(TODO_ITEM_URL + &quot;/1&quot;)
                        .accept(MediaType.APPLICATION_JSON)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(requestBody)
        )
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(content().json(responseBody));

        verify(itemService).updateItem(1, requestObject);
    }

    @Test
    @DisplayName(&quot;PUT &quot; + TODO_ITEM_URL + &quot;/&quot; + Long.MAX_VALUE)
    public void update_item_when_id_not_exist() throws Exception {

        when(itemService.updateItem(Long.MAX_VALUE, requestObject)).thenThrow(EntityNotFoundException.class);

        mockMvc.perform(
                put(TODO_ITEM_URL + &quot;/&quot; + Long.MAX_VALUE)
                        .accept(MediaType.APPLICATION_JSON)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(requestBody)
        )
                .andExpect(status().isNotFound());

        verify(itemService).updateItem(Long.MAX_VALUE, requestObject);
    }

    @Test
    @DisplayName(&quot;DELETE &quot; + TODO_ITEM_URL + &quot;/1&quot;)
    public void delete_item_when_id_exist() throws Exception {

        when(itemService.deleteItemById(1)).thenReturn(responseObject);

        mockMvc.perform(
                delete(TODO_ITEM_URL + &quot;/1&quot;)
                        .accept(MediaType.APPLICATION_JSON)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(requestBody)
        )
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(content().json(responseBody));

        verify(itemService).deleteItemById(1);
    }

    @Test
    @DisplayName(&quot;DELETE &quot; + TODO_ITEM_URL + &quot;/&quot; + Long.MAX_VALUE)
    public void delete_item_when_id_not_exist() throws Exception {

        when(itemService.deleteItemById(Long.MAX_VALUE)).thenThrow(EntityNotFoundException.class);

        mockMvc.perform(
                delete(TODO_ITEM_URL + &quot;/&quot; + Long.MAX_VALUE)
                        .accept(MediaType.APPLICATION_JSON)
                        .content(requestBody)
        )
                .andExpect(status().isNotFound());

        verify(itemService).deleteItemById(Long.MAX_VALUE);
    }

    @Test
    @DisplayName(&quot;POST &quot; + TODO_ITEM_URL + &quot;/1&quot;)
    public void change_item_status_when_id_exist() throws Exception {

        when(itemService.changeItemStatus(1)).thenReturn(responseObject);

        mockMvc.perform(
                post(TODO_ITEM_URL + &quot;/1&quot;)
                        .accept(MediaType.APPLICATION_JSON)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(requestBody)
        )
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(content().json(responseBody));

        verify(itemService).changeItemStatus(1);
    }

    @Test
    @DisplayName(&quot;POST &quot; + TODO_ITEM_URL + &quot;/&quot; + Long.MAX_VALUE)
    public void change_item_status_when_id_not_exist() throws Exception {

        when(itemService.changeItemStatus(Long.MAX_VALUE)).thenThrow(EntityNotFoundException.class);

        mockMvc.perform(
                post(TODO_ITEM_URL + &quot;/&quot; + Long.MAX_VALUE)
                        .accept(MediaType.APPLICATION_JSON)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(requestBody)
        )
                .andExpect(status().isNotFound());

        verify(itemService).changeItemStatus(Long.MAX_VALUE);
    }
}

</code></pre>
<p>When I start Integration testing Im getting 3 failed test(save_item(), update_item_when_id_exist() and update_item_when_id_not_exist()). I thought it was due to my repo item.save(). However nothing came out from debuging. I already tried solutions like adding - @PostMapping(produces = {MediaType.APPLICATION_JSON_VALUE} )
didn't work for me.</p>
",https://stackoverflow.com/questions/64676042/im-getting-content-type-not-set-error-from-my-integration-test-on-spring-boot,"['java', 'spring', 'spring-boot', 'junit', 'integration-testing']",1583,True,0,2
API documentation for API Gateway with Lambda proxy integration,"<p>I defined a SAM app with few Lambdas behind an API Gateway&quot;</p>
<pre><code>  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Ref EnvType
      Auth:
        DefaultAuthorizer: LambdaTokenAuthorizer
        Authorizers:
          LambdaTokenAuthorizer:
            FunctionArn: !GetAtt AuthorizerLambda.Arn
  MyFunction:
    Type: 'AWS::Serverless::Function'
...
      Events:
        MyEvent:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: &quot;/MyResource/{proxy+}&quot;
            Method: post
</code></pre>
<p>Obviously, API Gateway does not know much about the proxied resource such as:</p>
<ul>
<li>proxied path(s)</li>
<li>request model</li>
<li>response model</li>
</ul>
<p>Documentation generated from API Gateway stage reflects this:</p>
<pre><code>swagger: &quot;2.0&quot;
info:
  version: &quot;1.0&quot;
  title: &quot;xxx-dev&quot;
host: &quot;xxx.execute-api.us-west-2.amazonaws.com&quot;
basePath: &quot;/dev&quot;
schemes:
- &quot;https&quot;
paths:
  /MyResource/{proxy+}:
    post:
      responses: {}
      security:
      - LambdaTokenAuthorizer: []
securityDefinitions:
  LambdaTokenAuthorizer:
    type: &quot;apiKey&quot;
    name: &quot;Authorization&quot;
    in: &quot;header&quot;
    x-amazon-apigateway-authtype: &quot;custom&quot;
</code></pre>
<p>Is there a way to feed API Gateway with missing bits (proxied paths, response models, request models)?
Ultimately i need a document that is good enough to generate the client code / allow some integration testing.
Similar question here -&gt; <a href=""https://stackoverflow.com/questions/56040691/aws-lambda-proxy-swagger-template-integration/65508374#65508374"">Aws lambda proxy Swagger template integration</a></p>
",https://stackoverflow.com/questions/65509291/api-documentation-for-api-gateway-with-lambda-proxy-integration,"['amazon-web-services', 'swagger', 'aws-api-gateway', 'openapi', 'sam']",216,False,2,0
Express/Passport not setting cookie for supertest agent,"<p>I’m trying to do some integration testing for my Express server with supertest and mocha. Users authenticate via Passport LocalStrategy and I’m setting a session cookie with cookie-session. All works fine in the browser and Postman. However I cannot make it work in combination with supertest: Express response does not contain the cookie on the signup/login routes, thus I cannot make any authenticated requests.</p>

<p>On the Express server <code>cors</code> middleware is in place and cookies are <code>sameSite</code> and <code>httpOnly</code>. Any idea what might be wrong? </p>
",https://stackoverflow.com/questions/61665519/express-passport-not-setting-cookie-for-supertest-agent,"['node.js', 'express', 'testing', 'cookies', 'supertest']",870,True,2,1
initialize database for testing purpose on Spring Data R2DBC,"<p>In a non-test environment, I can set up the bean to initialize the database with the <code>schema.sql</code> like this</p>
<pre><code>    @Bean
    ConnectionFactoryInitializer initializer(@Qualifier(&quot;connectionFactory&quot;) ConnectionFactory connectionFactory) {

        ConnectionFactoryInitializer initializer = new ConnectionFactoryInitializer();
        initializer.setConnectionFactory(connectionFactory);
        initializer.setDatabasePopulator(new ResourceDatabasePopulator(new ClassPathResource(&quot;schema.sql&quot;)));

        return initializer;
    }
</code></pre>
<p>the problem is, I want to do something like this but for testing purpose. I'm trying to do some kind of integration testing with the database so I want the schema to be inserted to a dummy database too.</p>
<p>I've tried using this annotation but it still won't execute</p>
<pre><code>@Sql(scripts = &quot;classpath:schema.sql&quot;, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
</code></pre>
<p>I've created a separate <code>application-test.properties</code> on my test resources folder containg this properties values</p>
<pre><code>spring.r2dbc.url=r2dbc:postgresql://localhost:5432/test
spring.r2dbc.username=postgres

logging.level.org.springframework.r2dbc=DEBUG
</code></pre>
<p>and have added <code>@ActiveProfiles(profiles = &quot;test&quot;)</code> annotation too.</p>
",https://stackoverflow.com/questions/65351356/initialize-database-for-testing-purpose-on-spring-data-r2dbc,"['java', 'spring', 'spring-data-r2dbc', 'r2dbc', 'r2dbc-postgresql']",4304,True,2,3
Best way to setup MSTest for REST service with cookie-authentication?,"<p>Background: I am using ASP.NET Core 3.1, and integration testing a REST service that requires cookie authentication. </p>

<p>Candidate solution below.</p>

<p>Note:</p>

<ul>
<li>The reason I use a vanilla Host instead of TestServer is because of the cookie requirement. When using TestServer, it provides an HttpClient for you, but the client does not pass cookies back to the server.</li>
<li>I also attempted to use a custom HttpClient with TestServer. That consistently generated a System.Net.Sockets.SocketException (No connection could be made because the target machine actively refused it.)</li>
</ul>

<pre><code>using Microsoft.Extensions.Hosting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using WebApi; // Contains my Startup.cs

namespace WebApiTest
{
    [TestClass]
    public class UserTest
    {
        static IHost HttpHost;

        [ClassInitialize]
        public static async Task ClassStartup(TestContext context)
        {
            HttpHost = Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(webBuilder =&gt;
                {
                    webBuilder.UseStartup&lt;Startup&gt;();
                })
                .Build();
            await HttpHost.StartAsync();
        }

        [ClassCleanup]
        public static async Task ClassCleanup()
        {
            await HttpHost.StopAsync();
        }

        public static HttpContent GetHttpContent(object content)
        {
            HttpContent httpContent = null;

            if (content != null)
            {
                httpContent = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(content, content.GetType()));
                httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(""application/json"");
            }

            return httpContent;
        }

        public static HttpClient GetCookieHttpClient()
        {
            SocketsHttpHandler handler = new SocketsHttpHandler
            {
                AllowAutoRedirect = false,
                CookieContainer = new CookieContainer(),
                UseCookies = true
            };

            return new HttpClient(handler);
        }

        [TestMethod]
        public async Task GetUserData_ReturnsSuccess()
        {
            using (HttpClient client = GetCookieHttpClient())
            {
                var credentials = new
                {
                    Email = ""test@test.com"",
                    Password = ""password123"",
                };

                HttpResponseMessage response = await client.PostAsync(""http://localhost:5000/api/auth/login"", GetHttpContent(credentials));
                response = await client.GetAsync(String.Format(""http://localhost:5000/api/users/{0}"", credentials.Email));
                Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
            }
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/61312890/best-way-to-setup-mstest-for-rest-service-with-cookie-authentication,"['c#', 'asp.net-core', 'integration-testing', 'mstest']",1054,True,0,2
Junit Integration Test issue for testing create and exception functionality,"<p>I have been going through many articles on Integration Testing.As per my understanding we have to carry out test without using mocks. I need to test that if lobby is already present, it should throw the exception. I am creating lobby which in turn interacts with user service layer. Below integration test is failing with Null Pointer exception at userService.createUser(testUser) in setupLobby method.</p>

<p>What am I doing wrong with this Integration testing? </p>

<p>Integration Test Code -</p>

<pre><code>public class LobbyServiceIntegrationTest {

LobbyService lobbyService;
UserService userService;

private User testUser;
private Lobby lobbyTest;
private Long lobbyId;
private List&lt;User&gt; userList = new ArrayList&lt;&gt;();

@BeforeEach
public void setupLobby(){

    testUser = new User();
    testUser.setName(""testName"");
    testUser.setUsername(""testUsername"");

    testUser = userService.createUser(testUser);

    lobbyTest = new Lobby();
    lobbyTest.setName(""testLobby"");
    lobbyTest.setHostPlayerId(testUser.getId());

    lobbyId = lobbyService.createLobby(lobbyTest);


}

@Test
public void createdLobbyExist_Exception(){

    Lobby newLobby = new Lobby();
    newLobby.setName(""testLobby"");
    newLobby.setHostPlayerId(1L);

    assertThrows(LobbyException.class, ()-&gt;lobbyService.createLobby(newLobby));
}
</code></pre>

<p>}</p>

<p>Functionality which I want to test </p>

<pre><code>    public Long createLobby(Lobby newLobby){

    checkIfLobbyExist(newLobby);
    newLobby.getPlayerIds().add(newLobby.getHostPlayerId());

    newLobby = lobbyRepository.save(newLobby);

    User user = userRepository.getOne(newLobby.getHostPlayerId());
    user.setLobbyId(newLobby.getId());
    userRepository.save(user);

    return newLobby.getId();

}
</code></pre>

<p>And create user  </p>

<pre><code>    public User createUser(User newUser) {

    checkIfUserExists(newUser);

    newUser.setToken(UUID.randomUUID().toString());
    newUser.setStatus(UserStatus.OFFLINE);
    newUser.setCreationDate(new java.sql.Date(Calendar.getInstance().getTimeInMillis()));


    // saves the given entity but data is only persisted in the database once flush() is called
    newUser = userRepository.save(newUser);
    userRepository.flush();

    log.debug(""Created Information for User: {}"", newUser);
    return newUser;
}
</code></pre>
",https://stackoverflow.com/questions/61550590/junit-integration-test-issue-for-testing-create-and-exception-functionality,"['java', 'testing', 'junit', 'integration-testing']",199,True,0,1
Framework for handling HTTP responses in C#,"<p>The project is a C# desktop application that interacts with a webpage.</p>
<p>The last time I did anything like this, I used WatiN and HTMLAgilityPack. But WatiN isn't very elegant as it opens a browser window to interact with the website. It's more designed for Integration Testing, still it got the job done.</p>
<p>This time I'm looking at AngleSharp to parse the HTML, but I still need to write code that logs into the website, presses a couple of buttons and does some POSTS.</p>
<p>Are there any frameworks I can use to make this straightforward?</p>
",https://stackoverflow.com/questions/62659008/framework-for-handling-http-responses-in-c,"['c#', 'httpresponse', 'anglesharp']",167,True,2,2
Best way to manage train/test/val splits on AzureML,"<p>I'm currently using AzureML with pretty complex workflows involving large datasets etc. and I'm wondering what is the best way to manage the splitting resulting of preprocessing steps. All my projects are built as pipelines fed by registered Datasets. I want to be able to track the splitting in order to easily retrieve, for example, test and validation sets for integration testing purposes.</p>
<p>What would be the best pattern to apply there ? Registering every intermediate set as different Dataset ? Directly retrieving the intermediate sets using the Run IDs ? ...</p>
<p>Thaanks</p>
",https://stackoverflow.com/questions/62538688/best-way-to-manage-train-test-val-splits-on-azureml,"['python', 'azure', 'azure-machine-learning-service']",193,True,2,2
"Gitlab CI, how to get a container host name, started with docker-maven-plugin","<p>I'm setting up an integration testing environment for my Spring Boot Java application. So I'm spinning off a PostgreSQL database using <code>docker-maven-plugin</code>, which my application is supposed to call into.</p>
<p>This setup works ok when running <code>mvn verify</code> on my local system, but on the GitLab CI runner, is failing, because the PostgreSQL hostname doesn't match anymore.</p>
<p>My question is, how can I get the hostname of the database container in the CI pipeline?</p>
<p>My plugin configuration looks something like this:</p>
<pre class=""lang-xml prettyprint-override""><code>&lt;plugin&gt;
    &lt;groupId&gt;io.fabric8&lt;/groupId&gt;
    &lt;artifactId&gt;docker-maven-plugin&lt;/artifactId&gt;
    &lt;version&gt;${docker.maven.plugin.version}&lt;/version&gt;
    &lt;executions&gt;
        &lt;execution&gt;
            &lt;id&gt;prepare-it-database&lt;/id&gt;
            &lt;phase&gt;pre-integration-test&lt;/phase&gt;
            &lt;goals&gt;
                &lt;goal&gt;start&lt;/goal&gt;
            &lt;/goals&gt;
            &lt;configuration&gt;
                &lt;images&gt;
                    &lt;image&gt;
                        &lt;name&gt;postgres:9.6.14&lt;/name&gt;
                        &lt;alias&gt;it-database&lt;/alias&gt;
                        &lt;run&gt;
                            &lt;ports&gt;
                                &lt;port&gt;it-database.port:5432&lt;/port&gt;
                            &lt;/ports&gt;
                            &lt;wait&gt;
                                &lt;log&gt;(?s)database system is ready to accept connections.*database system is ready to accept connections&lt;/log&gt;
                                &lt;time&gt;20000&lt;/time&gt;
                            &lt;/wait&gt;
                            &lt;log&gt;
                                &lt;prefix&gt;POSTGRESQL-TEST&lt;/prefix&gt;
                                &lt;date&gt;ISO8601&lt;/date&gt;
                                &lt;color&gt;blue&lt;/color&gt;
                             &lt;/log&gt;
                         &lt;/run&gt;
                     &lt;/image&gt;
                 &lt;/images&gt;
             &lt;/configuration&gt;
         &lt;/execution&gt;
         &lt;execution&gt;
             &lt;id&gt;remove-it-database&lt;/id&gt;
             &lt;phase&gt;post-integration-test&lt;/phase&gt;
             &lt;goals&gt;
                 &lt;goal&gt;stop&lt;/goal&gt;
             &lt;/goals&gt;
         &lt;/execution&gt;
     &lt;/executions&gt;
 &lt;/plugin&gt;
</code></pre>
<p>Eventually, I will have to pass that database hostname in my <code>application yaml</code>:</p>
<pre><code>spring:
  datasource:
    platform: postgresql
    url: jdbc:postgresql://&lt;db_host_name_here_once_i_get_it&gt;:${it-database.port}/postgres
    username: postgres
    password: postgres
    schema: classpath:schema-postgresql.sql
    data: classpath:data-postgresql.sql
    driver-class-name: org.postgresql.Driver
    initialization-mode: always
</code></pre>
",https://stackoverflow.com/questions/63161146/gitlab-ci-how-to-get-a-container-host-name-started-with-docker-maven-plugin,"['docker', 'gitlab-ci', 'gitlab-ci-runner', 'docker-maven-plugin']",299,False,2,0
Sprockets::Rails::Helper::AssetNotPrecompiled: application.css,"<p>I get the following error when running my rspec test on CircleCI or Heroku Integration testing. However, it does not appear when running locally.</p>
<pre><code>--- Caused by: ---

     # Sprockets::Rails::Helper::AssetNotPrecompiled:

     #   application.css
</code></pre>
<p>I tried adding:</p>
<p>I tried adding <code>config.assets.debug = false</code> to my test environment, but still fails on Heroku and CircleCI, but passes locally.</p>
<p>I found the following:</p>
<p><a href=""https://github.com/phfdonda/story-weavers/pull/2"" rel=""nofollow noreferrer"">https://github.com/phfdonda/story-weavers/pull/2</a></p>
<p><a href=""https://github.com/rmosolgo/graphiql-rails/issues/75"" rel=""nofollow noreferrer"">https://github.com/rmosolgo/graphiql-rails/issues/75</a></p>
<p><a href=""https://github.com/rails/sprockets/issues/633"" rel=""nofollow noreferrer"">https://github.com/rails/sprockets/issues/633</a></p>
<p><a href=""https://github.com/rails/sprockets/issues/690"" rel=""nofollow noreferrer"">https://github.com/rails/sprockets/issues/690</a></p>
<p>My manifest file is:</p>
<pre><code>//= link_tree ../images
//= link application.css
//= link application.js
</code></pre>
<p>adding a precompile in the test environment does not fix the issue..</p>
<pre><code> config.assets.precompile += ['application.js', 'application.css']
</code></pre>
",https://stackoverflow.com/questions/64069485/sprocketsrailshelperassetnotprecompiled-application-css,"['heroku', 'rspec', 'assets', 'circleci', 'ruby-on-rails-6']",3247,True,2,1
Make jenkins spawn agents on gke in different node pools,"<p>I have a jenkins and most jobs do some ansible work and need 300mb of ram tops with 50m cpu, but I'v got few massive integration testing jobs that take 14000m cpu(14vcpus) or more, i know there is there a way to have 2 node pools (one with small instances 4gb, and one with the massive 30vcpu machines), and if I had 2 microserwices I could make them use NodeSelector, but jenkins is one microserwice, can I make it somehow spawn different job agents in different node pools? </p>
",https://stackoverflow.com/questions/61906695/make-jenkins-spawn-agents-on-gke-in-different-node-pools,"['jenkins', 'kubernetes', 'google-cloud-platform', 'google-kubernetes-engine', 'kubernetes-helm']",230,True,2,1
java.lang.NoClassDefFoundError: org/apache/logging/log4j/core/Layout while running integration test using ESIntegTestCase,"<p>I am trying to set up integration testing for ElasticSearch in Java.</p>

<p>I extended <code>ESIntegTestCase</code> and tried running a dummy empty test.
I get this exception as a result of the test:</p>

<pre><code>java.lang.NoClassDefFoundError: org/apache/logging/log4j/core/Layout
    at java.base/java.lang.Class.getDeclaredMethods0(Native Method)
    at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3166)
    at java.base/java.lang.Class.getMethodsRecursive(Class.java:3307)
    at java.base/java.lang.Class.getMethod0(Class.java:3293)
    at java.base/java.lang.Class.getMethod(Class.java:2106)
    at org.apache.maven.surefire.util.ReflectionUtils.tryGetMethod(ReflectionUtils.java:60)
    at org.apache.maven.surefire.common.junit3.JUnit3TestChecker.isSuiteOnly(JUnit3TestChecker.java:65)
    at org.apache.maven.surefire.common.junit3.JUnit3TestChecker.isValidJUnit3Test(JUnit3TestChecker.java:60)
    at org.apache.maven.surefire.common.junit3.JUnit3TestChecker.accept(JUnit3TestChecker.java:55)
    at org.apache.maven.surefire.common.junit4.JUnit4TestChecker.accept(JUnit4TestChecker.java:53)
    at org.apache.maven.surefire.util.DefaultScanResult.applyFilter(DefaultScanResult.java:102)
    at org.apache.maven.surefire.junit4.JUnit4Provider.scanClassPath(JUnit4Provider.java:309)
    at org.apache.maven.surefire.junit4.JUnit4Provider.setTestsToRun(JUnit4Provider.java:189)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:132)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:379)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:340)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:125)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:413)
Caused by: java.lang.ClassNotFoundException: org.apache.logging.log4j.core.Layout
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 18 more
</code></pre>

<p>This happens only when I run any test or try to build module while the testing class extends any class from Elasticsearch Testing Framework in this case <code>ESIntegTestCase</code>.
If the testing class doesn't extend anything - tests run just fine.</p>

<p>Here's my POM:</p>

<pre><code>    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.elasticsearch&lt;/groupId&gt;
            &lt;artifactId&gt;elasticsearch&lt;/artifactId&gt;
            &lt;version&gt;6.4.1&lt;/version&gt;
            &lt;type&gt;jar&lt;/type&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.elasticsearch.client&lt;/groupId&gt;
            &lt;artifactId&gt;transport&lt;/artifactId&gt;
            &lt;version&gt;6.4.1&lt;/version&gt;                    
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.data&lt;/groupId&gt;
            &lt;artifactId&gt;spring-data-elasticsearch&lt;/artifactId&gt;
            &lt;version&gt;3.1.1.RELEASE&lt;/version&gt;            
            &lt;type&gt;jar&lt;/type&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.groupid&lt;/groupId&gt;
            &lt;artifactId&gt;myModule0&lt;/artifactId&gt;
            &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
            &lt;type&gt;jar&lt;/type&gt;
            &lt;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.springframework.data&lt;/groupId&gt;
                    &lt;artifactId&gt;spring-data-elasticsearch&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.groupid&lt;/groupId&gt;
            &lt;artifactId&gt;myModule1&lt;/artifactId&gt;
            &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
            &lt;type&gt;jar&lt;/type&gt;
            &lt;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.elasticsearch&lt;/groupId&gt;
                    &lt;artifactId&gt;elasticsearch&lt;/artifactId&gt;
                &lt;/exclusion&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.elasticsearch.client&lt;/groupId&gt;
                    &lt;artifactId&gt;transport&lt;/artifactId&gt;
                &lt;/exclusion&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.springframework.data&lt;/groupId&gt;
                    &lt;artifactId&gt;spring-data-elasticsearch&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.elasticsearch.test&lt;/groupId&gt;
            &lt;artifactId&gt;framework&lt;/artifactId&gt;
&lt;!--  tried different versions, nothing seem to resolve this--&gt;
            &lt;version&gt;7.6.1&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

    &lt;/dependencies&gt;
</code></pre>

<p>It also a child of a module, which following exclusions for spring-boot-starter-web:2.0.5.RELEASE:</p>

<pre><code>          &lt;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.elasticsearch&lt;/groupId&gt;
                    &lt;artifactId&gt;elasticsearch&lt;/artifactId&gt;
                &lt;/exclusion&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.elasticsearch.client&lt;/groupId&gt;
                    &lt;artifactId&gt;transport&lt;/artifactId&gt;
                &lt;/exclusion&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.springframework.data&lt;/groupId&gt;
                    &lt;artifactId&gt;spring-data-elasticsearch&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
</code></pre>

<p>What's the problem?</p>
",https://stackoverflow.com/questions/60763786/java-lang-noclassdeffounderror-org-apache-logging-log4j-core-layout-while-runni,"['java', 'elasticsearch', 'pom.xml', 'noclassdeffounderror']",6006,False,2,1
Newtonsoft.Json.JsonReaderException: Could not convert string to integer 2,"<p>i am currently at integration testing phase in my project and i ran into an error while trying to test an endpoint to see if my database returns some tasks.
my domain object looks like this:</p>
<pre><code>public class Task
    {
        public Guid Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }

        [Column(TypeName = &quot;decimal(18,2)&quot;)] 
        public decimal? InitialPrice { get; set; }
    }
</code></pre>
<p>My basic test code for an endpoint</p>
<pre><code>[Fact]
        public async Task Should_return_All_Tasks_with_ok_statusCode()
        {
            client.SetFakeBearerToken((object) token);
            
            var response = await client.GetAsync(&quot;/api/v1/tasks&quot;);

            response.StatusCode.Should().Be(HttpStatusCode.OK);
            var json = await response.Content.ReadAsStringAsync();
            var data = JsonConvert.DeserializeObject&lt;List&lt;Task&gt;&gt;(json);
            data.Count.Should().BeGreaterThan(0);
        }
</code></pre>
<p>When i run the test i get the error</p>
<pre><code>Newtonsoft.Json.JsonReaderException: Could not convert string to integer: 64fa643f-2d35-46e7-b3f8-31fa673d719b. Path '[0].id', line 1, position 45.
</code></pre>
<p>I have also tried using the ReadAsAsync&lt;List&gt;() method from the webapi.client package and i still get the same error.</p>
<p>an api call to the endpoint im trying to test would give:</p>
<pre><code>[
  {
    &quot;id&quot;: &quot;64fa643f-2d35-46e7-b3f8-31fa673d719b&quot;,
    &quot;title&quot;: &quot;Garden Trimming in Lagos Ajah&quot;,
    &quot;description&quot;: &quot;Please my garden needs trimmin, Im in lagos&quot;,
    &quot;initialPrice&quot;: 20.3
  }
]
</code></pre>
<p>I would appreciate the help</p>
",https://stackoverflow.com/questions/65414568/newtonsoft-json-jsonreaderexception-could-not-convert-string-to-integer-2,"['c#', 'asp.net-web-api', '.net-core', 'json.net']",1485,True,1,1
"Unit, Integration and Functional Testing","<p>I am working on Test Case and I would like to get clarity about which are the directories &amp; files that come under,</p>

<ol>
<li>Unit Testing.</li>
<li>Integration Testing.</li>
<li>Functional Testing.</li>
</ol>

<p>My application architecture is as follows,</p>

<ul>
<li>controllers (which controls the respective action by calling service file from services directory).</li>
<li>models (model for data tables).</li>
<li>routes (for routing).</li>
<li>services (a layer that communicates with model).</li>
<li>db (holds migration for the database).</li>
<li>index.js (which runs the server).</li>
</ul>

<p>Could anyone help me out by saying which directories &amp; files needs which type of testing (Unit, Integration, Functional)?</p>

<p>Thank you. </p>
",https://stackoverflow.com/questions/62230188/unit-integration-and-functional-testing,"['node.js', 'testing', 'mocha.js', 'chai', 'sinon']",81,True,0,1
How to pass a variable (ui object) in flutter/dart?,"<p>im a very newbie to flutter integration testing. For now I only know how to write basic sheets of finding elements on a screen and make some actions to them.</p>
<p>Can please anyone help me on how to pass a variable in a function if i want to reuse it? Example:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>static Future&lt;void&gt; createProjectFromWizard(FlutterDriver driver, String projectName, bool direct) async {

    final faker = new Faker();
    
    final buttonStart = find.byValueKey(OnboardingIds.buttonStart);
    await driver.waitFor(buttonStart).then((_) =&gt; driver.tap(buttonStart));
    </code></pre>
</div>
</div>
</p>
<p>I want to reuse this function but instead of final buttonStart I need to find another ui-button. How can I do this without re-writing this function? (Because it is a very long one, i pasted a short piece)</p>
",https://stackoverflow.com/questions/64265815/how-to-pass-a-variable-ui-object-in-flutter-dart,"['flutter', 'testing', 'dart', 'integration']",59,False,0,0
Can I use karate for testing microservices?,"<p>Let me give some background. We're trying to do e2e testing between a bunch of spring boot services that write to kafka, move files and talk to other services to do the file moving. I think we're pretty good on integration testing with mocks and whatnot, but is there a way to leverage karate or any other testing framework to help achieve fully e2e for the few major scenarios? Like can i have a test on one service that takes actual data and sends to the next service without mocking?</p>
<p>I hope that made sense. Thank you.</p>
",https://stackoverflow.com/questions/65501980/can-i-use-karate-for-testing-microservices,"['spring-boot', 'e2e-testing', 'karate']",1191,True,3,3
KafkaContainer - how to read kafka container port as property in Spring Boot after start() / how to configure Kafka port before starting,"<p>I am doing integration testing with <code>KafkaContainer</code>; after starting the container, the port is chosen randomly.</p>
<p>I can get the port by <code>container.getBootStrapServer()</code>, but what I need is to put the dynamic host+port in the properties (<code>application-itest.yml</code>, under <code>spring.kafka.bootstrap-servers</code>, because that is where Spring Kafka picks the value to configure my bean of <code>KafkaTemplate</code>).</p>
<p>Or, if I can set the port to be a static value while starting <code>KafkaContainer</code>, like <code>9999</code>, and set it in the yaml file, it also will work. I don't know how to do neither.(Do I need to inject another bean of <code>KafkaTemplate</code> after getting the value?)</p>
<p>How do I start KafkaContainer:</p>
<pre><code>    public static final KafkaContainer kafka = new KafkaContainer(
            DockerImageName.parse(&quot;confluentinc/cp-kafka:5.4.3&quot;)
    );
    private AdminClient adminClient;

    ...

    @BeforeEach
    void setup() {
        if (adminClient == null) {
            kafka.start();
            // here value is dynamic and is not accessible in Environment; not as `@AutoConfigureWiremock`, I have `wiremock.server` value set after)
            String bootStrapServer = kafka.getBootstrapServers();
            log.info(&quot;Kafka container created at: {}&quot;, bootStrapServer);
            adminClient = AdminClient.create(Map.of(
                    AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootStrapServer
            ));
            // create my topic
            log.info(&quot;Current topic: {}&quot;, topic);
            adminClient.createTopics(Set.of(
                    new NewTopic(topic, 4, (short) 1)
            ));
        }
    }

</code></pre>
",https://stackoverflow.com/questions/65078939/kafkacontainer-how-to-read-kafka-container-port-as-property-in-spring-boot-aft,"['spring-boot', 'apache-kafka', 'testcontainers']",2217,True,2,2
How do you disable Okta auto configuration for testing?,"<p>I'm using <a href=""https://mvnrepository.com/artifact/com.okta.spring/okta-spring-boot-starter/1.4.0"" rel=""nofollow noreferrer"">this Okta Spring Boot starter</a>, but I cannot disable the auto configuration for integration testing. Normally, you would do something like this:</p>
<pre class=""lang-java prettyprint-override""><code>@SpringBootTest
@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class, OktaOAuth2AutoConfig.class })
class ApplicationTests {

    @Test
    void contextLoads() {
    }
}
</code></pre>
<p>However, the OktaOAuth2AutoConfig class is package protected and you cannot disable it. I've tried component scanning filters and a bunch of other techniques, but the problem is that it is still loading and requiring <code>okta.oauth2.issuer</code> (along with client id and secret) and calling it to make sure it is a valid OAuth2 provider. I don't want this functionality in case the tests have to run somewhere where the auto config can't call the issuer. Any ideas?</p>
",https://stackoverflow.com/questions/62682142/how-do-you-disable-okta-auto-configuration-for-testing,"['spring-boot', 'spring-security', 'okta']",1354,True,1,1
Entity column with insertable and updatable false create problem for in memory h2 database,"<p>I have a simple entity create with <code>INSERTED</code> and <code>UPDATED</code> as columns. Both are marked as <code>insertable=false</code> and <code>updatable=false</code></p>

<pre><code>@Temporal(TemporalType.TIMESTAMP)
@Column(name = ""INSERTED"", nullable = false, insertable = false, updatable = false)
private final Date inserted = new Date();

@Temporal(TemporalType.TIMESTAMP)
@Column(name = ""UPDATED"", nullable = false, insertable = false, updatable = false)
private final Date updated = new Date();
</code></pre>

<p>This works fine while running it against <code>MariaDB</code> database.</p>

<p>However i am using <code>H2</code> database for integration testing of Spring Boot application. And while testing insertions of data to DB. I am receiving following errors</p>

<pre><code>Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column ""INSERTED""; SQL statement:
insert into PROSPECT (PROPERTIES, NAME, STATUS, UUID, MATCHID, ID) values (?, ?, ?, ?, ?, ?) [23502-200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:459) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:429) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.get(DbException.java:205) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.get(DbException.java:181) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.table.Column.validateConvertUpdateSequence(Column.java:374) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.table.Table.validateConvertUpdateSequence(Table.java:845) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.command.dml.Insert.insertRows(Insert.java:187) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.command.dml.Insert.update(Insert.java:151) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.command.CommandContainer.update(CommandContainer.java:198) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.command.Command.executeUpdate(Command.java:251) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:191) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:152) ~[h2-1.4.200.jar:1.4.200]
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-3.4.2.jar:?]
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.2.jar:?]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3226) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3751) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:91) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[?:?]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:108) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1344) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:435) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3221) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2389) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
</code></pre>

<p>In above exception I am able to see <code>INSERTED</code> and <code>UPDATED</code> fields are missing and They are marked as <code>NOT_NULL</code> in SQL file</p>

<p>H2 settings in test-application.properties</p>

<pre><code>spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto = update
</code></pre>

<p>If <code>INSERTABLE</code> and <code>UPDATABLE</code> annotation values are removed then everything works just fine. Integration tests do pass. </p>

<p>Is there any restriction at <code>H2</code> level with these annotation values?</p>
",https://stackoverflow.com/questions/60509306/entity-column-with-insertable-and-updatable-false-create-problem-for-in-memory-h,"['hibernate', 'spring-boot', 'jpa', 'h2']",954,False,1,0
Spring Batch - Rollback while JUnit Test,"<p>I would like to ask you about rollback transaction while integration testing SpringBatch. I would like to achieve sth like this:</p>
<ol>
<li>In JUnit run job which do some active operation on database (insert, update etc).</li>
<li>After test, rollback all change from database</li>
</ol>
<p>I have test class like this:</p>
<pre><code>@ActiveProfiles(&quot;test&quot;)
@RunWith(SpringRunner.class)
@SpringBatchTest
@SpringBootTest
@EnableAutoConfiguration
@ContextConfiguration(classes = {
  JobConfig.class,
  PersistenceConfig.class
})
@TestExecutionListeners({
  DependencyInjectionTestExecutionListener.class,
  DirtiesContextTestExecutionListener.class
})
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class SpringBatchIntegrationTest implements EnumConverter {

  @Autowired
  private JobLauncherTestUtils jobLauncherTestUtils;

  @Autowired
  private JobRepositoryTestUtils jobRepositoryTestUtils;

  @Before
  public void cleanUp() {
    jobRepositoryTestUtils.removeJobExecutions();
  }
</code></pre>
<p>And my test run job:</p>
<pre><code>final JobExecution jobExecution = jobLauncherTestUtils.launchJob(defaultJobParameters());

final JobInstance actualJobInstance = jobExecution.getJobInstance();
final ExitStatus actualJobExitStatus = jobExecution.getExitStatus();
</code></pre>
<p>Is it possible to do this? I was looking for solution but I didn't find anything. @Transactional is deprecated and not working in SpringBatch. I also try to add:</p>
<p>@Test
@Sql(scripts = &quot;/sql/clear.sql&quot;, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void givenReferenceOutputWhenJobExecutedThenSuccess() throws Exception {</p>
<p>but my clear.sql isn't executed.</p>
",https://stackoverflow.com/questions/64488349/spring-batch-rollback-while-junit-test,"['testing', 'junit', 'transactions', 'spring-batch', 'rollback']",307,False,1,0
Ignore jest test unless explicitly triggered,"<p>I have integration testing that sends me an email. I have written a jest test that tests this feature, but I only want it to run if I explicitly run that test: I don't want to receive an email every time I start VS Code.</p>
<p>I don't want to mock the email service, because success for this test is the email arriving in my inbox.</p>
<p>Is it possible to have jest ignore a test unless it is explicitly triggered?  Eg in VS Code clicking the &quot;Debug&quot; codelens button.</p>
<p>If not, what are some techniques for managing tests like this?</p>
",https://stackoverflow.com/questions/62792252/ignore-jest-test-unless-explicitly-triggered,"['visual-studio-code', 'jestjs']",185,False,0,0
Scala Akka framework Integration testing,"<p>I am trying to write a simple integration test for a scala application that uses the AKKA framework.</p>
<p>I want to</p>
<ol>
<li>have the application start on my local host</li>
<li>write test cases that hit the application directly</li>
</ol>
<p>I have done similar things things using springboottest but i can't seem to find anything remotely similar to this. I have been trying to read up on testkit routes and what not but it seems more like a unit test then it is a full application integration testing.</p>
<p>Any pointers or recommendations on what I am looking for would be great.</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/64937814/scala-akka-framework-integration-testing,"['scala', 'akka', 'integration-testing']",176,False,0,2
How to get message from E11000 DuplicationKeyError?,"<p>So I am writing unittests for a project and I am testing <code>register()</code> function.</p>

<p>Here is it:</p>

<pre><code>def register():
    # Get information about user
    username = request.get_json().get(""username"")
    password = request.get_json().get(""password"")
    name = request.get_json().get(""name"")
    email = request.get_json().get(""email"")

    # Put information about user in a tuple
    values = (
        None, 
        username, 
        User.hash_password(password), 
        name,
        email,
        None
    )

    try:
        # Create user and update session
        User(*values).create()
        ActiveUser.logged_in = True
        ActiveUser.username = username
        info_log.info(""User %s registered successfully."" % username)

        return jsonify(success=True, message=""Registration successful!"")

    except pymongo.errors.DuplicateKeyError as e:
        # Catch pymongo exception
        return jsonify(success=False, message=""Duplicated username or email!""), 403
</code></pre>

<p>I want to have three tests: valid, invalid (duplicate username), invalid (duplicate email).</p>

<pre><code># Register helper function
def register(self, username, password, name, email):
    return self.app.post(
        ""/register"",
        data = json.dumps(dict(username = username, password = password, name = name, email = email)),
        content_type='application/json',
        follow_redirects = True
        )

def test_02_valid_user_registration(self):
    response = self.register('test', '12345678', 'Tester 1', 'test@mail.mail')
    self.assertEqual(response.status_code, 200)
    self.assertIn(b'Registration successful!', response.data)

def test_03_invalid_user_registration_duplicate_username(self):
    response = self.register('test', '12345678', 'Tester 2', 'test1@mail.mail')
    self.assertEqual(response.status_code, 403)
    self.assertIn(b'Duplicate username or email!', response.data)

def test_04_invalid_user_registration_duplicate_email(self):
    response = self.register('test2', '12345678', 'Tester 3', 'test@mail.mail')
    self.assertEqual(response.status_code, 403)
    self.assertIn(b'Duplicate username or email!', response.data)
</code></pre>

<p>As expected I get DuplicateKeyError, because I have set Unique for those parameters in the database.</p>

<pre><code>pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: user.users index: username_1 dup key: { username: ""test"" }
</code></pre>

<p>Is there a way to get which is the duplicated item from the DuplicateKeyError, so I can have separate unit tests for duplicate username and email?</p>

<blockquote>
  <p>I know this is more of a component/integration testing rather than unit testing, but this is the only way I know how to do it in Python 3.</p>
</blockquote>
",https://stackoverflow.com/questions/61499410/how-to-get-message-from-e11000-duplicationkeyerror,"['python', 'python-3.x', 'mongodb', 'flask', 'pymongo']",142,True,0,1
Test GCP publisher retry settings in Spring application,"<p>I've a spring integration application - which listens for messages from a Kafka topic and publishes them to Google Cloud Topic.</p>

<p>The GCP Publisher is created using DefaultPublisherFactory and has the below retry configuration</p>

<pre><code>RetrySettings retrySettings = RetrySettings.newBuilder()
        .setInitialRetryDelay(Duration.ofSeconds(1))
        .setRetryDelayMultiplier(600)
        .setMaxRetryDelay(Duration.ofSeconds(2))
        .setTotalTimeout(Duration.ofSeconds(10))
        .setInitialRpcTimeout(Duration.ofSeconds(10))
        .setMaxRpcTimeout(Duration.ofSeconds(10))
        .build()
</code></pre>

<p>The application is up and everything runs as expected. </p>

<p>But I'm unable to figure out how to test the above retry settings. </p>

<p>Since the application isn't failing - the retry scenario is not tested. </p>

<p>I'm fairly new to integration testing - I googled a lot - but could not figure out way - to produce or mock the retry scenario.</p>

<p>Any guidance in figuring this out would be very helpful.</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/59746411/test-gcp-publisher-retry-settings-in-spring-application,"['spring', 'google-cloud-platform', 'mockito', 'spring-integration', 'integration-testing']",275,True,0,1
Spring Boot DataJpaTest (for Repositories) fail with java.lang.IllegalStateException: Failed to load ApplicationContext,"<p>I want to <strong>test the Repository-Layer of my SpringBootApplication.</strong>
I used the following Articel: 
<a href=""https://www.baeldung.com/spring-boot-testing#integration-testing-with-datajpatest"" rel=""nofollow noreferrer"">https://www.baeldung.com/spring-boot-testing#integration-testing-with-datajpatest</a></p>

<p>but there's a problem with loading the Application Context. I think it's a springBoot/Bean Problem.</p>

<p>Here's my Testing class: </p>

<pre><code>package ak19f.repositories;

import ak19f.entities.ComponentOur;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import javax.sql.DataSource;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
@ExtendWith(SpringExtension.class)
public class ComponentRepositoryTest {


    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private ComponentRepository componentRepository;

    @Test
    public void testGetOne() {
        // given
        ComponentOur c1 = new ComponentOur();
        c1.setId(1);
        c1.setComponentBrand(""d"");
        c1.setComponentDescription(""s"");
        c1.setSerialNumber(""123"");
        entityManager.persist(c1);
        entityManager.flush();

        // when
        ComponentOur found = componentRepository.getOne(1);

        // then
        assertThat(found.getComponentBrand())
                .isEqualTo(c1.getComponentBrand());
        assertThat(found.getComponentDescription())
                .isEqualTo(c1.getComponentDescription());
        assertThat(found.getComponentTyp())
                .isEqualTo(c1.getComponentTyp());
        assertThat(found.getSerialNumber())
                .isEqualTo(c1.getSerialNumber());
    }

}
</code></pre>

<p>The Application-class:  </p>

<pre><code>
@SpringBootApplication
@EnableWebMvc
public class PrototypApplication  implements WebMvcConfigurer {

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

</code></pre>

<p>And the ComponentRepository Interface: </p>

<pre><code>package ak19f.repositories;
import ak19f.entities.ComponentOur;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ComponentRepository extends JpaRepository&lt;ComponentOur,Integer&gt;{

}
</code></pre>

<p>And the ComponentEntity: </p>

<pre><code>package ak19f.entities;

import ak19f.entities.ServiceAgreement;

import javax.persistence.*;
import java.io.Serializable;
import java.util.List;

@Entity
@Table(name = ""component_our"")
public class ComponentOur implements Serializable, EntityBase {



    @Id
    @Column(name = ""component_id"" , nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(name = ""component_typ"" , nullable = false)
    private String componentTyp;

    @Column(name = ""component_description"")
    private String componentDescription;

    @Column(name = ""component_brand"")
    private String componentBrand;

    @Column( name = ""serial_number"")
    private String serialNumber;

    public ComponentOur(){}

    public ComponentOur(String componentTyp, String componentDescription, String componentBrand){
        this.componentTyp = componentTyp;
        this.componentDescription = componentDescription;
        this.componentBrand= componentBrand;
    }


    @Override
    public Integer getId() {
        return id;
    }

    @Override
    public void setId(Integer id) {
    }

    public String getComponentTyp() {
        return componentTyp;
    }

    public void setComponentTyp(String componentTyp) {
        this.componentTyp = componentTyp;
    }

    public String getComponentDescription() {
        return componentDescription;
    }

    public String getComponentBrand() {
        return componentBrand;
    }

    public void setComponentBrand(String componentBrand) {
        this.componentBrand = componentBrand;
    }

    public void setComponentDescription(String componentDescrip) {
        this.componentDescription = componentDescrip;
    }

    public String getSerialNumber() {
        return serialNumber;
    }

    public void setSerialNumber(String serialNumber) {
        this.serialNumber = serialNumber;
    }
}
</code></pre>

<p>The Problem is the following Error when I start the ComponentTest: 
Here's a Sample of the Error Stack: </p>

<pre><code>java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:98)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassBasedTestDescriptor.java:337)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:342)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassBasedTestDescriptor.java:337)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:313)
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:743)
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:742)
    at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:647)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:336)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:259)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$2(ClassBasedTestDescriptor.java:252)
    at java.util.Optional.orElseGet(Optional.java:267)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$3(ClassBasedTestDescriptor.java:251)
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:29)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:106)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:105)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:69)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:107)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:107)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:75)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    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: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:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    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: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:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    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:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:636)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:125)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    ... 69 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
    ... 87 more
Caused by: java.lang.IllegalStateException: No ServletContext set
    at org.springframework.util.Assert.state(Assert.java:73)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:533)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 88 more






</code></pre>

<p>I checked out different Spring-boot-test annotations like @SpringBootTest, but nothing changed.
Is there anyone out there who has the same issue or a solution? 
If you need further information/ code snippets / error stacks please contact me.
thanks</p>
",https://stackoverflow.com/questions/59898504/spring-boot-datajpatest-for-repositories-fail-with-java-lang-illegalstateexcep,"['java', 'spring', 'spring-boot', 'jpa', 'junit-jupiter']",8502,True,2,1
Redux Saga Test Plan - Integration Tests Fail To Run,"<p>I am having trouble getting started with <a href=""https://github.com/jfairbank/redux-saga-test-plan#readme"" rel=""nofollow noreferrer"">redux-saga-test-plan</a>. The goal that I'm trying to achieve is integration testing my sagas. I'm using create-react-app, so no unique setup. This is my only test and I cannot get it to run.</p>
<p><code>CatActions</code></p>
<pre><code>import * as types from './CatTypes';

//Replace action name and update action types
export const getCats = () =&gt; ({
  type: types.GET_CATS,
});

export const setCats = payload =&gt; ({
  type: types.SET_CATS,
  payload,
});
</code></pre>
<p><code>CatTypes</code></p>
<pre><code>export const GET_CATS = 'GET_CATS';
export const SET_CATS = 'SET_CATS';
</code></pre>
<p>Here is my saga:</p>
<pre><code>import { call, put, takeLatest } from 'redux-saga/effects';
import API from './CatApis';
import * as ACTIONS from './CatAction';
import { dispatchSnackbarError } from '../../utils/Shared';
import * as TYPES from './CatTypes';

export function* sagasRequestExample() {
  try {
    console.log('callin!');
    const response = yield call(API.apiExampleRequest);

    console.log('response :&gt;&gt; ', response);
    yield put(ACTIONS.setCats(response));
  } catch (err) {
    dispatchSnackbarError(err.response.data);
  }
}

export function* GetCats() {
  console.log('TYPES :&gt;&gt; ', TYPES);
  // On the first call here, TYPES is undefined - why?
  yield takeLatest('GET_CATS', sagasRequestExample);
  // yield takeLatest(TYPES.GET_CATS, sagasRequestExample);
}
</code></pre>
<p>Here is the test:</p>
<pre><code>    import { expectSaga } from 'redux-saga-test-plan';
import { GetCats } from './CatSagas';

expectSaga.DEFAULT_TIMEOUT = 10000;

test('just works!', () =&gt; {
  return (
    expectSaga(GetCats)
      .take('GET_CATS')
      .put({
        type: 'RECEIVE_USER',
        payload: { id: 42, name: 'Tucker' },
      })

      // // Dispatch any actions that the saga will `take`.
      // .dispatch({ type: 'REQUEST_USER', payload: 42 })

      // Start the test. Returns a Promise.
      .run()
  );
}, 10000);

</code></pre>
<p>I expect it to fail; but, I can't even get started.</p>
<p>I use <code>react-scripts test</code> (React 17)</p>
<p>When my tests run, I get - I really don't understand why TYPES is undefined</p>
<pre><code>console.log src/store/Cats/CatSagas.js:21
    TYPES :&gt;&gt;  undefined
</code></pre>
<p>as well as</p>
<pre><code>Timeout - Async callback was not invoked within the 10000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 10000ms timeout specified by jest.setTimeout.Error:
</code></pre>
<p>I don't think the API ever gets called. What am I doing wrong here? How am I supposed to be testing this saga?</p>
",https://stackoverflow.com/questions/65497360/redux-saga-test-plan-integration-tests-fail-to-run,"['javascript', 'reactjs', 'redux-saga', 'redux-saga-test-plan']",387,False,1,0
Register Mock Bean during Integration Testing for SpEL Bean Reference,"<p>I am getting the following error while running the test from my spring-boot app. I am using version= 2.3.3.RELEASE of <code>spring-boot-starter-data-mongodb</code> and version=2.2.0 of <code>de.flapdoodle.embed.mongo</code> for integration testing.</p>
<pre><code>org.springframework.expression.spel.SpelEvaluationException: EL1058E: A problem occurred when trying to resolve bean 'gameServiceImpl':'Could not resolve bean reference against BeanFactory'

    at org.springframework.expression.spel.ast.BeanReference.getValueInternal(BeanReference.java:59)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:55)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:91)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:117)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:308)
    at org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity.getCollection(BasicMongoPersistentEntity.java:129)
    at org.springframework.data.mongodb.repository.support.MappingMongoEntityInformation.getCollectionName(MappingMongoEntityInformation.java:97)
    at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.save(SimpleMongoRepository.java:88)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.data.repository.core.support.ImplementationInvocationMetadata.invoke(ImplementationInvocationMetadata.java:72)
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:382)
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:205)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:549)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:155)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy70.save(Unknown Source)
    at eatigo.com.webscraper.service.GameServiceImplTest.testSavingSingleEntity(GameServiceImplTest.java:107)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    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:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    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:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
    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: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:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
    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: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:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    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:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: org.springframework.expression.AccessException: Could not resolve bean reference against BeanFactory
    at org.springframework.context.expression.BeanFactoryResolver.resolve(BeanFactoryResolver.java:54)
    at org.springframework.expression.spel.ast.BeanReference.getValueInternal(BeanReference.java:55)
    ... 89 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'gameServiceImpl' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:816)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1109)
    at org.springframework.context.expression.BeanFactoryResolver.resolve(BeanFactoryResolver.java:51)
    ... 90 more
</code></pre>
<p>Below is my simple code implementations</p>
<p>I underdtand that the problem lies in this statement <code>@Document(collection = &quot;#{@gameServiceImpl.getCollectionName()}&quot;)</code> because during testing, the SPEL can't find any bean with name='gameServiceImpl' because it has been mocked during testing.</p>
<ol>
<li>Is there a way to inject a mock bean in the spring container registry for it to be recognized by SPEL?</li>
<li>Is it possible to replace and inject value in the class annotation here <code>@Document(collection = &quot;replace and inject value here&quot;)</code> during the initialization of entity class e.g <code>Game game= new Game();</code></li>
</ol>
<p>Entity</p>
<pre><code>@Document(collection = &quot;#{@gameServiceImpl.getCollectionName()}&quot;)
public class Game {
    @Id
    private int gameId;
}
</code></pre>
<p>Repository</p>
<pre><code>@Repository
public interface GameRepository extends MongoRepository&lt;Game, String&gt; {
}
</code></pre>
<p>Service</p>
<pre><code>@Service
public class GameServiceImpl implements GameService {

    private GameRepository gameRepository;
    private String collectionName;

    @Autowired
    public GameServiceImpl(GameRepository gameRepository){
        this.gameRepository = gameRepository;
    }

    @Override
    public String getCollectionName() {
        return collectionName;
    }

    @Override
    public void setCollectionName(String collectionName) {
        this.collectionName = collectionName;
    }

    public Game save(Game game){
        return gameRepository.save(game);
    }
}
</code></pre>
<p>Test</p>
<pre><code>ExtendWith(SpringExtension.class)
@ActiveProfiles(&quot;test&quot;)
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@SpringBootTest(classes = {MainApplication.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@DataMongoTest
public class GameServiceImplTest {

    @Mock(name = &quot;gameServiceImpl&quot;)
    private GameServiceImpl gameServiceImpl;

    @Autowired
    private GameRepository gameRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @BeforeEach
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testSavingGame(){
        Game game= new Game();

        String collectionName = &quot;testing&quot;;
        gameServiceImpl.setCollectionName(collectionName);
        when(gameServiceImpl.save(game)).thenReturn(gameRepository.save(game));
        when(gameServiceImpl.getCollectionName()).thenReturn(collectionName);

        Game result = gameServiceImpl.save(game);

        assertThat(result, is(notNullValue()));
        assertThat(mongoTemplate.collectionExists(collectionName), is(true));
        assertThat(mongoTemplate.findAll(Game.class, collectionName).size(), equalTo(1));
    }
}
</code></pre>
",https://stackoverflow.com/questions/64167148/register-mock-bean-during-integration-testing-for-spel-bean-reference,"['mongodb', 'spring-boot', 'mockito', 'integration-testing']",1256,False,1,1
How do I mock a const method IN a component as part of an integration test?,"<p>So, I am doing an integration test with jest &amp; tesing-library.
So, I have my &quot;main component&quot; called &quot;Product&quot; that brings in another component, lets call it &quot;ProductListings&quot;.</p>
<p>In &quot;ProductListings&quot;, i click on a div that calls a method IN the functional component. How do I mock that, to test it was called?</p>
<pre><code>  test('Clicking div calls method', async () =&gt; {
     render(&lt;Product /&gt;);
     // THIS div is in ProductListings component.. that is contained within Product component
     const divToClickAdd = await screen.findByTestId('myDivWithOnClick')
     user.click(divToClickAdd); // clicking this div fires the method
     // how to do this?
     expect.THE-MOCKED-FUNCTION-TO-HAVE-BEEN-CALLED 
 });
</code></pre>
<p>// this is what ProductListing looks like (psuedo). It is IN Products component, that I am integration testing.</p>
<pre><code> const ProductListing = () =&gt; {

   // I WANT TO MOCK THIS &quot;fireTheAPI&quot; in my test above.
   const fireTheAPI = () =&gt; {
      // do some stuff
   }

   return (
     &lt;div onClick={() =&gt; fireTheAPI()} data-testId=&quot;myDivWithOnClick&quot;&gt;this is a product listing item&lt;/div&gt;

   )
}
</code></pre>
<p>See my issue. Bring in Parent component, that contains a &quot;inner component, ProductListings, and I get a div from that, and click.. I need to mock that function IN it, &quot;fireTheAPI&quot;</p>
<p>btw, &quot;Product&quot; looks something like:</p>
<pre><code>const Product = () =&gt; {
   return (
      &lt;div&gt;
        &lt;WhateverComponent /&gt;
        &lt;div&gt;
            &lt;ProductListings /&gt; // &lt;--- mock a function in here
        &lt;/div&gt;
     &lt;/div&gt;
   )
}
</code></pre>
",https://stackoverflow.com/questions/63046873/how-do-i-mock-a-const-method-in-a-component-as-part-of-an-integration-test,"['reactjs', 'jestjs', 'react-testing-library', 'testing-library']",701,True,1,1
Jest ignore ReferenceError through eslint,"<p>I'm fairly new to Node integration testing and I have a problem for which I need some help. I have to write test cases and I had setup the test environment and had written the first test case as well.</p>

<pre><code>const request = require('supertest')
const mongoose = require('mongoose')

test('test', () =&gt; {
    expect(1+1).toBe(2)
})
</code></pre>

<p>And when I try running the test using jest, I get the following error</p>

<p><strong>ReferenceError: Sample is not defined</strong></p>

<p>denoting to the below code.</p>

<pre><code>const sampleSchema: new mongoose.Schema ({
///my schema goes in here
})

module.exports = Sample = mongoose.model('Sample', sampleSchema)
</code></pre>

<p>I rectified this and it showed another file and that kept going on. Also, changing the above also corrupts my program. I would like to know if it is possible to use eslint plugin to fix this issue(s). Please help!</p>
",https://stackoverflow.com/questions/62278923/jest-ignore-referenceerror-through-eslint,"['javascript', 'node.js', 'jestjs', 'eslint']",325,False,1,0
Flutter driver with custom OTP verification and native functions (Toast),"<p>I'm using flutter to develop apps. Now stuck on the test cases, </p>

<p>I referred <a href=""https://flutter.dev/docs/cookbook/testing/integration/introduction"" rel=""nofollow noreferrer"">flutter driver</a> for testing and it is working fine for simple UIs and flows.</p>

<p>I want to go through the login part, and <strong>I have an OTP verification section</strong> there, how do I pass this screen because I have to enter the pin that will receive at the verification time.</p>

<p>When I tried to check the native functions like toast (I'm using one library: <a href=""https://pub.dev/packages/fluttertoast"" rel=""nofollow noreferrer"">FlutterToast</a>) it is not catching the UI change. I tried with text catch</p>

<pre><code>await driver.waitFor(find.text('Invalid credentials.'));
</code></pre>

<p>referred links:</p>

<ol>
<li><a href=""https://blog.codemagic.io/integration-tests-codemagic/"" rel=""nofollow noreferrer"">https://blog.codemagic.io/integration-tests-codemagic/</a></li>
<li><a href=""https://medium.com/ionicfirebaseapp/an-introduction-to-integration-testing-for-flutter-app-b7d2b2af1739"" rel=""nofollow noreferrer"">https://medium.com/ionicfirebaseapp/an-introduction-to-integration-testing-for-flutter-app-b7d2b2af1739</a></li>
</ol>
",https://stackoverflow.com/questions/61345912/flutter-driver-with-custom-otp-verification-and-native-functions-toast,"['android', 'ios', 'flutter', 'toast', 'flutterdriver']",474,False,1,2
How to cache a docker image from a GitHub Action,"<p>I am having a scenario where I build an application using maven and docker on a GitHub workflow.</p>
<p>Then when the application (with docker image) is build, the integration testing of the application fails.</p>
<p>I often need to change existing integration tests without making changes in the application itself before rerunning The GitHub workflow. This causes the action to be build (and tested locally) with java and docker.</p>
<p>The build process is already done and a docker image uploaded to GitHub Packages. How can I check if this application already have a docker image?</p>
<p>Can I use actions/cache@v2 (<a href=""https://github.com/actions/cache"" rel=""noreferrer"">https://github.com/actions/cache</a>)? How? Docker is not mentioned in the languages it can cache...</p>
",https://stackoverflow.com/questions/63318776/how-to-cache-a-docker-image-from-a-github-action,"['java', 'docker', 'github-actions']",855,True,5,1
How to return an Observable from a sample data [Angular],"<p>I'm learning shallow integration testing in Angular. I've a component <code>HeroesComponent</code>. It has got one service injection i.e. <code>HeroService</code> and one child component <code>HeroComponent</code>. For now I'm trying to mock service injection only. I've some sample data in <code>HEROES: Hero[]</code> Here's my spec file:</p>

<p><strong>heores.component.spec.ts</strong></p>

<pre><code>import { Hero } from ""../hero""
import { HeroesComponent } from ""./heroes.component"";
import { HeroService } from ""../hero.service"";
import { TestBed, ComponentFixture } from ""@angular/core/testing"";
import { NO_ERRORS_SCHEMA } from ""@angular/core"";
import { of } from ""rxjs/internal/observable/of"";

describe('HeroesComponent', () =&gt; {
    let HEROES: Hero[];
    let mockHeroService: HeroService;
    let fixture: ComponentFixture&lt;HeroesComponent&gt;

    beforeEach(() =&gt; {
        HEROES = [
            {id: 1, name: 'Ant man', strength: 20},
            {id: 2, name: 'Gohan', strength: 10},
            {id: 3, name: 'Goku', strength: 5}
        ];
        mockHeroService = jasmine.createSpyObj(['getHeroes', 'addHero', 'deleteHero']);

        TestBed.configureTestingModule({
            declarations: [HeroesComponent],
            providers: [
                {provide: HeroService, useValue: mockHeroService}
            ],
            schemas: [NO_ERRORS_SCHEMA]
        })

        fixture=TestBed.createComponent(HeroesComponent);
     })

     it('should set heroes correctly from the service', () =&gt; {
        // arrange
        mockHeroService.getHeroes.and.returnValue(of(HEROES));

        // act
        fixture.detectChanges();

        // assert
        expect(fixture.componentInstance.heroes.length).toBe(3);
    })
})
</code></pre>

<p>But I'm getting this error on console. The problem is with <code>and</code> inside my <code>it()</code> method:</p>

<blockquote>
  <p>ERROR in src/app/heroes/heroes.second.spec.ts(32,39): error TS2339: Property 'and' does not exist > on type '() =>
  Observable'.</p>
</blockquote>

<p>Please point out my mistake. Feel free to ask for more code. Thanks.</p>

<p>PS: Here's the code for <code>HeroesComponent</code>:</p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  heroes: Hero[];

  constructor(private heroService: HeroService) { }

  ngOnInit() {
    this.getHeroes();
  }

  getHeroes(): void {
    this.heroService.getHeroes()
    .subscribe(heroes =&gt; this.heroes = heroes);
  }

  add(name: string): void {
    name = name.trim();
    var strength = 11
    if (!name) { return; }
    this.heroService.addHero({ name, strength } as Hero)
      .subscribe(hero =&gt; {
        this.heroes.push(hero);
      });
  }

  delete(hero: Hero): void {
    this.heroes = this.heroes.filter(h =&gt; h !== hero);
    this.heroService.deleteHero(hero).subscribe();
  }
}
</code></pre>

<p>Here's a screenshot of the pluralsight tutorial that I'm following. For him the code is working without any error: 
<a href=""https://i.stack.imgur.com/ul8E4.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ul8E4.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/61562139/how-to-return-an-observable-from-a-sample-data-angular,"['angular', 'karma-jasmine']",196,True,0,1
xUnit - deps.json not created for Integration Test in .NetCore 3.1 [Api.deps.json&#39;. This file is required for functional tests to run properly.],"<p>I have a visual studio solution with 2 projects, both in .Net Core 3.1</p>
<p>Xyz.Api,
Xyz.ApiTests</p>
<p>ApiTests is a xUnit project for integration testing.</p>
<p>I have followed what has been mentioned here.
<a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1"" rel=""nofollow noreferrer"">Integration Tests in .NET Core</a></p>
<p>This is what <code>ApiTests.csproj</code> looks like</p>
<pre><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;

    &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;16.5.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Mvc.Testing&quot; Version=&quot;3.1.8&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.NETCore.App&quot; Version=&quot;2.2.8&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;coverlet.collector&quot; Version=&quot;1.2.0&quot; /&gt;
  &lt;/ItemGroup&gt;
    &lt;ItemGroup&gt;
    &lt;ProjectReference Include=&quot;..\Xyz.Api\Xyz.Api.csproj&quot; /&gt;
  &lt;/ItemGroup&gt;
&lt;/Project&gt;
</code></pre>
<p>I am able to run the tests from Visual Studio and it works fine.</p>
<p>But when I publish the ApiTests project, it doesn't create Xyz.Api.deps.json file which is required to run test using .net core cli.</p>
<p>This is the error I get with command &quot;<code>dotnet test Xyz.ApiTests.dll</code>&quot;</p>
<pre><code>System.InvalidOperationException : Can't find'D:\T\Xyz.Api.deps.json'. This file is required for functional tests to run properly. There should be a copy of the file on your source project bin folder. If that is not the case, make sure that the property PreserveCompilationContext is set to true on your project file. E.g '&lt;PreserveCompilationContext&gt;true&lt;/PreserveCompilationContext&gt;'. 
</code></pre>
<p>I need to do this to make sure it works in Azure Pipeline.</p>
<p>Is there anything I am missing, or is there any other way to do this?</p>
",https://stackoverflow.com/questions/63914217/xunit-deps-json-not-created-for-integration-test-in-netcore-3-1-api-deps-jso,"['c#', '.net', '.net-core', 'integration-testing', 'xunit']",2145,True,4,3
Azure release pipeline not picking up variable from nestedStack.yml file,"<p>I'm configuring our Release pipeline so that Integration Tests are automatically run after pull requests are merged to master and deployed to Dev environment.</p>

<p>I'm currently getting a connection error, specifically <strong>java.net.UnknownHostException:</strong> and it looks like my one of my output variables from my nestedStack.yml code is not being imported/read properly:</p>

<p>my-repo/cloud-formation/nestedStack.yml
<a href=""https://i.stack.imgur.com/ctLAn.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ctLAn.png"" alt=""enter image description here""></a></p>

<p>You can see there is a property there ""ApiGatewayInvokeUrl"" which is marked as an Output. It is used on Azure DevOps for the ""Integration Testing"" task in my ""Deploy to Dev"" stage. It is written as $(ApiGatewayInvokeUrl) as that's how variables on Azure DevOps are used.</p>

<p><a href=""https://i.stack.imgur.com/O1tV9.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/O1tV9.png"" alt=""enter image description here""></a></p>

<p>This Deploy to Dev will ""succeed"", however when I further inspect the Integration Tests, I see none actually ran and there was a connection error immediately. I can see it is outputting the variable as $(ApiGatewayInvokeUrl) , so it looks like it just reads it as a String, and never substitutes it for the correct URL value:
<a href=""https://i.stack.imgur.com/8Lu51.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/8Lu51.png"" alt=""enter image description here""></a></p>

<p>I was going off the way another team set up there Integration Tests on a similar pipeline but I might have missed something. Do I need to define $(ApiGatewayInvokeUrl) somewhere in my codebase, or somewhere on Azure? Or am I missing something? I checked the other teams code and didn't see them define it anywhere else, that's why I am ultra confused.</p>

<p><strong>Update:</strong> I went into AWS API Gateway and copied the invoke URL and hard-coded that into the Azure DevOps Maven (integration testing) goal path and now it's connecting. So it's 100% just not importing that variable for somer reason. </p>
",https://stackoverflow.com/questions/59583283/azure-release-pipeline-not-picking-up-variable-from-nestedstack-yml-file,"['java', 'azure', 'api', 'azure-devops', 'azure-pipelines']",446,True,0,1
How to automatically log responses using Flurl v3.0.0,"<p>I'm using Flurl in integration testing and trying to configure a client to log responses (using Flurl.Http 3.0.0).</p>
<p>I'm using <a href=""https://flurl.dev/docs/configuration/#event-handlers"" rel=""nofollow noreferrer"">event handlers</a> to read the response as a string and then log it.
However, if the calling code uses <code>IFlurlResponse.GetJsonAsync&lt;&gt;</code> when the logging is enabled, the deserialized object is null (I imagine because the stream has already been read).</p>
<p>I thought it may be possible because I can see that internally Flurl tracks whether the response stream has been read (using the <code>_streamRead</code> and <code>_capturedBody</code> members).</p>
<p>Here's a repro, using <code>Flurl.Http 3.0.0</code>:</p>
<pre class=""lang-cs prettyprint-override""><code>   class Program
    {
        static async Task Main(string[] args)
        {
            using (var client = new FlurlClient(&quot;https://jsonplaceholder.typicode.com/&quot;))
            {
                var post = await client
                            .Request(&quot;posts/1&quot;)
                            .ConfigureRequest(settings =&gt; settings.AfterCallAsync = LogResponse)
                            .GetJsonAsync&lt;Post&gt;();
                Console.WriteLine($&quot;Is null with logging enabled: {post is null}&quot;); // prints True

                post = await client.Request(&quot;posts/1&quot;).GetJsonAsync&lt;Post&gt;();
                Console.WriteLine($&quot;Is null with logging disabled: {post is null}&quot;); // prints False
            }
        }

        private static async Task LogResponse(FlurlCall call)
        {
            var responseString = await call.Response.GetStringAsync();
            Console.WriteLine(responseString);
        }
    }

    public class Post
    {
        public int Id { get; set; }
        public int UserId { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
    }
</code></pre>
<p>Output:</p>
<pre><code>{
  &quot;userId&quot;: 1,
  &quot;id&quot;: 1,
  &quot;title&quot;: &quot;sunt aut facere repellat provident occaecati excepturi optio reprehenderit&quot;,
  &quot;body&quot;: &quot;quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto&quot;
}
Is null with logging enabled: True
Is null with logging disabled: False
</code></pre>
<p>If I change the calling code from using <code>GetJsonAsync&lt;&gt;</code> to <code>GetStringAsync</code> and handle json deserialization myself then the response can be 'read' twice, but it's more verbose.</p>
",https://stackoverflow.com/questions/64814837/how-to-automatically-log-responses-using-flurl-v3-0-0,['flurl'],702,True,3,1
"@TestConfiguration for Embedded Redis, same Redis Server for all Test classes","<p>I use a <a href=""https://github.com/ozimov/embedded-redis"" rel=""nofollow noreferrer"">Embedded Redis</a> for integration testing. I set up my tests with Redis according to following article: <a href=""https://www.baeldung.com/spring-embedded-redis"" rel=""nofollow noreferrer"">https://www.baeldung.com/spring-embedded-redis</a>.</p>
<p>The problem is, if I want to use the @TestConfiguration with several test classes, I get errors because @PreDestroy is not called. The Embedded Redis is created new each time and is not shared between the test classes. It is therefore tried every time to create a new Redis Sserver on the same port, which leads to the following error:</p>
<pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testRedisConfiguration': 
Invocation of init method failed; nested exception is java.lang.RuntimeException: 
Can't start redis server. Check logs for details.
</code></pre>
<p>When I add the @DirtiesContext to all test classes I get following error:</p>
<pre><code>java.lang.IllegalStateException: org.springframework.web.context.support.GenericWebApplicationContext@255e5e2e has been closed already
</code></pre>
<p>Is there a way to use the same Embedded Redis for all my test classes?</p>
",https://stackoverflow.com/questions/63591202/testconfiguration-for-embedded-redis-same-redis-server-for-all-test-classes,"['java', 'spring-boot', 'redis', 'spring-boot-test']",3311,False,2,2
Set Testid on Native Component,"<p>I'm integration testing with the tipsi-stripe package using Detox, using the following UI:</p>

<p><a href=""https://i.stack.imgur.com/iOnm6.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/iOnm6.png"" alt=""Credit Card Sample""></a></p>

<p>My test is as follows:</p>

<pre><code>    ...
    await expect(element(by.text('10'))).toBeVisible()
    await expect(element(by.text('Give $10'))).toBeNotVisible()
    await element(by.text('10')).tap()
    await expect(element(by.text('Give $10'))).toBeVisible()
    await expect(element(by.id('cc-card-input'))).toBeVisible()
    await element(by.id('cc-card-input')).typeText(""4242424242424242"")
    ...
</code></pre>

<p>The last line fails with:</p>

<pre><code>  ● Signin › allows the person to make a payment

    Error performing 'Click to focus &amp; type text (4242424242424242)' on view '(with tag value: is ""cc-card-input"" and view has effective visibility=VISIBLE)'.
    &gt; 28 |     await element(by.id('cc-card input')).typeText(""4242424242424242"")

</code></pre>

<p>The failure indicates the cc card input isn't able to be typed in. </p>

<p>Heres the component from the library in question:</p>

<pre><code>import React, { Component } from 'react'
import {
  requireNativeComponent,
  findNodeHandle,
  StyleSheet,
  View,
  TouchableWithoutFeedback,
  ViewPropTypes,
  Platform,
  Text,
} from 'react-native'
import PropTypes from 'prop-types'
import TextInputState from 'react-native/Libraries/Components/TextInput/TextInputState'

const FieldStylePropType = PropTypes.shape({
  ...ViewPropTypes.style,
  color: PropTypes.string,
})

/**
 * @typedef {Object} PaymentCardTextFieldNativeEventParams
 * @property {string} number -- card number as a string
 * @property {number} expMonth
 * @property {number} expYear
 * @property {string} cvc
 */

/**
 * @typedef {Object} PaymentCardTextFieldNativeEvent
 * @property {boolean}  valid
 * @property {PaymentCardTextFieldNativeEventParams} params
 */

/**
 * @callback OnChangeCallback
 * @param {PaymentCardTextFieldNativeEvent} params
 */

/**
 * // TODO: Get a more precise type here, not sure how to JSDoc react-native Style Types
 * @typedef {Object} PaymentComponentTextFieldStyleProp
 */

/**
 * A Component that collects the CardNumber, ExpirationDate, and CVC all in one.
 * @typedef {Object} PaymentCardTextFieldProps
 *
 * @property {string} expirationPlaceholder
 * @property {string} numberPlaceholder
 * @property {string} cvcPlaceholder
 * @property {boolean} disabled
 * @property {OnChangeCallback} onChange
 * @property {PaymentComponentTextFieldStyleProp} style
 *
 * @property {string} cursorColor iOS-only!
 * @property {string} textErrorColor iOS-only!
 * @property {string} placeholderColor iOS-only!
 * @property {""default""|""light""|""dark""} keyboardAppearance iOS-only!
 *
 * @property {boolean} setEnabled Android-only!
 * @property {string} backgroundColor Android-only!
 * @property {string} cardNumber Android-only!
 * @property {string} expDate Android-only!
 * @property {string} securityCode Android-only!
 */

const NativePaymentCardTextField = requireNativeComponent('TPSCardField', PaymentCardTextField, {
  nativeOnly: {
    borderColor: true,
    borderWidth: true,
    cornerRadius: true,
    textColor: true,
    fontFamily: true,
    fontWeight: true,
    fontStyle: true,
    fontSize: true,
    enabled: true,
    onChange: true,
    params: true, // Currently iOS only
    keyboardAppearance: true, // iOS only
  },
})

/**
 * @type {import('react').ComponentClass&lt;PaymentCardTextFieldProps&gt;}
 */
export default class PaymentCardTextField extends Component {
  static propTypes = {
    ...ViewPropTypes,
    style: FieldStylePropType,

    // Common
    expirationPlaceholder: PropTypes.string,
    numberPlaceholder: PropTypes.string,
    cvcPlaceholder: PropTypes.string,
    disabled: PropTypes.bool,
    onChange: PropTypes.func,

    ...Platform.select({
      ios: {
        cursorColor: PropTypes.string,
        textErrorColor: PropTypes.string,
        placeholderColor: PropTypes.string,
        keyboardAppearance: PropTypes.oneOf(['default', 'light', 'dark']),
      },
      android: {
        setEnabled: PropTypes.bool,
        backgroundColor: PropTypes.string,
        cardNumber: PropTypes.string,
        expDate: PropTypes.string,
        securityCode: PropTypes.string,
      },
    }),
  }

  static defaultProps = {
    ...View.defaultProps,
  }

  valid = false // eslint-disable-line react/sort-comp
  params = {
    number: '',
    expMonth: 0,
    expYear: 0,
    cvc: '',
  }

  componentWillUnmount() {
    if (this.isFocused()) {
      this.blur()
    }
  }

  isFocused = () =&gt; TextInputState.currentlyFocusedField() === findNodeHandle(this.cardTextFieldRef)

  focus = () =&gt; {
    TextInputState.focusTextInput(findNodeHandle(this.cardTextFieldRef))
  }

  blur = () =&gt; {
    TextInputState.blurTextInput(findNodeHandle(this.cardTextFieldRef))
  }

  handlePress = () =&gt; {
    this.focus()
  }

  handleChange = (event) =&gt; {
    const { onChange, onParamsChange } = this.props
    const { nativeEvent } = event

    this.valid = nativeEvent.valid
    this.params = nativeEvent.params

    if (onChange) {
      // Send the intended parameters back into JS
      onChange({ ...nativeEvent })
    }

    if (onParamsChange) {
      onParamsChange(nativeEvent.valid, nativeEvent.params)
    }
  }

  setCardTextFieldRef = (node) =&gt; {
    this.cardTextFieldRef = node
  }

  // Previously on iOS only
  setParams = (params) =&gt; {
    this.cardTextFieldRef.setNativeProps({ params })
  }

  render() {
    const {
      style,
      disabled,
      expDate,
      cardNumber,
      securityCode,
      cursorColor,
      textErrorColor,
      placeholderColor,
      numberPlaceholder,
      expirationPlaceholder,
      cvcPlaceholder,
      keyboardAppearance,
      ...rest
    } = this.props

    const {
      borderColor,
      borderWidth,
      borderRadius,
      fontFamily,
      fontWeight,
      fontStyle,
      fontSize,
      overflow,
      backgroundColor,
      color,
      ...fieldStyles
    } = StyleSheet.flatten(style)

    const viewStyles = {
      overflow,
      width: fieldStyles.width,
    }

    const commonStyles = {
      borderColor,
      borderWidth,
      borderRadius,
      backgroundColor,
    }

    return (
      &lt;View style={[commonStyles, viewStyles]}&gt;
        &lt;TouchableWithoutFeedback
          style={{ borderWidth: 2, borderColor: 'red'}}
          rejectResponderTermination
          testID={rest.testID}
          onPress={this.handlePress}
          accessible={rest.accessible}
          accessibilityLabel={rest.accessibilityLabel}
          accessibilityTraits={rest.accessibilityTraits}
        &gt;
          &lt;NativePaymentCardTextField
            ref={this.setCardTextFieldRef}
            style={[styles.field, fieldStyles]}
            borderColor=""transparent""
            borderWidth={0}
            cornerRadius={borderRadius}
            textColor={color}
            fontFamily={fontFamily}
            fontWeight={fontWeight}
            fontStyle={fontStyle}
            fontSize={fontSize}
            enabled={!disabled}
            numberPlaceholder={numberPlaceholder}
            expirationPlaceholder={expirationPlaceholder}
            cvcPlaceholder={cvcPlaceholder}
            onChange={this.handleChange}
            // iOS only
            cursorColor={cursorColor}
            textErrorColor={textErrorColor}
            placeholderColor={placeholderColor}
            keyboardAppearance={keyboardAppearance}
            // Android only
            cardNumber={cardNumber}
            expDate={expDate}
            securityCode={securityCode}
          /&gt;
        &lt;/TouchableWithoutFeedback&gt;
      &lt;/View&gt;
    )
  }
}
</code></pre>

<p>You can see that the testID is assigned to the TouchableWithoutFeedBack component - not the component thats being typed in.</p>

<p>I've tried</p>

<ul>
<li>setting the testID on the <code>NativePaymentCardTextField</code></li>
<li>setting <code>accessible={true}</code>, with an accessibilityId set on the parent component</li>
</ul>

<p><a href=""https://gist.github.com/juddey/d7051e382ae000c5a5381c44f5b5a136"" rel=""nofollow noreferrer"">View Hierarchy from Detox</a></p>

<p>I get the same error on both.</p>

<p>What do I need to do to be able to enter a credit card number into this component (if its even possible)</p>

<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/60358452/set-testid-on-native-component,"['react-native', 'detox']",1574,True,1,1
Integration Testing with ASP.NET Core and Entity Framework Core - How to Restore Test Data in Database Per Test?,"<p>I am a new .NET Core user. I am trying to perform integration testing on a ASP.NET.Core WebAPI that uses <strong>EF Core</strong> for managing data. Architecture is based on <a href=""https://github.com/dotnet-architecture/eShopOnContainers"" rel=""nofollow noreferrer"">eShopContainers</a> DDD sample. I am using Xunit for testing and have considered three approaches for resetting the database running in a docker-compose stack, to an initial state prior to running each test:</p>

<ol>
<li><strong>Test Setup</strong>: Create and seed database with test data, <strong>TearDown</strong>: Remove database.</li>
<li><strong>Test Setup</strong>: Seed database table with test data, <strong>TearDown</strong>: Clear test data.</li>
<li><strong>Test Setup</strong>: Create a transaction, <strong>TearDown</strong>: Abort transaction. </li>
</ol>

<p>The System Under Test executes create/delete/update operations within a transaction using BeginTransaction(). Not sure if EF Core can use nested transactions so have tried performing options 1 and 2 when testing.</p>

<p>The code below uses WebApiTestFactory as a class derived from <code>WebApplicationFactory</code>. This is provided as a class fixture to create a TestServer instance for testing.</p>

<pre class=""lang-cs prettyprint-override""><code>    public class CoursesScenarios : CoursesScenarioBase, IClassFixture&lt;WebApiTestFactory&gt;, IDisposable
    {
        /// &lt;summary&gt; 
        /// With Xunit constructor gets run before every test
        /// Code in the Dispose method gets run after every test completed
        /// &lt;/summary&gt;
        public CoursesScenarios(WebApiTestFactory factory) : base(factory)
        {
            Console.WriteLine(""CoursesScenario test setup..."");

            Server.Host
                .MigrateDbContext&lt;CourseContext&gt;((context, services) =&gt;
                {
                    Console.WriteLine(""Seeding lookup data"");
                    var env = services.GetService&lt;IWebHostEnvironment&gt;();
                    var settings = services.GetService&lt;IOptions&lt;CourseSettings&gt;&gt;();
                    var logger = services.GetService&lt;ILogger&lt;CoursesContextSeed&gt;&gt;();

                    new CoursesContextSeed()
                        .SeedAsync(context, env, settings, logger)
                        .Wait();
                });

            // load the test data
            Server.Host
                .MigrateDbContext&lt;CourseContext&gt;((context, services) =&gt;
                {
                    Console.WriteLine(""Seeding the test data"");
                    var env = services.GetService&lt;IWebHostEnvironment&gt;();
                    var settings = services.GetService&lt;IOptions&lt;CourseSettings&gt;&gt;();
                    var logger = services.GetService&lt;ILogger&lt;CoursesContextTestSeed&gt;&gt;();

                    new CoursesContextTestSeed()
                        .SeedAsync(context, env, settings, logger)
                        .Wait();
                });

            foreach(Course c in Context.Courses)
            {
                Console.WriteLine($""Course {c.Id}"");
            }

        }

        // tests here
        [Fact]
        ...
        //

        ///
        /// &lt;summary&gt;
        /// This gets called after every test by XUnit
        /// &lt;/summary&gt;
        ///
        public void Dispose()
        {
            // using (var command = Context.Database.GetDbConnection().CreateCommand())
            // {
            //     command.CommandText = @""DELETE FROM CourseManagement.Course;
            //         ALTER SEQUENCE coursemanagement.""""unit_UnitID_seq"""" RESTART WITH 1;"";
            //     Context.Database.OpenConnection();
            //     int result = command.ExecuteNonQuery();
            //     Console.WriteLine($""{result} records deleted from course table"");
            //     how to reload entities to match deleted state of rows in table?
            //     currently entities in memory are saved back to database
            // }
            Context.Database.EnsureDeleted();
        }
</code></pre>

<p>The following exception is raised on the server and received during testing. This is as a result of deleting the database, so the connection is lost. </p>

<pre class=""lang-cs prettyprint-override""><code>Npgsql.NpgsqlException (0x80004005): Exception while connecting
 ---&gt; System.Net.Sockets.SocketException (111): Connection refused
   at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.&lt;&gt;c__DisplayClass32_0.&lt;&lt;Open&gt;g__OpenLong|0&gt;d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.NpgsqlConnection.Open()
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
   at Microsoft.AspNetCore.Hosting.IWebHostExtensions.InvokeSeeder[TContext](Action`2 seeder, TContext context, IServiceProvider services) in /src/BuildingBlocks/WebHost.Customization/IWebHostExtensions.cs:line 76
   at Microsoft.AspNetCore.Hosting.IWebHostExtensions.&lt;&gt;c__DisplayClass1_0`1.&lt;MigrateDbContext&gt;b__2() in /src/BuildingBlocks/WebHost.Customization/IWebHostExtensions.cs:line 54
   at Polly.Policy.&lt;&gt;c__DisplayClass108_0.&lt;Execute&gt;b__0(Context ctx, CancellationToken ct)
   at Polly.Policy.&lt;&gt;c__DisplayClass138_0.&lt;Implementation&gt;b__0(Context ctx, CancellationToken token)
   at Polly.Retry.RetryEngine.Implementation[TResult](Func`3 action, Context context, CancellationToken cancellationToken, ExceptionPredicates shouldRetryExceptionPredicates, ResultPredicates`1 shouldRetryResultPredicates, Action`4 onRetry, Int32 permittedRetryCount, IEnumerable`1 sleepDurationsEnumerable, Func`4 sleepDurationProvider)
</code></pre>

<p>Has anyone managed to successfully reset database state with EF Core for integration testing, either using delete database approach or seeding/unseeding table state? Have also tried the seed data/unseed data approach, resetting identity key and deleting records using raw SQL query, but then encountered difficulty resynchronising EF Core with the state of the deleted rows in the underlying table, EF Core sees them as new entities and adds them back. Maybe best way is to resort to using test data sql scripts and ADO.NET to initialise test data state?</p>
",https://stackoverflow.com/questions/60510597/integration-testing-with-asp-net-core-and-entity-framework-core-how-to-restore,"['c#', 'asp.net-core', 'entity-framework-core']",5016,True,2,2
How can i run only the unit tests not the integration tests on build phase with maven,"<p>I added the <code>maven-failsafe-plugin</code> to my project for runnig integration tests. When i run <code>test</code> only unit tests are running and when i run <code>integration-test</code> first unit tests and then integration tests are running. </p>

<p>It's all what i want so far but when i clean and build the project both unit tests and integration tests are running which i wouldn't prefer because i just don't want to prepare the environment for integration testing on every build.
I clean and build the project for some generated source to regenerate and i don't want to run the integration test meanwhile.</p>

<p>Is there a way that i only run the integration tests on purpose not by any automation?</p>
",https://stackoverflow.com/questions/61614589/how-can-i-run-only-the-unit-tests-not-the-integration-tests-on-build-phase-with,"['java', 'maven', 'unit-testing', 'integration-testing', 'maven-failsafe-plugin']",470,True,1,1
Spring Data JPA database changes after each method don&#39;t roll back in integration tests,"<p>I am using <strong>JUnit 5</strong> with <strong>Spring boot 2.2.4</strong> for integration testing my Spring Boot application code with <strong>MySQL 5.7</strong> database but the <strong>changes that a previous test method makes to database aren't rolled back</strong> causing errors in the ones that follow.</p>
<p>I've tried answers from different stackoverflow posts such as adding <code>@Transactional</code> (from Spring), <code>@Rollback</code> (method as well as class level), <code>@TestExecutionListeners(listeners = {TransactionalTestExecutionListener.class})</code>. I've tested these options individually (as well as in combination) but adding them in the test code together.</p>
<p>This is my test code:</p>
<pre><code>@DataJpaTest
@Transactional
@Rollback
@ExtendWith(SpringExtension.class)
@Import({UserUsecasesImpl.class})
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class UserUsecasesImplINTTest {

    @Autowired
    private TestEntityManager entityManager;
    @Autowired
    @Spy
    private UserRepository userRepository;
    @Autowired
    private UserUsecases userUsecases;

    @Test
    void injectedComponentsAreNotNull(){
        assertNotNull(entityManager);
        assertNotNull(userRepository);
        assertNotNull(userUsecases);
    }

    @Test
    @Rollback
    void Create_EntityAlreadyExists_ReturnsException() {
        // set up
        User expected = UserFixture.user1.toBuilder().build();
        // entityManager.persistAndFlush(expected);
        userRepository.saveAndFlush(expected);

        // execute
        User actual = userUsecases.create(expected);

        // verify
        assertEquals(expected, actual);
        verify(userRepository).findOne(any(Example.class));
        verify(userRepository, never()).save(any(User.class));
        verifyNoMoreInteractions();
    }

    @Test
    void Find_WhenUserPresent_ReturnUser() {
        // // set up
        User expected = UserFixture.user1.toBuilder().build();
        entityManager.persistAndFlush(expected);

        // execute
        User actual = userRepository.find(expected);

        // verify
        assertEquals(expected, actual);
    }

    @Test
    // @Transactional
    void Find_WhenUserNotPresent_ReturnNull() {
        // // set up
        User expected = UserFixture.user1.toBuilder().build();
        // entityManager.persistAndFlush(UserFixture.user2.toBuilder().build());

        // execute
        User actual = userUsecases.find(expected);

        // verify
        assertNull(actual);
    }
}
</code></pre>
<p><code>UserUsecasesImpl</code> is the class that I am trying to test which contains usecases such as creating a user, finding a user, get all users, etc. There is no special configuration anywhere else in the code.</p>
",https://stackoverflow.com/questions/63319222/spring-data-jpa-database-changes-after-each-method-dont-roll-back-in-integratio,"['java', 'spring', 'spring-boot', 'spring-data-jpa', 'integration-testing']",805,False,0,1
Assert that a specific exception is thrown in a Kafka listener method,"<p>I have a <code>@KafkaListener</code> method that might throw an <code>IllegalArgumentException</code>. For the sake of the question it might look like:</p>

<pre><code>@KafkaListener(topics = ""SomeTopic"")
public void listen(ConsumerRecord&lt;String, SomeDto&gt; record) {
    throw new IllegalArgumentException(""Whats up?"");
}

</code></pre>

<p>As part of integration testing (using Spring Boot and JUnit) I want to test the method and assert that an exception has indeed been thrown. In my test class, I have a test that boils down to:</p>

<pre><code>@Rule
public ExpectedException exceptionRule = ExpectedException.none();

@Test
public void createHierarchy_invalidEventType_exception() {
    exceptionRule.expect(IllegalArgumentException.class);
    kafkaTemplate.send(""SomeTopic"", someDto);
}
</code></pre>

<p>The log shows:</p>

<blockquote>
  <p>org.springframework.kafka.listener.ListenerExecutionFailedException: Listener method 'public void com.something.EventService.listenPosition(org.apache.kafka.clients.consumer.ConsumerRecord)' threw exception; nested exception is java.lang.IllegalArgumentException: This event type is not supported.;</p>
</blockquote>

<p>So <code>IllegalArgumentException</code> got wrapped into <code>ListenerExecutionFailedException</code> and I modified my test method:</p>

<pre><code>@Test
public void createHierarchy_invalidEventType_exception() {
    exceptionRule.expectCause(isA(IllegalArgumentException.class));
    kafkaTemplate.send(""SomeTopic"", someDto);
}
</code></pre>

<p>But the log still shows the same stack trace. What am I doing wrong? How do I verify that the <code>@KafkaListener</code> method  indeed threw the exception?</p>

<p><strong>EDIT:</strong>
Here's the test's stack trace:</p>

<pre><code>java.lang.AssertionError: Expected test to throw (an instance of org.springframework.kafka.listener.ListenerExecutionFailedException and exception with cause is an instance of java.lang.IllegalArgumentException)

    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.rules.ExpectedException.failDueToMissingException(ExpectedException.java:263)
    at org.junit.rules.ExpectedException.access$200(ExpectedException.java:106)
    at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:245)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
</code></pre>

<p>Thanks.</p>
",https://stackoverflow.com/questions/60549060/assert-that-a-specific-exception-is-thrown-in-a-kafka-listener-method,"['java', 'exception', 'junit']",507,False,0,0
What is the good way of working when moving from on-premise to Azure PaaS model?,"<p>We plan to migrate to Azure cloud and would like to know what is the recommened way of working, especially when the teams are used to working with dedicated UAT/DEV servers.</p>
<p>We have about 10 UAT physical database servers, each used for a different purpose. Some servers are used for integration testing, few for user acceptance testing, for chain testing etc.</p>
<p>We plan to use services such as Azure Data Factory (SSIS IR), Azure SQL Managed Instance, Virtual machines for custom applications</p>
<p>Creating the same number of database servers on cloud would be too expensive. How can we best deal with such scenario and how it is handled within your teams? Any pointers are appreciated.</p>
",https://stackoverflow.com/questions/65412126/what-is-the-good-way-of-working-when-moving-from-on-premise-to-azure-paas-model,"['azure', 'azure-sql-database', 'virtual-machine', 'azure-data-factory']",118,False,0,1
"How many integration tests, and how many per Jest testing file?","<p>I'm currently running Jest with NestJS and I'm writing some integration tests.</p>
<p>I'm encountering a few timing problems in Jest, and am wondering if it's to do with the number of tests in my file. I have 9 <em>describe</em> blocks, and 32 <em>test</em> and <em>it</em> blocks in my largest file - is this too many?</p>
<p>As a more general question, how many integration tests should I write? All of these tests are to do with the login/register functionality of my app - is this too many? Can I ever have <em>too many</em> tests?</p>
<p>Please could someone also point out how/where can I find out about conventions for Jest and integration testing as a whole?</p>
",https://stackoverflow.com/questions/62765099/how-many-integration-tests-and-how-many-per-jest-testing-file,"['testing', 'jestjs', 'integration-testing', 'nestjs']",794,True,0,1
