title,body,link,tags,view_count,is_answered,score,answer_count
Integration testing with Jooq,"<p>How does one write integration tests in JUnit which use JOOQ as data access layer, and which rollback after test completion?</p>

<p>It seems that Jooq provides only very limited transactional management.  It offers a method</p>

<pre><code>DSLContext.transaction(TransactionalRunnable transactional)
</code></pre>

<p>This method will rollback a transaction if exception is thrown by the passed lambda.  But it is not obvious how to make this work with JUnit integration tests.  What I really want is an equivalent of @Transactional interface without using Spring.</p>

<pre><code>@Transactional
class UserApiTest
{
  UserApi api;

  @Test
  public void testUpdateUserLastName() {
    User user = getUserByUsername();
    user.setLastName(""NewLastName"");
    api.updateUser(user);
    assertEquals(""NewLastName"", user.getLastName());
    // database should be unchanged after test completion because of automatic rollback
  }
}

class UserApiImpl implements UserApi
{
  private final DSLContext db;

  @Override
  public void updateUser(LegacyUser user) {
    UserRecord userRecord = db.newRecord(USER, user);
    db.executeUpdate(userRecord);
  }
}
</code></pre>

<p>Any suggestions would be appreciated.</p>
",https://stackoverflow.com/questions/57443526/integration-testing-with-jooq,"['testing', 'transactions', 'jooq']",984,True,2,1
NodeJS + PostgreSQL integration testing,"<p>I would like to include Postgres interaction into my integration tests, i.e. not mock the database part, and I need help on figuring out the best way to do the test cleanup.</p>

<p>My setup is NodeJS, Postgres, Sequelize, Karma+Mocha. Currently, before running the tests a new database is created and migrated, after each test I run a raw query that truncates all the tables, and after all tests cases are finished the test database is dropped. As you probably guessed it, the execution time for running tests like this is pretty slow.</p>

<p>I was wondering if there is a way to speed the process up. Is there an in-memory psql database that I could use for my test cases (I've search for one for a while but couldn't find it), or something like that.</p>

<p>To be more precise, I'm looking for a way to clear the database after a test wrote something to it, in a way that does not require truncating all the tables after every test case.</p>
",https://stackoverflow.com/questions/56806923/nodejs-postgresql-integration-testing,"['node.js', 'postgresql', 'sequelize.js', 'integration-testing', 'karma-mocha']",2243,True,1,1
Flutter Integration Testing- Is there any way to relaunch app while integration testing?,"<p>I am trying to do flutter integration testing. As it stays on same screen when previous test executed. I need to relaunch app for testing from first/launch screen. Is there any way to relaunch app in flutter testing?</p>
",https://stackoverflow.com/questions/59047356/flutter-integration-testing-is-there-any-way-to-relaunch-app-while-integration,"['testing', 'flutter', 'integration-testing', 'flutter-test']",535,False,4,1
Integration testing in R,"<p>Are there common- or best practices in doing integration tests in R? Or even packages?</p>

<p>I have many modules as scripts in a data pipeline and I was thinking of the following solution:</p>

<p>Collect all inputs as a list object and all outputs as a list object. Then I could replace the input and output objects with input test data and desired output test data and compare.</p>

<p>I was thinking perhaps using the script in a testing mode by passing arguments to docopt or using an environment variable.</p>

<p>Or are integration tests not a thing in R? Should every script rather be some huge function that is properly unit tested?</p>

<p>Thanks for any advice!</p>
",https://stackoverflow.com/questions/59237046/integration-testing-in-r,['r'],799,False,1,0
Integration Testing File Uploads,"<p>I am currently developing an MVC website with some form functionality. As part of the form, users can choose to upload a file. The I've written the code for this and it is working perfectly but my issue comes from trying to write automated tests to ensure I don't break anything with future refactors.</p>

<p>I have read through the laravel documentation for file uploads and attempted to replicate this but get an failure when asserting that the file exists. The form is optional but there is some data that is required to be sent with it.</p>

<p>TestFile</p>

<pre><code> public function testDirect_FormPassesWithFile() 
    {
        Storage::fake('local');
        $file = UploadedFile::fake()-&gt;create('document.pdf');
        $response = $this-&gt;post('/direct', $this-&gt;data());
        $response-&gt;assertSessionHasNoErrors();
        Storage::disk('local')-&gt;assertExists($file-&gt;hashName());
        $response-&gt;assertStatus(302);
        $this-&gt;assertCount(1, QuickQuote::all()); 
    }

 private function data() 
    { 
        return [
            'name' =&gt; $this-&gt;faker-&gt;name,
            'email' =&gt; $this-&gt;faker-&gt;email,
            'phone' =&gt;'07718285557',
            'risk' =&gt; $this-&gt;faker-&gt;address,
            'rebuild' =&gt; $this-&gt;faker-&gt;numberBetween($min = 500000, $max = 1000000),
            'startdate' =&gt; '2019-09-01',
            'currentpremium' =&gt; $this-&gt;faker-&gt;numberBetween($min = 100, $max = 1000),
            'file' =&gt; 'document.pdf',
            '_token' =&gt; csrf_token()
        ];
    }
</code></pre>

<p>Controller</p>

<pre><code>
 public function store(StoreQuickQuote $request)
    {
        $validated = $request-&gt;validated();

        //Code entered if there are any files uploaded
        if ($request-&gt;file('file')) {
            //loop through each file and store, saving path to an array
            $files = array();
            foreach($request-&gt;file('file') as $file) {
                $path = $file-&gt;store('uploads'); 
                array_push($files, $path);
            }
            //Turn the array into json and then insert into the validated data
            $filenames = json_encode($files);
            $merged = array_merge($validated, ['file' =&gt; $filenames]);

            $quick_quote = QuickQuote::create($merged);
        }

        //No files so just store
        $quick_quote = QuickQuote::create($validated);

        return redirect('/direct')-&gt;with('success', 'Thanks! We\'ll Be In Touch.');
    }
</code></pre>

<p>Validation Request</p>

<pre><code> public function rules()
    {
        return [
            'name' =&gt; 'required',
            'email' =&gt; 'required|email',
            'phone' =&gt; 'required',
            'risk' =&gt; 'required',
            'rebuild' =&gt; 'required',
            'startdate' =&gt; 'required',
            'currentpremium' =&gt; 'present',
            'file' =&gt; 'nullable'
        ];
    }
</code></pre>

<p>Form Input</p>

<pre><code>&lt;input type=""file"" id=""file"" name=""file[]"" multiple&gt; 
</code></pre>

<p>My output is always </p>

<pre><code>There was 1 failure:

1) Tests\Feature\DirectTest::testDirect_FormPassesWithFile
Unable to find a file at path [mJ4jQ2hmxW6uMMPEneUVS6O4bZziuuTT5kq2NFVS.pdf].
Failed asserting that false is true.
</code></pre>

<p>I'm not too sure where I am going so any tips would be great.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/57255167/integration-testing-file-uploads,"['php', 'laravel', 'integration-testing']",62,True,0,1
"Azure policies, integration testing","<p>I'm new to azure and I have some azure policies to implement controls over azure services.</p>

<p>I was wondering if there exist any integration testing frameworks or tooling support to test azure policies?</p>

<p>Can I create mock objects for azure services and test if the policies work as expected or not?</p>
",https://stackoverflow.com/questions/58230014/azure-policies-integration-testing,"['azure', 'integration-testing', 'azure-policy']",39,False,0,1
C# Integration Testing Errors,"<p>I have had some problems with my code is throwing lots of errors during the testing phase (2/10). But I don't understand why. Whereas when I launch my code and access those path everything works fine.</p>

<p>Here is a screenshot of the errors:</p>

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

<p>Here is my <code>System.cs</code>:</p>

<pre><code>using Shard.Shared.Core;
using System;
using System.Collections.Generic;

namespace Shard.Shared.Web.API
{
    public class Systems
    {
        public List&lt;SystemSpecification&gt; MySystems { get; set; }
    }
}
</code></pre>

<p>Here is my <code>SystemController.cs</code>:</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Shard.Shared.Core;
using Xunit;

namespace Shard.Shared.Web.API.Controllers
{
    [ApiController]
    [Route(""[controller]"")]
    public class SystemsController : ControllerBase
    {
        public Systems systemList = new Systems();
        public void CreateUniverse()
        {
            MapGeneratorOptions options = new MapGeneratorOptions
            {
                Seed = ""Val Halla""
            };

            MapGenerator map = new MapGenerator(options);
            var array = map.Generate().Systems.ToArray();
            systemList.MySystems = array.ToList();
        }

        [HttpGet]
        public IEnumerable&lt;Systems&gt; Get()
        {
            CreateUniverse();
            /*return Enumerable.Range(1, 5).Select(index =&gt; new Systems { 
                Sectors = map.Generate(),
                MySystems = array.ToList()
            })*/ yield return systemList;
        }

        [HttpGet(""{sectorName}"")]
        public IActionResult GetSector(string sectorName)
        {
            CreateUniverse();
            if (String.IsNullOrWhiteSpace(sectorName))
            {
                return StatusCode(404);
            }
            SystemSpecification findSector = systemList.MySystems.FirstOrDefault((p) =&gt; p.Name == sectorName);

            if (findSector == null)
            {
                return StatusCode(404);
            }

            return StatusCode(200, findSector);
        }

        [HttpGet(""{sectorName}/planets"")]
        public IActionResult GetSectorPlanets(string sectorName)
        {
            CreateUniverse();
            if (String.IsNullOrWhiteSpace(sectorName))
            {
                return StatusCode(404);
            }
            var findSector = systemList.MySystems.FirstOrDefault((p) =&gt; p.Name == sectorName);
            if (findSector == null)
            {
                return StatusCode(404);
            }

            var planets = findSector.Planets;

            if (planets == null)
            {
                return StatusCode(404);
            }

            Assert.NotNull(findSector);

            return StatusCode(200,planets);
        }

        [HttpGet(""{sectorName}/planets/{planetName}"")]
        public IActionResult GetSectorPlanets_SpecificPlanet(string sectorName, string planetName)
        {
            CreateUniverse();

            if (sectorName.Trim().Length == 0 || planetName.Trim().Length == 0)
            {
                return StatusCode(404);
            }
            else
            {
                /*var findSector = systemList.MySystems.FirstOrDefault((p) =&gt; p.Name == sectorName);
                var findPlanetName = findSector.Planets.FirstOrDefault((p) =&gt; p.Name == planetName);*/

                foreach (SystemSpecification system in systemList.MySystems)
                {
                    if (system.Name == sectorName)
                    {
                        foreach (PlanetSpecification planet in system.Planets)
                        {
                            if (planet.Name == planetName)
                            {
                                return StatusCode(200, planet);
                            }
                        }
                    }
                }

                return StatusCode(404);

                /*if (findSector == null || findPlanetName == null)
                {
                    return StatusCode(404);
                }*/

                //return StatusCode(200, findPlanetName);
            }
        }
    }
}
</code></pre>

<p>I tested all these cases when I launch the program but when it comes to respecting the test cases it's mainly the errors it's displaying that I barely understand. So please I will really appreciate if you guys can help me out.</p>

<p>These are the test cases (<code>BaseIntegrationTests.SectorTests.cs</code>):</p>

<pre><code>using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace Shard.Shared.Web.IntegrationTests
{
    public partial class BaseIntegrationTests&lt;TEntryPoint, TWebApplicationFactory&gt;
    {
        [Fact]
        [Trait(""grading"", ""true"")]
        [Trait(""version"", ""1"")]
        public async Task CanReadSystems()
        {
            using var client = factory.CreateClient();
            using var response = await client.GetAsync(""systems"");
            await response.AssertSuccessStatusCode();

            var array = await response.Content.ReadAsAsync&lt;JArray&gt;();
            Assert.NotEmpty(array);
        }

        [Fact]
        [Trait(""grading"", ""true"")]
        [Trait(""version"", ""1"")]
        public async Task SystemsHaveNames()
        {
            using var client = factory.CreateClient();
            using var response = await client.GetAsync(""systems"");
            await response.AssertSuccessStatusCode();

            var array = await response.Content.ReadAsAsync&lt;JArray&gt;();

            Assert.NotNull(array[0][""name""]);
            Assert.Equal(JTokenType.String, array[0][""name""].Type);
        }

        [Fact]
        [Trait(""grading"", ""true"")]
        [Trait(""version"", ""1"")]
        public async Task SystemsHavePlanets()
        {
            using var client = factory.CreateClient();
            using var response = await client.GetAsync(""systems"");
            await response.AssertSuccessStatusCode();

            var array = await response.Content.ReadAsAsync&lt;JArray&gt;();

            Assert.NotNull(array[0][""planets""]);
            Assert.Equal(JTokenType.Array, array[0][""planets""].Type);
            Assert.NotEmpty(array[0][""planets""]);
        }

        [Fact]
        [Trait(""grading"", ""true"")]
        [Trait(""version"", ""1"")]
        public async Task PlanetsHaveNames()
        {
            using var client = factory.CreateClient();
            using var response = await client.GetAsync(""systems"");
            await response.AssertSuccessStatusCode();

            var array = await response.Content.ReadAsAsync&lt;JArray&gt;();

            Assert.NotNull(array[0][""planets""][0][""name""]);
            Assert.Equal(JTokenType.String, array[0][""planets""][0][""name""].Type);

            var names = array.SelectTokens(""$[*].planets[*].name"").Select(token =&gt; token.Value&lt;string&gt;());
        }

        [Fact]
        [Trait(""grading"", ""true"")]
        [Trait(""version"", ""1"")]
        public async Task PlanetsHaveSizes()
        {
            using var client = factory.CreateClient();
            using var response = await client.GetAsync(""systems"");
            await response.AssertSuccessStatusCode();

            var array = await response.Content.ReadAsAsync&lt;JArray&gt;();

            Assert.NotNull(array.SelectToken(""[0].planets[0].size""));
            Assert.Equal(JTokenType.Integer, array.SelectToken(""[0].planets[0].size"").Type);
            Assert.Equal(JTokenType.Integer, array.SelectToken(""[0].planets[0].size"").Type);
        }

        [Fact]
        [Trait(""grading"", ""true"")]
        [Trait(""version"", ""2"")]
        public async Task PlanetsDoNotHaveResources()
        {
            using var client = factory.CreateClient();
            using var response = await client.GetAsync(""systems"");
            await response.AssertSuccessStatusCode();

            var array = await response.Content.ReadAsAsync&lt;JArray&gt;();
            var allPlanets = array.SelectTokens(""[*].planets[*]"").Cast&lt;IDictionary&lt;string, JToken&gt;&gt;();
            var allProperties = allPlanets.SelectMany(planet =&gt; planet.Keys).Distinct();
            Assert.DoesNotContain(""resource"", string.Join("","", allProperties));
        }

        public async Task&lt;JToken&gt; GetFirstSystem()
        {
            using var client = factory.CreateClient();
            using var systemsResponse = await client.GetAsync(""systems"");
            await systemsResponse.AssertSuccessStatusCode();

            var systems = await systemsResponse.Content.ReadAsAsync&lt;JArray&gt;();
            var system = systems.FirstOrDefault();
            Assert.NotNull(system);

            return system;
        }

        [Fact]
        [Trait(""grading"", ""true"")]
        [Trait(""version"", ""1"")]
        public async Task CanFetchOneSystem()
        {
            var system = await GetFirstSystem();

            using var client = factory.CreateClient();
            using var response = await client.GetAsync(""systems/"" + system[""name""].Value&lt;string&gt;());
            await response.AssertSuccessStatusCode();

            Assert.Equal(system.ToString(), (await response.Content.ReadAsAsync&lt;JToken&gt;()).ToString());
        }

        [Fact]
        [Trait(""grading"", ""true"")]
        [Trait(""version"", ""1"")]
        public async Task CanFetchPlanetsOfOneSystem()
        {
            var system = await GetFirstSystem();

            using var client = factory.CreateClient();
            using var response = await client.GetAsync(""systems/"" + system[""name""].Value&lt;string&gt;() + ""/planets"");
            await response.AssertSuccessStatusCode();

            Assert.Equal(system[""planets""].ToString(), (await response.Content.ReadAsAsync&lt;JToken&gt;()).ToString());
        }

        [Fact]
        [Trait(""grading"", ""true"")]
        [Trait(""version"", ""1"")]
        public async Task CanFetchOnePlanet()
        {
            var system = await GetFirstSystem();
            var planet = system[""planets""][0];

            using var client = factory.CreateClient();
            using var response = await client.GetAsync(
                ""systems/"" + system[""name""].Value&lt;string&gt;() + ""/planets/"" + planet[""name""].Value&lt;string&gt;());
            await response.AssertSuccessStatusCode();

            Assert.Equal(planet.ToString(), (await response.Content.ReadAsAsync&lt;JToken&gt;()).ToString());
        }

        [Fact]
        [Trait(""grading"", ""true"")]
        public async Task NonExistingSectorReturns404()
        {
            using var client = factory.CreateClient();
            using var response = await client.GetAsync(""systems"");
            await response.AssertSuccessStatusCode();

            var array = await response.Content.ReadAsAsync&lt;JArray&gt;();

            Assert.NotNull(array.SelectToken(""[0].planets[0].size""));
            Assert.Equal(JTokenType.Integer, array.SelectToken(""[0].planets[0].size"").Type);
            Assert.Equal(JTokenType.Integer, array.SelectToken(""[0].planets[0].size"").Type);
        }
    }
}
</code></pre>

<p>I can't really figure out the error messages. </p>

<p>Thanks</p>
",https://stackoverflow.com/questions/57966135/c-integration-testing-errors,"['c#', 'asp.net', 'asp.net-core']",198,False,0,0
Maven Integration Testing Command,"<p>I created Maven project using Java for automation testing. When i run mvn verify it does not open any browser. What wrong with it? I can easily run testng class from eclipse but i need to run for CI/CD. </p>

<pre><code>&lt;build&gt;
    &lt;pluginManagement&gt;
      &lt;plugins&gt;
        &lt;plugin&gt;
          &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
          &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
          &lt;version&gt;3.8.0&lt;/version&gt;
          &lt;configuration&gt;
             &lt;source&gt;1.8&lt;/source&gt;
             &lt;target&gt;1.8&lt;/target&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-M3&lt;/version&gt;
        &lt;configuration&gt;
            &lt;suiteXmlFiles&gt;
                &lt;suiteXmlFile&gt;testng.xml&lt;/suiteXmlFile&gt;
            &lt;/suiteXmlFiles&gt;
        &lt;/configuration&gt;

        &lt;executions&gt;
            &lt;execution&gt;
                &lt;goals&gt;
                    &lt;goal&gt;integration-test&lt;/goal&gt;
                    &lt;goal&gt;verify&lt;/goal&gt;
                &lt;/goals&gt;
            &lt;/execution&gt;
        &lt;/executions&gt;
    &lt;/plugin&gt;

      &lt;/plugins&gt;
    &lt;/pluginManagement&gt;
  &lt;/build&gt;
</code></pre>

<p>Please help. Thanks. </p>

<p><a href=""https://i.stack.imgur.com/8bF5s.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/8bF5s.png"" alt=""Maven Console Output""></a></p>

<p><a href=""https://i.stack.imgur.com/O70DU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/O70DU.png"" alt=""Project Structure""></a></p>
",https://stackoverflow.com/questions/56627016/maven-integration-testing-command,"['maven', 'selenium', 'maven-plugin']",503,False,0,0
AspNetCore Integration Testing Multiple WebApplicationFactory Instances?,"<p>Does any one know if it is possible to host multiple instances of <code>WebApplicationFactory&lt;TStartop&gt;()</code> in the same unit test?</p>

<p>I have tried and can't seem to get anywhere with this one issue.</p>

<p>i.e
</p>

<pre><code>_client = WebHost&lt;Startup&gt;.GetFactory().CreateClient();
var baseUri = PathString.FromUriComponent(_client.BaseAddress);
_url = baseUri.Value;

_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
    ""Bearer"", ""Y2E890F4-E9AE-468D-8294-6164C59B099Y"");
</code></pre>

<p><code>WebHost</code> is just a helper class that allows me to build factory and then a client easily in one line.</p>

<p>Under the covers all it does is this:</p>

<p><code>new WebApplicationFactory&lt;TStartup&gt;()</code> but a few other things too.</p>

<p>It <strong>would be</strong> <em>nice</em> if i could stand up another instace of a different web server to test server to server functionality.</p>

<p>Does anyone know if this is possible or not?</p>
",https://stackoverflow.com/questions/54944216/aspnetcore-integration-testing-multiple-webapplicationfactory-instances,"['c#', 'unit-testing', 'asp.net-core', 'integration-testing', 'asp.net-core-2.2']",7816,True,10,4
Integration testing with Embedded Postgres,"<p>I followed the instructions mentioned here: <a href=""https://medium.com/@valeryyakovlev/embedded-postgres-test-config-ab8e4e0d3256"" rel=""nofollow noreferrer"">https://medium.com/@valeryyakovlev/embedded-postgres-test-config-ab8e4e0d3256</a></p>

<p>It works fine when I run locally but gives the following error when built on gitlab CI. </p>

<pre><code>            Caused by:
            org.springframework.beans.BeanInstantiationException: Failed to instantiate [ru.yandex.qatools.embed.postgresql.EmbeddedPostgres]: Factory method 'embeddedPostgres' threw exception; nested exception is de.flapdoodle.embed.process.exceptions.DistributionException: java.io.IOException: Could not open inputStream for http://get.enterprisedb.com/postgresql/postgresql-11.1-1-linux-x64-binaries.tar.gz

                Caused by:
                de.flapdoodle.embed.process.exceptions.DistributionException: java.io.IOException: Could not open inputStream for http://get.enterprisedb.com/postgresql/postgresql-11.1-1-linux-x64-binaries.tar.gz

                    Caused by:
                    java.io.IOException: Could not open inputStream for http://get.enterprisedb.com/postgresql/postgresql-11.1-1-linux-x64-binaries.tar.gz

                        Caused by:
                        java.io.IOException: Server returned HTTP response code: 403 for URL: http://get.enterprisedb.com/postgresql/postgresql-11.1-1-linux-x64-binaries.tar.gz

Gradle Test Executor 1 finished executing tests.
</code></pre>

<p>I found some sources mentioning to customize proxy: <a href=""https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo#customize-proxy-for-download"" rel=""nofollow noreferrer"">https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo#customize-proxy-for-download</a></p>

<p>It didn't help.  </p>
",https://stackoverflow.com/questions/57103253/integration-testing-with-embedded-postgres,"['java', 'postgresql', 'spring-boot', 'gitlab-ci']",730,False,2,0
Integration testing DAO INSERT statement,"<p>I need to perform an integration test for an INSERT statement.<br>
Basically, I want an automated test that ensures that the SQL written in that query is in fact correct.<br>
I'm not sure on how to write this integration test.  </p>

<p>You need to take into account the following thoughts:  </p>

<ul>
<li>The method performs a fire-and-forget type INSERT, so unit testing it is IMO not useful.  </li>
<li>I cannot write a findById method, because the record doesn't have an ID. An id is useless in my case, because these records will never be retrieved by id. Moreover, this would cause a chicken-and-egg problem because either findById or insert statements may be wrong.    </li>
</ul>

<p>I've seen a bunch of posts that immediately start about discussing unit testing. I don't want to unit test this, I want to write an integration test that ensures my SQL query is correct.  </p>

<p>I am not looking for specific code, I am looking for the correct conceptual way to test my sql query performed in the code (in my case it happens to be Java).<br>
Could you give me some advice?  </p>

<p>Code: </p>

<pre><code>public void insertPostStat(PostStat postStat) {
    final String sql = ""INSERT INTO post_stat(created_at, geom, google_place_id, google_place_name) "" +
            ""VALUES(?, ST_SetSRID(ST_MakePoint(? , ? ), 4326), ?, ?"";

    KeyHolder holder = new GeneratedKeyHolder();
    SqlParameterSource param = new MapSqlParameterSource()
            .addValue(""created_at"", postStat.getCreatedAtMs())
            .addValue(""longitude"", postStat.getLongitude())
            .addValue(""latitude"", postStat.getLatitutde())
            .addValue(""google_place_id"", postStat.getGooglePlaceId())
            .addValue(""google_place_name"", postStat.getGooglePlaceName());
    template.update(sql,param, holder);
}
</code></pre>
",https://stackoverflow.com/questions/54873130/integration-testing-dao-insert-statement,"['java', 'integration-testing']",756,True,1,1
Spring integration testing with Schedulers.elastic,"<p>I have the following spring reactor code that does saving in DB through Schedulers.elastic(). However I see the elastic thread does not end / commit until 60 seconds elapses(its idle time). So my integration test are failing unless I wait for that time. Is there a better way to do this ? like using  Schedulers.immediate() for tests and elastic for actual deployment.</p>

<pre><code>public void method() {
   Mono.just(student)
   .flatMap(student -&gt; populateStudentDetails(student))
   .subscribeOn(Schedulers.elastic)
   .subscribe(studentRepository::save);
}
</code></pre>

<p>I am running my test as below</p>

<pre><code>@SpringBootTest
public class TestClass {
   @Test
   void testMethod() {
        testClass.method();
        //assertForDatainDB
        //fails if immediately asserted
        //succeeds if asserted after 60s
   }
}
</code></pre>
",https://stackoverflow.com/questions/54129382/spring-integration-testing-with-schedulers-elastic,"['spring', 'project-reactor', 'reactor']",370,True,1,1
Integration testing without Spring context,"<p>Should I always start Spring context during integration tests? (I mean using <code>@SpringBootTest</code> annotation)</p>

<p>Currently I'm writing integration test that involves a few classes and in order to make it faster I create object graph <em>by hand</em> (i.e. I don't start Spring IoC container). So currently my integration test (written in Spock) looks like this:</p>

<pre><code>class UserConverterIT extends Specification {

    UserConverter converter = new UserConverter(new UserDtoFactory(new UserGroupPolicy()))

    def 'should ...'() {
        when:
        converter.convert(...)

        then:
        ...
    }
}
</code></pre>

<p>Alternatively I could add <code>@SpringBootTest</code> annotation, put <code>@Autowire</code> above <code>UserConverter</code> field and all dependecies would be injected automatically. However, the first approach is much faster. Is there something wrong in this approach?</p>
",https://stackoverflow.com/questions/56235109/integration-testing-without-spring-context,"['java', 'spring', 'spring-boot', 'testing', 'spring-boot-test']",610,False,0,1
Shutdown Hook Corda integration testing,"<p>I have the following <a href=""https://github.com/altfatterz/learning-corda/blob/master/workflows/iou-workflow/src/main/kotlin/com/example/flows/IOUFlow.kt"" rel=""nofollow noreferrer"">Corda service</a>. It starts up a Jetty Server</p>

<pre><code>@CordaService
class IOUService(private val serviceHub: AppServiceHub): SingletonSerializeAsToken() {

    init {
        val port = serviceHub.myInfo.addresses.first().port - 1002
        log.println(""IOUService init was called..."")
        log.println(""Port: $port"")

        val jettyServer = JettyServer()
        jettyServer.start(port)
    }
}
</code></pre>

<p>My problem is how to release the stared Jetty port when running integration tests. Here are two example test (basically the same test twice to illustrate the problem):</p>

<pre><code>    @Test
    fun `node test`() = withDriver {
        val (partyAHandle, partyBHandle) = startNodes(bankA, bankB)
        assertEquals(bankB.name, partyAHandle.resolveName(bankB.name))
        assertEquals(bankA.name, partyBHandle.resolveName(bankA.name))
    }

    @Test
    fun `node test2`() = withDriver {
        val (partyAHandle, partyBHandle) = startNodes(bankA, bankB)
        assertEquals(bankB.name, partyAHandle.resolveName(bankB.name))
        assertEquals(bankA.name, partyBHandle.resolveName(bankA.name))
    }
</code></pre>

<p>The first test will start up 3 nodes: one notary, BankA and BankB nodes with the following details:</p>

<pre><code>Notary:
Advertised P2P messaging addresses      : localhost:10000
RPC connection address                  : localhost:10001
RPC admin connection address            : localhost:10002
Jetty Port: 8998

BankA:
Advertised P2P messaging addresses      : localhost:10004
RPC connection address                  : localhost:10005
RPC admin connection address            : localhost:10006
Jetty Port: 9002

BankB:
Advertised P2P messaging addresses      : localhost:10008
RPC connection address                  : localhost:10009
RPC admin connection address            : localhost:10010
Jetty Port: 9006
</code></pre>

<p>Unfortunately the second test will fails since the Jetty ports are still bound:</p>

<pre><code>[ERROR] 14:22:04,825 [driver-pool-thread-0] internal.Node.installCordaServices - Corda service com.example.flows.IOUService failed to instantiate. Reason was: Address already in use [errorCode=1pryyp4, moreInformationAt=https://errors.corda.net/OS/4.1/1pryyp4]
 java.io.IOException: Failed to bind to 0.0.0.0/0.0.0.0:9006
</code></pre>

<p>How to register a shutdown hook during integration testing in order to shut down the Jetty servers?</p>

<p>The example code can be found here:</p>

<p><a href=""https://github.com/altfatterz/learning-corda"" rel=""nofollow noreferrer"">https://github.com/altfatterz/learning-corda</a></p>
",https://stackoverflow.com/questions/59214090/shutdown-hook-corda-integration-testing,['corda'],73,False,0,1
Azure functions integration testing locally,"<p>I am trying to run integration tests on an azure functions project locally. My method is to start the azure server programatically using a process. This does not work for some reason.</p>

<p>This is how i setup the process:</p>

<pre><code>private Process process;
private RestClient client;

[OneTimeSetUp]
public void OneTimeSetUp()
{
    const string dotnetExePath = @""C:\Program Files\dotnet\dotnet.exe"";
    const string functionHostPath = @""C:\Users\MyName\AppData\Local\AzureFunctionsTools\Releases\2.24.0\cli\func.dll"";
    const string functionAppFolder = @""C:\Users\MyName\Source\Repos\ShyftApi\ShyftApi\bin\Debug\netstandard2.0"";

    process = new Process
    {
        StartInfo =
        {
            FileName = dotnetExePath,
            Arguments = $""\""{functionHostPath}\"" start -p {7001}"",
            WorkingDirectory =  functionAppFolder
        }
    };

    bool success = process.Start();
    Assert.AreEqual(true, success);
    client = new RestClient($""http://localhost:{7001}/api"");
    Thread.Sleep(8000);
}
</code></pre>

<p><code>OneTimeSetup</code> succeeds without an error so i assume that the process started correctly (but i see no azure shell, wierd?)</p>

<p>I run a simple http call (using restsharp):</p>

<pre><code>[Test]
public void SimpleTest()
{
    RestRequest request = new RestRequest(""/test"", Method.POST);
    IRestResponse response = client.Execute(request);
    Assert.AreEqual(200, response.StatusCode);
}
</code></pre>

<p>This is the azure function that i am trying to test:</p>

<pre><code>[FunctionName(""test"")]
public static IActionResult Test([HttpTrigger(AuthorizationLevel.Anonymous, ""get"", Route = null)]HttpRequest req, TraceWriter log)
{
    return new OkObjectResult(""ok"");
}
</code></pre>

<p>The test fails because <code>response.StatusCode</code> is 0 so i assume that the server is not up. </p>

<p>I followed the format used in <a href=""https://blog.kloud.com.au/2018/11/08/integration-testing-precompiled-v2-azure-functions/"" rel=""nofollow noreferrer"">https://blog.kloud.com.au/2018/11/08/integration-testing-precompiled-v2-azure-functions/</a> for the arguments to the process. I have manually checked that the paths are correct (But the process starts sucessfully so i dont think the paths are the issue?). </p>

<p>The endpoint i am trying to hit is <code>http://localhost:7071/api/test</code> and when running the azure server regurarly (F5) and accessing it through my browser i get a 200 ok.</p>

<p>What do you think could be the issue? The starting arguments to the process or am i just using the wrong url?</p>
",https://stackoverflow.com/questions/56759066/azure-functions-integration-testing-locally,"['azure', 'rest', 'process', 'integration-testing', 'restsharp']",434,False,-1,1
Avoid dependency in Integration Testing,"<p>In integration testing scenario, I have an object creation if the object creation is successful I have Record CRUD operation but if object creation fails then record operation should be skipped. To maintain these integration scenarios I have configured my testng.xml file like this : -  </p>

<pre><code>&lt;!DOCTYPE suite SYSTEM ""http://testng.org/testng-1.0.dtd""&gt;
&lt;suite name=""TestNG"" verbose=""1"" &gt;

    &lt;test name=""Object  Testing"" preserve-order=""true""&gt;
        &lt;classes&gt;
            &lt;class name=""com.settings.test.employee.PostObject"" /&gt;
            &lt;class name=""com.settings.test.employee.GetObject"" /&gt;
            &lt;class name=""com.settings.test.employee.DeleteObject"" /&gt;
        &lt;/classes&gt;
    &lt;/test&gt;

    &lt;test name="" Record Testing"" preserve-order=""true""&gt;
        &lt;classes&gt;
            &lt;class name=""com.settings.test.employee.PostObject"" /&gt;
            &lt;class name=""com.settings.test.employee.PostRecord"" /&gt;
            &lt;class name=""com.settings.test.employee.GetRecord"" /&gt;
            &lt;class name=""com.settings.test.employee.GetRecordByID"" /&gt;
            &lt;class name=""com.settings.test.employee.DeleteObject"" /&gt;
        &lt;/classes&gt;
    &lt;/test&gt;


&lt;/suite&gt;

</code></pre>

<p>In this approach unneccessary i am doing the same operation again and again which increases time of execution and code size.
I need to maintain this dependency at a class level not outside of the class, please suggest me some approach on how I can make it happen?.</p>
",https://stackoverflow.com/questions/57767831/avoid-dependency-in-integration-testing,"['testing', 'automation', 'testng']",39,False,0,1
IntelliJ creating Integration Testing Environment,"<p>I'm creating another source set for integration testing, but every time my gradle rebuilds it turns my main test root folder back to source root folder (blue), when I want it to be test root folder (green). What do I need to configure in my build.gradle so that this is fixed?</p>

<pre><code>sourceSets {
    integration {
        compileClasspath += sourceSets.main.output
        runtimeClasspath += sourceSets.main.output
    }
}

configurations {
    intTestRuntimeOnly.extendsFrom runtimeOnly
    intTestImplementation.extendsFrom testImplementation
}

dependencies {
    intTestImplementation 'junit:junit:4.12'
}
task integrationTest(type: Test) {
    description = 'Runs integration tests.'
    group = 'verification'

    testClassesDirs = sourceSets.integration.output.classesDirs
    classpath = sourceSets.integration.runtimeClasspath
    shouldRunAfter test
}

check.dependsOn integrationTest
</code></pre>

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

<p>Everytime I manually change it to testsources root and rebuild it just turns back to blue. </p>

<p>I followed this documentation <a href=""https://docs.gradle.org/current/userguide/java_testing.html#sec:configuring_java_integration_tests"" rel=""nofollow noreferrer"">https://docs.gradle.org/current/userguide/java_testing.html#sec:configuring_java_integration_tests</a></p>

<p>Thanks</p>
",https://stackoverflow.com/questions/59221824/intellij-creating-integration-testing-environment,"['java', 'gradle', 'intellij-idea']",92,False,0,0
Spring Cloud Stream - Integration testing,"<p>I have micro services built based on Spring Cloud Stream. Testing team needs to create integration test for these services. What are best practices?</p>

<p>Based on the sample below, Sink/Source/Processor from different applications needs to be in classpath of the testing project. Is the expectation is to package each service and include it in testing project?</p>

<p><a href=""https://github.com/spring-cloud/spring-cloud-stream-samples/blob/master/testing-samples/testing-demo/src/test/java/org/springframework/cloud/stream/testing/processor/integration/ToUpperCaseProcessorIntTests.java"" rel=""nofollow noreferrer"">https://github.com/spring-cloud/spring-cloud-stream-samples/blob/master/testing-samples/testing-demo/src/test/java/org/springframework/cloud/stream/testing/processor/integration/ToUpperCaseProcessorIntTests.java</a></p>

<p>Thanks</p>
",https://stackoverflow.com/questions/55739806/spring-cloud-stream-integration-testing,"['spring-cloud-stream', 'spring-cloud-dataflow']",999,True,0,1
Flink - Integration testing with multiple sources,"<p>I have a Flink job, which I am integration testing using the approach described here: <a href=""https://ci.apache.org/projects/flink/flink-docs-stable/dev/stream/testing.html#integration-testing"" rel=""noreferrer"">https://ci.apache.org/projects/flink/flink-docs-stable/dev/stream/testing.html#integration-testing</a></p>

<p>The job takes its input from two sources, which are combined in a <code>CoFlatMapFuntion</code>.  In the test environment, I'm currently using two simple SourceFunctions to emit the values, however this doesn't provide any control over the order in which the events are emitted.  This is necessary in order to properly test the functionality of the job.</p>

<p>How can I modify my test to ensure one source function emits all of its data before the second?</p>

<p>I've seen the approach suggested in <a href=""https://stackoverflow.com/questions/52153863/integration-test-for-complex-topology-multiple-inputs-in-flink"">Integration test for complex topology (multiple inputs) in Flink</a>, this is fine for unit testing but I'm looking for a solution which allows me to integration test the entire job.</p>
",https://stackoverflow.com/questions/54908476/flink-integration-testing-with-multiple-sources,"['java', 'apache-flink', 'flink-streaming']",1803,True,5,1
Parallel integration testing with SQL database,"<p>Wanted Result: Run integration tests in parallel with entity framework configured to use some kind of database that enforces constraints.</p>

<p>Current Situation: I have a project with some integration tests, and by that I mean test set up with <code>WebApplicationFactory&lt;Startup&gt;</code>. Currently I use it with EF Core setup to use In Memory Database</p>

<pre><code> protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            ConfigureWebHostBuilder(builder);
            builder.ConfigureTestServices(services =&gt;
            {
                var serviceProvider = new ServiceCollection()
                    .AddEntityFrameworkInMemoryDatabase()
                    .BuildServiceProvider();

                services.AddDbContext&lt;AppDbContext&gt;(options =&gt; 
                {
                    options.UseInMemoryDatabase(""testDb"");
                    options.UseInternalServiceProvider(serviceProvider);
                    options.EnableDetailedErrors();
                    options.EnableSensitiveDataLogging();
                });
            });
        }
</code></pre>

<p>While this works, the problem is that it doesn't enforce SQL queries and I already ran in multiple cases where integration tests show the feature works, but when trying to reproduce it with actual project running and having EF connected to SQL Server database, the feature fails because of some failed database constraint.</p>

<p>Ideas:</p>

<ul>
<li>At first I thought of using SQLite in memory database. Didn't work, I think it's some concurrency issue, because at the start of every test case, I wipe the database with <code>.EnsureDeleted()</code> <code>.EnsureCreated()</code> <code>.Migrate()</code></li>
<li>Then SQLite with files with random names. Didn't work, because I couldn't manage to wipe out internal DbContext Cache. I was sure that file was recreated and clean, but DbContext simply had cached entities.</li>
<li>Finally after some migrations I released that I wouldn't probably be able to use SQLite at all, because it doesn't support a lot of migration types (Removing FK, altering a column, etc.)/</li>
</ul>
",https://stackoverflow.com/questions/54750866/parallel-integration-testing-with-sql-database,"['c#', 'asp.net', 'entity-framework', 'xunit']",745,False,4,0
Integration testing ASP.NET Core with .NET Framework - can&#39;t find deps.json,"<p>I have a ASP.NET Core Web API project targeting .NET Framework 4.7 that I'm trying to write integration tests for. I created a unit test project using Visual Studio Add new project and then the Unit Test Project (.NET Framework) template. I added the Microsoft.AspNetCore.Mvc.Testing NuGet package to the test project, and I have the following test:</p>

<pre><code>using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TestRepro.Tests
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public async Task TestMethod1()
        {
            var factory = new WebApplicationFactory&lt;Startup&gt;();
            var client = factory.CreateClient();
            var response = await client.GetAsync(""/api/values"");
        }
    }
}
</code></pre>

<p>But this throws the following exception:</p>

<blockquote>
  <p>Test method TestRepro.Tests.UnitTest1.TestMethod1 threw exception: 
  System.InvalidOperationException: Can't find'[path removed]\TestRepro.Tests\bin\Debug\TestRepro.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 'true'. For functional tests to work they need to either run from the build output folder or the TestRepro.deps.json file from your application's output directory must be copied to the folder where the tests are running on. A common cause for this error is having shadow copying enabled when the tests run.</p>
</blockquote>

<p>I have verified that TestRepro.deps.json exists in the web application output folder (TestRepro\bin\Debug\net47), but it is not copied to the test project output folder (TestRepro.Tests\bin\Debug). And I have not been able to find out how to disable shadow copying.</p>

<p><strong>Edit:</strong> <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#aspnet-core-integration-tests"" rel=""noreferrer"">The documentation</a> says:</p>

<blockquote>
  <p>The Microsoft.AspNetCore.Mvc.Testing package handles the following tasks: Copies the dependencies file (*.deps) from the SUT into the test project's bin folder.</p>
</blockquote>

<p>But that doesn't seem to work. I can copy the file manually, but that doesn't work in a automated build scenario. One way would be to have a build step doing it in TeamCity, but it feels crude. Any ideas?</p>

<p>I have <a href=""https://github.com/henrik-olsson-valtech/TestRepro"" rel=""noreferrer"">a repro on GitHub</a> if that helps.</p>
",https://stackoverflow.com/questions/55131379/integration-testing-asp-net-core-with-net-framework-cant-find-deps-json,"['.net', 'asp.net-core', 'visual-studio-2017', 'integration-testing']",17282,True,32,8
DynamoDB fake server for integration testing,"<p>I am new to DynamoDB and I was wondering if there is any kind of embedded DynamoDB fake server available as a maven dependency/plugin, in order to run end-to-end tests as part of the maven build. E.g. something like <a href=""https://mvnrepository.com/artifact/info.archinnov/achilles/5.0.0"" rel=""nofollow noreferrer"">Achilles</a> but for DynamoDB instead of Cassandra. </p>

<p>Worth mentioning that I found <a href=""https://dynamodb.jcabi.com/index.html"" rel=""nofollow noreferrer"">this project</a>, but I found it to be too unstable and I was not able to get it to work.</p>

<p>Thank you for your help.</p>
",https://stackoverflow.com/questions/55710652/dynamodb-fake-server-for-integration-testing,"['java', 'maven', 'testing', 'amazon-dynamodb']",4662,True,3,2
Integration testing MultipartFile uploads with spring,"<p>I am trying to write integration tests for my Post endpoint.
This is part of a 2 part process where the Public endpoint feeds into the service endpoint which does the core of the work. 
This is the public endpoint so the response is mocked.</p>

<p>I am using springMVC and my code works fine, however when trying to use MockMvc.perform to do the post with content i seem to be getting a response with 'Required request part ""file"" is not present'.</p>

<p>In the code I use HttpEntity to send the file through to the service and that works, I can't see that working here though.</p>

<p>any help would be greatly appreciated. </p>

<pre><code>@PostMapping(""/save/image"")
public ResponseEntity saveImage(@RequestParam(""file"") MultipartFile image) 
{
// functionality
}
</code></pre>
",https://stackoverflow.com/questions/57142467/integration-testing-multipartfile-uploads-with-spring,"['java', 'spring-mvc', 'mockito']",1430,True,3,1
Reset RabbitMQ-node for integration testing,"<p>I am using RabbitMQ in a project and am running my integration tests against it. Since the tests need to be independent from each other, I would like to reset the RabbitMQ instance before each test and currently solve this by restarting the (automatically created) RabbitMQ docker container. However, this is extremely slow (for integration tests).</p>
<p>I know from <a href=""https://stackoverflow.com/q/11459676/898999"">this answer</a> that it's possible to reset the rabbitmq-instance with <code>rabbitmqctl stop &amp;&amp; rabbitmqctl reset &amp;&amp; rabbitmqctl start</code> - but in case of the docker-image, the stop-signal kills the main container process (which is rabbitmq-server), which in turn leads to dockerd killing the complete container.</p>
<p>The only solution I found so far is running the management-api-plugin, iterating over all queues, exchanges, policies, etc. and deleting them through that - which in turn takes a while as well and requires the management-plugin to run.</p>
<p><em>Is it possible to reset a running rabbitmq-node programmatically via AMQP, some other API-endpoint or running a command, without stopping it first?</em></p>
",https://stackoverflow.com/questions/56937107/reset-rabbitmq-node-for-integration-testing,"['docker', 'rabbitmq', 'integration-testing']",1628,True,3,1
Integration testing with event sourcing systems,"<p>I'm working on a PoC where we use CQRS in combination with Event Sourcing. We use the Axon framework and Axon server as toolset.</p>

<p>We have some microservices (Maven packages) with some business logic.</p>

<p>A simple overview of the application flow:</p>

<p>We post a xml message (with REST) to service 1 that will result in an event (with Aggregate). 
Service 2 handles the event ""fired"" by service 1 and starts a saga flow. Part of the sage flow is for example to send a mail message.</p>

<p>I can do some tests with Axon Test to test the aggregate from service 1 or the saga from service 2. But is there a good option to do a real integration test where we start with posting a message to the REST interface and check all the operations in the aggregate and saga (inclusive sending mail and so on)</p>

<p>Maybe this kind of integration test is overdone and it's better to test each component on it's own. I doubt what's needed / the best solution to test this type of system.</p>
",https://stackoverflow.com/questions/56067305/integration-testing-with-event-sourcing-systems,"['testing', 'integration-testing', 'event-sourcing', 'axon']",1594,True,2,2
Integration Testing - Microservice calling each other,"<p>I'm having trouble with running integration test on my application.</p>

<p>I'm trying to write a test on controller that calls another api controller in same solution.</p>

<p>So basicly i have two APIS one calling other in same solution. </p>

<p>I know how to test one API but i can't seem to figure out how to run the other API.</p>

<p>I have tried building two seperate TestServers with different startup. But nothing seems to trigger other api.</p>

<p>Any pointers will be deeply appreciated.</p>

<pre><code>    [TestInitialize]
    public void Init()
    {
        var builder = new WebHostBuilder()
            .UseConfiguration(new ConfigurationBuilder()
            .AddJsonFile(""appsettings.json"")
            .Build())
            .UseStartup&lt;Startup&gt;();
        _server = new TestServer(builder);
        _client = _server.CreateClient();
    }


    [TestMethod]
    public void TestUser()
    {
        var request = _client.GetAsync(""/api/v1/"").Result;
        var jsonString = request.Content.ReadAsStringAsync().Result;
        var result = JsonConvert.DeserializeObject&lt;bool&gt;(jsonString);
        Assert.IsNotNull(result);
    }




    public async Task&lt;bool?&gt; GetUser()
    {
        bool? result = null;
        HttpResponseMessage response = await _client.GetAsync(""/"");
        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();
            result = JsonConvert.DeserializeObject&lt;bool&gt;(responseContent);
        }
        return result;

    }
</code></pre>
",https://stackoverflow.com/questions/58096150/integration-testing-microservice-calling-each-other,"['c#', 'testing', '.net-core']",97,False,1,0
Integration testing async DOM event handlers,"<p>I've inherited a decent number of integration tests which simulate mouse/touch events against DOM elements and assert application state periodically while the resulting action is performed.</p>

<p>A common problem throughout these tests is a failure to wait for the full completion of async behavior resulting in unintended side-effects.</p>

<p>Consider the following:</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>const LoadState = {
  Pending: 'pending',
  Loaded: 'loaded',
  Failed: 'failed'
};

const App = {
  state: {
    loadState: LoadState.Pending,
    renderAnimationFrameId: null
  },
  
  ui: {
    loadState: document.getElementById('load-state'),
    loadButton: document.getElementById('load-button')
  },
  
  initialize() {
    this._load = this._load.bind(this);
    this.ui.loadButton.addEventListener('click', this._load);
  },
  
  render() {
    // Throttle rendering to framerate.
    if (this.state.renderAnimationFrameId) {
      return;
    }
  
    this.state.renderAnimationFrameId = requestAnimationFrame(() =&gt; {
      this.ui.loadState.textContent = this.state.loadState;
      this.state.renderAnimationFrameId = null;
    });
  },
  
  _load() {
    window.fetch(new Request('flowers.jpg')).then(({ ok }) =&gt; {
      this.state.loadState = ok ? LoadState.Loaded : LoadState.Failed;
    }).catch(() =&gt; {
      this.state.loadState = LoadState.Failed;
    }).finally(() =&gt; {
      this.render();
    });
  }
};

App.initialize();
App.render();</code></pre>
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;input id='load-button' type=""button"" value=""Load Data"" /&gt;

&lt;div id='load-state'&gt;
  Pending
&lt;/div&gt;</code></pre>
</div>
</div>
</p>

<p>Assuming a mocked implementation of <code>fetch</code>, I would like to verify that <code>load-button</code> reacts properly to being clicked and that <code>App</code> properly updates afterward. Something like this is written fairly intuitively:</p>

<pre><code>window.fetch = Promise.resolve(true);
describe('App', () =&gt; {
    App.initialize();

    it('should load', (done) =&gt; {
        App.ui.loadButton.dispatchEvent(new Event('click'));

        // Wait for event to update state after fetch resolution.
        setTimeout(() =&gt; {
            expect(App.state.loadState === LoadState.Loaded);
            done();
        });
    });

    it('should render', (done) =&gt; {
        App.render();

        // Wait for throttled render
        setTimeout(() =&gt; {
            expect(App.state.renderAnimationFrameId === null);
            expect(App.ui.loadState.textContent === LoadState.Loaded);
            done();
        });
    });
});
</code></pre>

<p>These tests introduce a subtle bug. The first test has partially waited, but not fully waited, for App's asynchronous logic to settle.The test passes because <code>state.loadState</code> is correct, but a call to <code>render</code> is still in-flight. The second test may exhibit erratic results due to this.</p>

<p>I'm wondering what appropriate responses to this might be. Some proposed solutions include:</p>

<ul>
<li><p>Mock <code>setTimeout</code>, <code>setInterval</code>, <code>requestAnimationFrame</code> and enqueue their callbacks instead of executing asynchronously. Allow for synchronous play-forward of callbacks. Very magical &amp; error-prone solution, promises still asynchronous and need to be handled separately</p></li>
<li><p>Rewrite production code to ensure all pending promises are publicly exposed. This makes using <code>async</code> and <code>await</code> much more challenging and unintuitive.</p></li>
<li><p>Spy on <code>setTimeout</code>, <code>setInterval</code>, <code>requestAnimationFrame</code>, and <code>Promise</code> , try to infer what async behavior is still pending as a result of a method being ran, determine async resolution by polling spies. This is less complex than the above, but race conditions and third-party code becomes more difficult to debug, and unclear how using <code>await</code> or <code>yield</code> would work.</p></li>
</ul>

<p>Maybe there are other options? Basically it's unclear whether it should be the app's responsibility to make async functionality exposed properly, or if the burden is fully on the testing environment. If on the testing environment, does it make sense to fully control async behavior, or is a strictly reactionary approach preferred?</p>

<p>TL;DR: Mouse/touch event handlers are async and have no need to expose their internals. What's an appropriate response in order to support testing needs?</p>
",https://stackoverflow.com/questions/56961638/integration-testing-async-dom-event-handlers,"['javascript', 'asynchronous', 'testing']",38,False,1,0
Integration testing a node.js socket.io server,"<p>I'm trying to set up a server to respond to socket.io clients using nodejs, express and socket.io. I want to write tests to probe the server and make sure it's handling the events correctly and sending appropriate responses to the client.</p>

<p>I tried writing some automated tests using jest but I couldn't figure out how to actually emit events to the server and have it respond.</p>

<p><a href=""https://stackoverflow.com/questions/15509231/unit-testing-node-js-and-websockets-socket-io"">Unit testing Node.js and WebSockets (Socket.io)</a></p>

<p>I checked out the above post but it didn't work for me...</p>
",https://stackoverflow.com/questions/54390971/integration-testing-a-node-js-socket-io-server,"['node.js', 'unit-testing', 'testing', 'socket.io', 'automated-tests']",3344,True,1,1
Integration testing EF Core + AutoMapper ProjectTo,"<p>I'm trying to integration test a service class that uses AutoMapper and the ProjectTo extension method. In the application itself, I am injecting an IMapper via ASP.Net Core's built-in DI framework. All of this seems to be configured correctly as the app itself works. For example, my service class resembles this</p>

<pre><code>public class MyServiceClass
{
    private readonly IMapper _mapper;
    private readonly MyDbContext _context;
    public MyServiceClass(IMapper mapper, MyDbContext context)
    {
        _mapper = mapper;
        _context = context;
    }

    public MyModelDto GetMyModel()
    {
        var myModelDto = _context.MyModels.ProjectTo&lt;MyModelDto&gt;().FirstOrDefault();
        return myModelDto;
    }
}
</code></pre>

<p>Now, I want to integration test this service i.e. new it up in an Xunit test (without ASP.Net DI framework since it's a unit test project) and have it actually run the query against a test database. My unit test looks something like this</p>

<pre><code>public class MyServiceClassTests
{
    [Fact]
    public void GetMyModelTest()
    {
        // Arrange
        var context = new MyDbContext();
        var config = new MapperConfiguration(cfg =&gt;
        {
            cfg.AddProfile&lt;MyModelProfile&gt;();
        });
        var mapper = new Mapper(config);
        var sut = new MyServiceClass(mapper, context);

        // Act
        var results = sut.GetMyModel();

        // Assert
        Assert.NotNull(results);
    }
}
</code></pre>

<p>I get the following exception:</p>

<pre><code>Error Message:
 System.InvalidOperationException : Mapper not initialized.
 Call Initialize with appropriate configuration. 
If you are trying to use mapper instances through a container or otherwise,
 make sure you do not have any calls to the static Mapper.Map methods,
 and if you're using ProjectTo or UseAsDataSource extension methods,
 make sure you pass in the appropriate IConfigurationProvider instance.
</code></pre>

<p>Emphasis on <strong>if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.</strong></p>

<p>Of course, I don't want to change all of my uses of ProjectTo&lt;> to pass in an IConfigurationProvider, I want to continue using the parameterless version. There's something that the services.AddAutoMapper() extension is doing that is not being replicated when I construct my own instance of IMapper in my unit test.</p>

<p>Is there anything I can do to make this work the way I think it ought to work?</p>
",https://stackoverflow.com/questions/54451046/integration-testing-ef-core-automapper-projectto,"['c#', 'entity-framework-core', 'automapper']",545,False,0,0
IdentityServer4 Integration Testing with InMemory Stores,"<p>I'm writing an integration test for my microservices authentication and authorization. I am using IdentityServer4 with in-memory stores and my code looks like this; </p>

<p>EDIT: I have added the SQLite in memory setup that I am using. Not sure if I need that for IS4 InMemory stores.</p>

<pre><code>var builder = services
    .AddIdentityServer(options =&gt;
    {
        options.IssuerUri = ""https://my.services.is4host"";
        options.Events.RaiseErrorEvents = true;
        options.Events.RaiseInformationEvents = true;
        options.Events.RaiseFailureEvents = true;
        options.Events.RaiseSuccessEvents = true;
    });

var migrationAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;  

var inMemorySqlite = new SqliteConnection(""Data Source=:memory:"");
inMemorySqlite.Open();

services
    .AddDbContext&lt;SecurityDbContext&gt;(
        options =&gt; options.UseSqlite(inMemorySqlite,
            sql =&gt; sql.MigrationsAssembly(migrationAssembly)));

// Migrate the database
var context = services.BuildServiceProvider().GetService&lt;SecurityDbContext&gt;();
context.Database.Migrate();

builder
    .AddInMemoryClients(IS4Config.GetClients())
    .AddInMemoryIdentityResources(IS4Config.GetIdentityResources())
    .AddInMemoryApiResources(IS4Config.GetAPIResources())
    .AddTestUsers(new List&lt;TestUser&gt;
    {
            new TestUser {
                SubjectId = Guid.NewGuid().ToString(),
                Claims = new List&lt;Claim&gt; {
                    new Claim(JwtClaimTypes.Subject, MyDemoUser.ElevatedUser.UserName),
                    new Claim(JwtClaimTypes.Email, MyDemoUser.ElevatedUser.Email),
                    new Claim(JwtClaimTypes.Role, MyDemoUser.ElevatedUser.Roles[0]),
                    new Claim(JwtClaimTypes.Role, MyDemoUser.ElevatedUser.Roles[1])
                },
                IsActive = true,
                Password = MyDemoUser.ElevatedUser.Password,
                Username = MyDemoUser.ElevatedUser.UserName
            },
            new TestUser {
                SubjectId = Guid.NewGuid().ToString(),
                Claims = new List&lt;Claim&gt; {
                    new Claim(JwtClaimTypes.Subject, MyDemoUser.WorkstationUser.UserName),
                    new Claim(JwtClaimTypes.Email, MyDemoUser.WorkstationUser.Email),
                    new Claim(JwtClaimTypes.Role, MyDemoUser.WorkstationUser.Roles[0])
                },
                IsActive = true,
                Password = MyDemoUser.WorkstationUser.Password,
                Username = MyDemoUser.WorkstationUser.UserName
            }
    });
</code></pre>

<p>and my test looks like this;</p>

<pre><code>var is4Host = new WebApplicationTestFactory&lt;Services.IS4Host.Startup&gt;();
var client = is4Host.CreateClient();

var disco = await client.GetDiscoveryDocumentAsync(""https://My.services.is4host"");
if (disco.IsError)
{
    Console.WriteLine(disco.Error);
    return false;
}

// request token
var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
    Address = disco.TokenEndpoint,
    ClientId = MyClient.ClientId,
    ClientSecret = MyClient.ClientSecret,
    Scope = MyApiResource.Gateway.Name,
    UserName = user.UserName,
    Password = user.Password
});

if (tokenResponse.IsError)
{
    Console.WriteLine(tokenResponse.Error);
    return false;
}

Console.WriteLine(tokenResponse.Json);
Console.WriteLine(""\n\n"");

return true;
</code></pre>

<p>I am adding records into the in memory stores but I keep getting the response below from IS4</p>

<pre><code>{
  ""error"": ""invalid_grant"",
  ""error_description"": ""invalid_username_or_password""
}
</code></pre>
",https://stackoverflow.com/questions/54262500/identityserver4-integration-testing-with-inmemory-stores,"['asp.net-core', '.net-core', 'identityserver4']",300,False,0,0
SpringBoot Integration testing Sybase and Testcontainers,"<p>Is it possible to use a sybase database with Testcontainers to do the integration testing with spring boot?</p>

<p>I can not install docker on my local machine.</p>
",https://stackoverflow.com/questions/55927232/springboot-integration-testing-sybase-and-testcontainers,"['java', 'spring-boot', 'integration-testing', 'junit5', 'testcontainers']",369,True,0,1
ASP.NET Core Integration Testing &amp; Mocking using Moq,"<p>I have the following <a href=""https://learn.microsoft.com/en-gb/aspnet/core/test/integration-tests?view=aspnetcore-2.2"" rel=""noreferrer"">ASP.NET Core integration test</a> using a custom <code>WebApplicationFactory</code> </p>



<pre class=""lang-cs prettyprint-override""><code>public class CustomWebApplicationFactory&lt;TEntryPoint&gt; : WebApplicationFactory&lt;TEntryPoint&gt;
    where TEntryPoint : class
{
    public CustomWebApplicationFactory()
    {
        this.ClientOptions.AllowAutoRedirect = false;
        this.ClientOptions.BaseAddress = new Uri(""https://localhost"");
    }

    public ApplicationOptions ApplicationOptions { get; private set; }

    public Mock&lt;IClockService&gt; ClockServiceMock { get; private set; }

    public void VerifyAllMocks() =&gt; Mock.VerifyAll(this.ClockServiceMock);

    protected override TestServer CreateServer(IWebHostBuilder builder)
    {
        this.ClockServiceMock = new Mock&lt;IClockService&gt;(MockBehavior.Strict);

        builder
            .UseEnvironment(""Testing"")
            .ConfigureTestServices(
                services =&gt;
                {
                    services.AddSingleton(this.ClockServiceMock.Object);
                });

        var testServer = base.CreateServer(builder);

        using (var serviceScope = testServer.Host.Services.CreateScope())
        {
            var serviceProvider = serviceScope.ServiceProvider;
            this.ApplicationOptions = serviceProvider.GetRequiredService&lt;IOptions&lt;ApplicationOptions&gt;&gt;().Value;
        }

        return testServer;
    }
}
</code></pre>

<p>which looks like it should work but the problem is that the <code>ConfigureTestServices</code> method is never being called, so my mock is never registered with the IoC container. You can find the full source code <a href=""https://github.com/Dotnet-Boxed/Templates/tree/cursor-paging-in-api-template/Source/ApiTemplate"" rel=""noreferrer"">here</a>.</p>

<pre class=""lang-cs prettyprint-override""><code>public class FooControllerTest : IClassFixture&lt;CustomWebApplicationFactory&lt;Startup&gt;&gt;, IDisposable
{
    private readonly HttpClient client;
    private readonly CustomWebApplicationFactory&lt;Startup&gt; factory;
    private readonly Mock&lt;IClockService&gt; clockServiceMock;

    public FooControllerTest(CustomWebApplicationFactory&lt;Startup&gt; factory)
    {
        this.factory = factory;
        this.client = factory.CreateClient();
        this.clockServiceMock = this.factory.ClockServiceMock;
    }

    [Fact]
    public async Task Delete_FooFound_Returns204NoContent()
    {
        this.clockServiceMock.SetupGet(x =&gt; x.UtcNow).ReturnsAsync(new DateTimeOffset.UtcNow);

        var response = await this.client.DeleteAsync(""/foo/1"");

        Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
    }

    public void Dispose() =&gt; this.factory.VerifyAllMocks();
}
</code></pre>
",https://stackoverflow.com/questions/57577045/asp-net-core-integration-testing-mocking-using-moq,"['asp.net-core', 'asp.net-core-mvc', 'moq', 'xunit', 'asp.net-core-testhost']",12580,True,11,3
spring Kafka integration testing with embedded Kafka,"<p>I have spring boot application that had a consumer consumes from topic in one cluster and produces to another topic in different cluster.</p>
<p>Now I'm trying to write integration test case using spring embedded Kafka but having an issue <code>KafkaTemplate could not be registered. A bean with that name has already been defined in class path resource</code></p>
<p><strong>Consumer Class</strong></p>
<pre><code>@Service
public class KafkaConsumerService {

@Autowired
private KafkaProducerService kafkaProducerService;

@KafkaListener(topics = &quot;${kafka.producer.topic}&quot;)
public void professor(List&lt;Professor&gt; pro) {
    pro.forEach(kafkaProducerService::produce);
    
   }

}
</code></pre>
<p><strong>Producer Class</strong></p>
<pre><code>@Service
public class KafkaProducerService {

@Value(&quot;${kafka.producer.topic}&quot;)
private String topic;

@Autowired
private KafkaTemplate&lt;String, Object&gt; kafkaTemplate;

public void produce(Professor pro) {
    kafkaTemplate.send(topic,&quot;professor&quot;,pro);
  }

 }
</code></pre>
<p>In my Test cases I want to override <code>KafkaTemplate</code> so that when i call <code>kafkaConsumerService.professor</code> method in <code>Test</code> it should produce the data into embedded Kafka and i should validate it.</p>
<p><strong>Test config</strong></p>
<pre><code>@TestConfiguration
@EmbeddedKafka(partitions = 1, controlledShutdown = false,
brokerProperties = {&quot;listeners=PLAINTEXT://localhost:3333&quot;, &quot;port=3333&quot;})
public class KafkaProducerConfigTest {

@Autowired
 KafkaEmbedded kafkaEmbeded;

@Autowired
KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;

@Before
public void setUp() throws Exception {
  for (MessageListenerContainer messageListenerContainer : kafkaListenerEndpointRegistry.getListenerContainers()) {
    ContainerTestUtils.waitForAssignment(messageListenerContainer, 
    kafkaEmbeded.getPartitionsPerTopic());
  }
}

@Bean
public ProducerFactory&lt;String, Object&gt; producerFactory() {
    return new DefaultKafkaProducerFactory&lt;&gt;(KafkaTestUtils.producerProps(kafkaEmbeded));
}

@Bean
public KafkaTemplate&lt;String, Object&gt; kafkaTemplate() {
    KafkaTemplate&lt;String, Object&gt; kafkaTemplate = new KafkaTemplate&lt;&gt;(producerFactory());
    return kafkaTemplate;
   }

 }
</code></pre>
<p><strong>Test class</strong></p>
<pre><code>@EnableKafka
@SpringBootTest(classes = {KafkaProducerConfigTest.class})
@RunWith(SpringRunner.class)
public class KafkaProducerServiceTest {

@Autowired
private KafkaConsumerService kafkaConsumerService;

@Test
public void testReceive() throws Exception {
     kafkaConsumerService.professor(Arrays.asList(new Professor()));
     
     //How to check messages is sent to kafka?
}

 }
</code></pre>
<p><strong>Error</strong></p>
<pre><code> The bean 'kafkaTemplate', defined in com.kafka.configuration.KafkaProducerConfigTest, could not be registered. 
 A bean with that name has already been defined in class path resource [com/kafka/configuration/KafkaProducerConfig.class] and overriding is disabled.
 Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
</code></pre>
<hr />
<p>And also can some one help me how to validate messages sent into embedded Kafka server?</p>
<p><strong>Note</strong> I'm having some deprecated warnings</p>
<blockquote>
<p>The type KafkaEmbedded is deprecated</p>
<p>The method getPartitionsPerTopic() from the type KafkaEmbedded is deprecated</p>
<p>The method producerProps(KafkaEmbedded) from the type KafkaTestUtils is deprecated</p>
</blockquote>
",https://stackoverflow.com/questions/54754662/spring-kafka-integration-testing-with-embedded-kafka,"['java', 'spring-boot', 'apache-kafka', 'spring-kafka', 'spring-kafka-test']",16597,True,2,1
Integration Testing Spring boot application JSON Assert,"<p>I have spring boot application was trying to write Integration testing but when i ht the in memory DB i get one value from that but when do ASSERT TO MATCH THE PARAMETER VALUES i AM  NOT ABLE TO COMPARE THE SIZE AND VALUES </p>

<p>these how the response when i hit the api in Postman </p>

<pre><code>{
    ""continuationToken"": ""09/07/19 05:21 PM"",
    ""permit"": [
        {
            ""expiry"": null,
            ""activation"": ""2019-07-01T06:00:00.000+0000"",
            ""permitId"": ""C8S43N5"",
            ""plateNumber"": ""ERT1234"",
            ""plateState"": ""AB""
        },
        {
            ""expiry"": null,
            ""activation"": ""2018-12-17T22:04:13.947+0000"",
            ""permitId"": ""CGW3TNF"",
            ""plateNumber"": ""FDF"",
            ""plateState"": ""AB""
        }
  ]
}
</code></pre>

<pre><code>        Assert.assertThat(response.getStatusCode(), Matchers.equalTo(HttpStatus.OK));
        String jsonBody = response.getBody();
        Assert.assertThat(jsonBody, JsonPathMatchers.hasJsonPath(""$[0].expiry"", Matchers.equalTo(""2080-06-26T06:00:00.000+0000"")));
        Assert.assertThat(jsonBody, JsonPathMatchers.hasJsonPath(""$[0].activation"", Matchers.equalTo(""2019-06-26T22:33:14.849+0000"")));
        Assert.assertThat(jsonBody, JsonPathMatchers.hasJsonPath(""$[0].permitId"", Matchers.equalTo(""CS383UA"")));
        Assert.assertThat(jsonBody, JsonPathMatchers.hasJsonPath(""$[0].plateNumber"", Matchers.equalTo(""VGZ05"")));
        Assert.assertThat(jsonBody, JsonPathMatchers.hasJsonPath(""$[0].plateState"", Matchers.equalTo(""AB"")));
</code></pre>

<blockquote>
  <p>java.lang.AssertionError:  Expected: is json with json path
  ""$[0]['expiry']"" evaluated to ""2080-06-26T06:00:00.000+0000""
       but: json path ""$[0]['expiry']"" was not found in &lt;{continuationToken=09/07/19 05:31 PM,
  permit=[{""expiry"":""2080-06-26T06:00:00.000+0000"",""activation"":""2019-06-26T22:33:14.849+0000"",""permitId"":""CS383UA"",""plateNumber"":""VGZ05"",""plateState"":""AB""}]}></p>
</blockquote>
",https://stackoverflow.com/questions/56958031/integration-testing-spring-boot-application-json-assert,['java'],799,True,1,1
"Integration testing with Spring, ActiveMQ and Qpid","<p>In the project I have to replace ActiveMQ client with Qpid, but with keeping activeMQ broker. Due to that change many tests are failing, especially integration tests.</p>

<p>Before I was using vm connection, like:</p>

<pre><code>vm://localhost:61616
</code></pre>

<p>However, since I want to use AMQP with Qpid, the connection has to be changed on following one:</p>

<pre><code>amqp://localhost:5672
</code></pre>

<p>I'm mocking my server using <code>DefaultMessageListenerContainer</code> and I'm executing connections with <code>JmsTemplate</code>. </p>

<p>When I'm running the test trying to create AMQP connection, I'm getting following exception:</p>

<pre><code>ERROR o.a.qpid.jms.JmsConnectionFactory - Failed to create JMS Provider instance for: amqp
javax.jms.JMSException: Connection refused: /0.0.0.0:5672
    at org.apache.qpid.jms.exceptions.JmsExceptionSupport.create(JmsExceptionSupport.java:77)
    at org.apache.qpid.jms.JmsConnectionFactory.createConnection(JmsConnectionFactory.java:183)
    at org.apache.qpid.jms.JmsConnectionFactory.createConnection(JmsConnectionFactory.java:165)
    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.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:363)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:307)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:419)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1737)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1239)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:855)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:758)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1308)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1154)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:224)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1114)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveBean(DefaultListableBeanFactory.java:407)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:341)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:335)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1101)
    at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:120)
    at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:96)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:419)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1737)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:275)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:243)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
    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.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    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.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: /0.0.0.0:5672
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
    at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:352)
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:340)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:632)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:579)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:496)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458)
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
    at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138)
    at java.lang.Thread.run(Thread.java:748)
    Caused by: java.net.ConnectException: Connection refused
    ... 11 common frames omitted
</code></pre>

<p>I modified all code to make sure that I'm using Qpid client with AMQP, broker has transport connector for AMQP as well. </p>

<p>What am I missing? Or is it just impossible to mock connection with AMQP?</p>
",https://stackoverflow.com/questions/55265261/integration-testing-with-spring-activemq-and-qpid,"['jms', 'activemq', 'amqp', 'qpid']",635,False,1,1
How to do integration testing in Flutter?,"<p>I want to do integration testing in Flutter. The tutorial I follow gives the following procedure:</p>

<ol>
<li>Add the flutter_driver package to pubspec:</li>
</ol>

<pre><code>dev_dependencies:
flutter_driver:
sdk: flutter
</code></pre>

<ol start=""2"">
<li>Enable the Flutter driver extension and add a call to
the enableFlutterDriverExtension() function in main.dart.</li>
<li>Run the integration test by using the flutter drive command:
flutter drive --target=my_app/test_driver/my_test.dart</li>
</ol>

<p>My problem is with understanding step 2. It's not clear to me where in Android Studio do you enable the driver extension and where exactly in main.dart do you call the function enableFlutterDriveExtension().</p>

<p>I also have problems with the third step. After running the said command, it says in my terminal that </p>

<pre><code>Error: The Flutter directory is not a clone of the GitHub project.
       The flutter tool requires Git in order to operate properly;
       to set up Flutter, run the following command:
       git clone -b stable https://github.com/flutter/flutter.git
</code></pre>
",https://stackoverflow.com/questions/56104378/how-to-do-integration-testing-in-flutter,"['flutter', 'flutter-dependencies']",2952,True,1,2
Database triggers not working in integration testing,"<p>I have created database triggers to manage the created and updated timestamps in my Postgres schema for my Spring boot application. When I run my integration tests, I see the created and updated field are not changed by the triggers and are still null. I am running my integration tests using docker-compose. I managing the table versioning &amp; migrations with Flyway. I created the table initially and adding the trigger(mentioned below) later with another migration script. Is there a way to test the trigger functions or anything wrong with my trigger function?</p>

<p>Here is the trigger function:</p>

<pre><code>CREATE OR REPLACE FUNCTION set_created_updated_dates()
  RETURNS TRIGGER AS
$$
BEGIN
  IF (TG_OP = 'INSERT') THEN
    NEW.created := CURRENT_TIMESTAMP;
    NEW.updated := CURRENT_TIMESTAMP;
  ELSIF (TG_OP = 'UPDATE') THEN
    NEW.updated := CURRENT_TIMESTAMP;
  END IF;

  RETURN NEW;
END;
$$
  LANGUAGE plpgsql;
</code></pre>

<p>routings is the name of my table:</p>

<pre><code>CREATE TRIGGER routings_set_created_updated_dates
  BEFORE INSERT OR UPDATE
  ON routings
  FOR EACH ROW
EXECUTE PROCEDURE set_created_updated_dates();
</code></pre>

<p>Here is my docker compose file:</p>

<pre><code>version: '3'
services:
  mockserver:
    image: ""artifactory.random/docker/jamesdbloom/mockserver:mockserver-5.5.1""
    ports:
      - 1080
  database:
    image: postgres:10.5
    environment:
      - POSTGRES_DB=test
      - POSTGRES_USER=test
      - POSTGRES_PASSWORD=test123
    ports:
      - 5432
</code></pre>
",https://stackoverflow.com/questions/57477825/database-triggers-not-working-in-integration-testing,"['java', 'postgresql', 'docker-compose', 'integration-testing', 'database-trigger']",520,False,0,0
Configure two ports for springboot integration testing,"<p>Im pretty new to spring framework and my JAVA application(Say Project_A) running at <a href=""http://localhost:8080"" rel=""nofollow noreferrer"">http://localhost:8080</a>, does processing and forwards the processed content to <a href=""http://localhost:9090"" rel=""nofollow noreferrer"">http://localhost:9090</a> where another application(Say Project_B) is running. Project_B replies back to Project_A and then Project_A forwards the content outside . </p>

<p>Im now trying to write integration test for Project_A , so need two mocks, one at the request side and the other at Project_B side . For request, I can make use of MockMVC to simulate request and send . But for simulating the Project_B , Im thinking of creating a mock controller which receives requests from Project_A and send replies accordingly . So for that, I need to create another Controller running in different port . The default port in project_A is 8080 and in my new controller mock I need to use 9090. </p>

<p>Is there a way to use two different ports in one spring junit application ? Or any better way to achieve it with spring unit testing itself ?</p>
",https://stackoverflow.com/questions/54746122/configure-two-ports-for-springboot-integration-testing,"['spring', 'spring-boot', 'spring-mvc', 'integration-testing', 'spring-test-mvc']",1054,False,1,2
Integration testing between web application and WebAPI,"<p>I am using <code>WebApplicationFactory&lt;TStartup&gt;</code> for integration testing  of a .NET Core 3.0 web application.<br>
It works when it  need to test just one web application.   </p>

<p>But what if  web application need to send request to WebAPI application. I need somehow to instantiate both <code>WebApplicationFactory&lt;Web.Startup&gt;</code> and <code>WebApplicationFactory&lt;Api.Startup&gt;</code>.   </p>

<p>I tried different alternatives with no luck. 
Can anybody with experience of similar task point a right way to me.</p>

<p>P.S. Inside web application there is injected internal <code>HttpClient</code> that used internally in Controllers to send requests to API:</p>

<pre class=""lang-cs prettyprint-override""><code>services.AddHttpClient&lt;IInternalApiClient, InternalApiClient&gt;();
</code></pre>
",https://stackoverflow.com/questions/58486057/integration-testing-between-web-application-and-webapi,"['c#', 'asp.net-core', 'integration-testing', 'asp.net-core-webapi']",304,False,0,1
Spring Integration testing doesn&#39;t use security configuration,"<p>I am new to integration testing and doing everything everything as in tutorials. 
My security config:</p>

<pre><code>@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers(""/ticket/create"")
                .access(""hasAnyAuthority('MANAGER','EMPLOYEE')"")
                .and().authorizeRequests().antMatchers(""/api/**"",""/ticket/*"")
                .access(""isAuthenticated()"")
                .and().formLogin().loginPage(""/login"").failureUrl(""/login?error"")
                .and().formLogin().defaultSuccessUrl(""/ticket/all"", true)
                .usernameParameter(""email"")
                .passwordParameter(""password"")
                .and().csrf().disable();
    }
</code></pre>

<p>All of my app requires login.</p>

<p>Now i'm trying to run a simple test to view main page of my app which: /ticket/all</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebAppInit.class, WebMvcConfig.class, WebSecurityConfig.class, HibernateConfig.class, SecurityWebApplicationInitializer.class})
@WebAppConfiguration
public class TicketLoginControllerTest extends TestCase {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    @Before
    public void setup() throws Exception {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testTicketOverviewAll() throws Exception {
        mockMvc.perform(get(""/ticket/all""))
                .andExpect(status().isOk());

    }
}
</code></pre>

<p>Test pass, even though i'm not authenticated.</p>

<p>Now my url: /ticket/create is forbidden for role ENGINEER</p>

<p>but when i try </p>

<pre><code>@Test
public void testTicketOverviewAll() throws Exception {
    mockMvc.perform(get(""/ticket/create""))
            .andExpect(status().isOk());

}
</code></pre>

<p>it still ok, when it should be 401 forbidden even if logged in.</p>

<p>I'm probably doing something wrong with test configuration but i don't know what exactly. Any help apreciated. 
If i just run my server and try all of the above, it will work as i expect it to work.</p>
",https://stackoverflow.com/questions/58166827/spring-integration-testing-doesnt-use-security-configuration,"['spring-mvc', 'junit', 'spring-security', 'integration-testing']",88,True,0,1
Integration testing deployed services using &quot;helm test&quot;,"<p>I'm using helm charts to deploy several REST services to Microsoft Azure. 
Some of these services communicate with each other and to some databases. After the deployment I want to test if ""everything"" works as expected. To be more precise, I want to send some HTTP requests to one of the services and check if the response makes sense. In automated tests of course.</p>

<p>I saw that it's possible to run basic commands after the deployment using <a href=""https://helm.sh/docs/developing_charts/#chart-tests"" rel=""nofollow noreferrer"">""helm test""</a>, but this is not exactly what I need.</p>

<p>In some earlier approach I used <a href=""https://learning.getpostman.com/docs/postman/collection_runs/command_line_integration_with_newman/"" rel=""nofollow noreferrer"">Newman</a> to execute a <a href=""https://www.getpostman.com/"" rel=""nofollow noreferrer"">Postman</a> collection in a script after the deployment.
The Postman collection defined several requests and the corresponding tests.</p>

<p>Now I don't know how to do it in the new environment (Azure) and deployment pipeline (helm, k8s).</p>

<p>It would be nice to have something like this again.
But for me it's not clear how to do it, e.g. </p>

<ul>
<li>how can I use Newman in the ""helm test"" scope?</li>
<li>how can I ensure, that the deployed Pods are all ""Running"" before starting the test (some wait time? status check?)?</li>
</ul>

<p><code>newman run ""test.postman_collection.json"" -e ""azure.postman_environment.json"" --bail</code></p>
",https://stackoverflow.com/questions/56688514/integration-testing-deployed-services-using-helm-test,"['java', 'kubernetes', 'postman', 'kubernetes-helm', 'newman']",3496,True,0,2
Spring boot integration testing not working JUnit5,"<p>I am trying to do integration testing in spring boot application using JUnit5 but it gives me Null Pointer Exception at that line <code>String response = restTemplate.getForObject(""/v1/students"", String.class);</code>. All unit tests are working fine but I can't figure out what's wrong with the integration test.
Here is the Integration Test class:</p>

<pre><code>package com.demo.student.demo;

import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class DemoApplicationTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void contextLoads() throws Exception {
        String response = restTemplate.getForObject(""/v1/students"", String.class);
        JSONAssert.assertEquals(""[{'id':1,'email':'test@test.test'}]"", response, false);
    }

}
</code></pre>

<p>Here is the stacktrace:</p>

<pre><code>java.lang.NullPointerException
    at com.demo.student.demo.DemoApplicationTest.contextLoads(DemoApplicationTest.java:18)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:513)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:170)
    at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:166)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:113)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:113)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:121)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:121)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
    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)
</code></pre>

<p>And the REST endpoint I am testing against:</p>

<pre><code>package com.demo.student.demo.service;

import com.demo.student.demo.entity.Student;
import com.demo.student.demo.exception.StudentNotFoundException;
import com.demo.student.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class StudentServiceImpl implements StudentService {

    private StudentRepository studentRepository;

    @Autowired
    public StudentServiceImpl(StudentRepository studentRepository){
        this.studentRepository = studentRepository;
    }

    @Override
    public List&lt;Student&gt; findAl() {
        return studentRepository.findAll();
    }

    @Override
    public Student findById(long id) {
        return  studentRepository.findById(id).orElseThrow(() -&gt; new StudentNotFoundException(id));
    }

    @Override
    public Student saveOrUpdate(Student student) {
        studentRepository.save(student);
        return student;
    }

    @Override
    public void deleteById(long id) {
        if(this.findById(id) != null)
            studentRepository.deleteById(id);
    }

}
</code></pre>
",https://stackoverflow.com/questions/59057032/spring-boot-integration-testing-not-working-junit5,"['spring', 'spring-boot', 'integration-testing', 'junit5']",1329,False,0,1
Integration testing .NET Code 2.2 IHostBuilder (Generic Host Builder),"<p>I am using .NET Core 2.2 IHostBuilder (Generic Host Builder) to build a console app running message streaming app as a BackgroundService (IHostedService).
 <a href=""https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.2"" rel=""noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.2</a></p>

<p>This is not the IWebHostBuilder that is typically used for hosting an ASP.NET Core web app.</p>

<p>I'd like to build some basic integration test to validate graceful shutdowns and the IoC configuration. I want to start a TestServer that hosts my IHostBuilder host. I don't need to serve any kinds of request.</p>

<p>I've done this kind of thing with IWebHostBuilder and TestServer in Microsoft.AspNetCore.TestHost. However, there is no support for IHostBuilder, only IWebHostBuilder.  <a href=""https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.testhost.testserver.-ctor?view=aspnetcore-2.2#Microsoft_AspNetCore_TestHost_TestServer__ctor_Microsoft_AspNetCore_Hosting_IWebHostBuilder_"" rel=""noreferrer"">https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.testhost.testserver.-ctor?view=aspnetcore-2.2#Microsoft_AspNetCore_TestHost_TestServer__ctor_Microsoft_AspNetCore_Hosting_IWebHostBuilder_</a></p>

<p>I know IHostBuilder will replace IWebHostBuilder in .NET Core 3.0 and TestServer there will support this. Trying to find a way to do this in .NET Core 2.2.</p>
",https://stackoverflow.com/questions/57600972/integration-testing-net-code-2-2-ihostbuilder-generic-host-builder,"['c#', 'integration-testing', '.net-core-2.2']",1727,False,11,1
Open Workspace during integration testing for vscode extension,"<p>I have a use case where I need to have a workspace open in the host environment for vscode testing. I want to know a function to open a default workspace and another function which I can use with await so that the testing function waits till a workspace is opened.</p>
",https://stackoverflow.com/questions/54926105/open-workspace-during-integration-testing-for-vscode-extension,"['visual-studio-code', 'continuous-integration', 'integration-testing', 'devops', 'vscode-extensions']",140,False,3,0
Integration Testing - How to hit endpoints using Microsoft.Owin.Testing.TestServer?,"<p>I have setup a basic Web API project to test writing integration tests, with the below setup</p>

<p>Startup:</p>

<pre><code>using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(WebApiTest.Startup))]

namespace WebApiTest
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            WebApiConfig.Register(new System.Web.Http.HttpConfiguration());
        }
    }
}
</code></pre>

<p>And the following controller:</p>

<pre><code>using System.Web.Http;

namespace WebApiTest.Controllers
{
    public class TestController : ApiController
    {
        public IHttpActionResult Post()
        {
            return Ok(""Hello, world!"");
        }
    }
}
</code></pre>

<p>For my Tests project I am using <code>NUnit</code> for my testing, and have two classes: an abstract <code>BaseTest</code> class, and a <code>ControllerTests</code> class which contains one test with the intention of sending a web request out to the above <code>TestController</code>'s <code>GET</code> Action method:</p>

<p>BaseTest:</p>

<pre><code>using Microsoft.Owin.Testing;
using NUnit.Framework;
using System;
using System.Net.Http;

namespace WebApiTest.Tests
{
    public abstract class BaseTest : IDisposable
    {
        protected const string _url = ""http://localhost/"";
        protected TestServer _server;

        public void Dispose()
        {
            _server.Dispose();
        }

        [SetUp]
        public void SetUp()
        {
            _server = TestServer.Create&lt;Startup&gt;();
        }

        protected HttpRequestMessage CreateRequest(string url, string 
contentType, HttpMethod method)
        {
            HttpRequestMessage request = new HttpRequestMessage
            {
                RequestUri = new Uri(_url + url),
                Method = method
            };
            request.Headers.Accept.Add(new 
System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(contentType));
            return request;
        }
    }
}
</code></pre>

<p>ControllerTests:</p>

<pre><code>using FluentAssertions;
using NUnit.Framework;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace WebApiTest.Tests
{
    [TestFixture]
    public class ControllerTests : BaseTest
    {
        [Test]
        public async Task Test1()
        {
            HttpRequestMessage request = CreateRequest(""test"", ""application/json"", HttpMethod.Post);
            HttpResponseMessage response = await _server.HttpClient.SendAsync(request);
            response.StatusCode.Should().Be(HttpStatusCode.OK);
        }
    }
}
</code></pre>

<p>The problem I am running into is that I'm not able to reach my endpoint with the call <code>await _server.HttpClient.SendAsync(request);</code> as I always get a <code>404: Not Found</code> response.</p>

<p>I'm not entirely sure what I'm doing wrong, whether it be something that's not being setup property or Api routes that aren't being mapped.</p>

<p><strong>update</strong>: Here is my <code>WebApiConfig.Register()</code> method for reference:</p>

<pre><code>public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();
    config.Routes.MapHttpRoute(
        name: ""DefaultApi"",
        routeTemplate: ""api/{controller}/{id}"",
        defaults: new { id = RouteParameter.Optional }
    );
}
</code></pre>
",https://stackoverflow.com/questions/56675136/integration-testing-how-to-hit-endpoints-using-microsoft-owin-testing-testserv,"['c#', 'asp.net', 'integration-testing', 'owin']",1208,True,3,2
spring boot integration testing mock method returns null,"<p>I wrote simple spring boot application with <code>Controller</code>, <code>Service</code> and <code>Business</code> classes, but while writing integration test the mock method of <code>Service</code> is returning null</p>

<p><strong>MockMainController</strong></p>

<pre><code>@RestController
public class MockMainController {

@Autowired
private MockBusiness mockBusiness;

@GetMapping(""request"")
public MockOutput mockRequest() {
    return mockBusiness.businessLogic(new MockInput());

      }

  }
</code></pre>

<p><strong>MockBusiness</strong></p>

<pre><code>@Service
public class MockBusiness {

@Autowired
private MockService mockService;

public MockOutput businessLogic(MockInput input) {
    return mockService.serviceLogic(input);
    }
}
</code></pre>

<p><strong>MockService</strong></p>

<pre><code>@Service
public class MockService {

@Autowired
private MockUtil mockUtil;

public MockOutput serviceLogic(MockInput input) {

    mockUtil.exchange(UriComponentsBuilder.fromUriString("" ""), HttpMethod.GET, HttpEntity.EMPTY,
            new ParameterizedTypeReference&lt;MockOutput&gt;() {
            });
    return new MockOutput();

     }

 }
</code></pre>

<p>I'm trying to mock the <code>MockService</code> bean in application context using <code>@MockBean</code></p>

<p><strong>MockControllerTest</strong></p>

<pre><code>@SpringBootTest
@ActiveProfiles(""test"")
@Profile(""test"")
@RunWith(SpringJUnit4ClassRunner.class)
public class MockControllerTest {

@Autowired
private MockMainController mockMainController;

@MockBean
private MockService mockService;

@Test
public void controllerTest() {
    MockOutput output = mockMainController.mockRequest();
    given(this.mockService.serviceLogic(ArgumentMatchers.any(MockInput.class)))
            .willReturn(new MockOutput(""hello"", ""success""));
    System.out.println(output);    //null
     }

 }
</code></pre>

<p>In the test method I created mock service bean using <code>@MockBean</code> I'm not having any error here but <code>System.out.println(output);</code> prints <code>null</code></p>
",https://stackoverflow.com/questions/55015662/spring-boot-integration-testing-mock-method-returns-null,"['java', 'spring', 'spring-boot', 'mockito']",2708,True,2,1
Implement Integration Testing with ASP.NET Core and NUnit,"<p>I am new to use NUnit integration testing with Asp core 2.2, I have already core RESTful Api but have no idea how to configure NUnit to implement integration test.
Usually I Implement it using Configuration file from Migration Folder as the following but no more exists in ASP Core 2.2 and I don't know what the new alternative.</p>

<pre><code>        var configuration = new Migrations.ApplicationDbContextModelSnapshot();
        var migrator = new Migrator(configuration);
        migrator.Update();
</code></pre>

<p>So please If you don't understand my question I just need an explicit link to use NUnit Integration Testing with .Net Core 2.2.</p>
",https://stackoverflow.com/questions/58120227/implement-integration-testing-with-asp-net-core-and-nunit,"['c#', 'asp.net-core', 'nunit', 'integration-testing']",239,True,-1,1
Integration testing issue on inserting in data base,"<p>I am very new to testing and I'm playing right now with integration testing.</p>

<p>I'm writing this piece of code to insert a new entry in the database and test the before and after arrays. But for some reason, it seems to return false and I'm not sure if I'm doing everything right:</p>

<p>Here is the JUnit Class:</p>

<pre><code>public class TestJunit {

private Question question;
private QuestionDAO questionDaoMock;

protected void setUp(){
    question = new Question();
    questionDaoMock = mock(QuestionDAO.class);  
    question.setQuestiondao(questionDaoMock);
}

@Test
public void testAdd() {
    questionDaoMock.openCurrentSessionwithTransaction();
    List&lt;Question&gt; currentQuestions = new ArrayList&lt;Question&gt;();
    currentQuestions = questionDaoMock.findAll();

    question.setChapterId(64);
    question.setText(""Rezultatul calculului 54*2-76:2 este..."");

    questionDaoMock.persist(question);
    currentQuestions.add(question);

    List&lt;Question&gt; newQuestions = new ArrayList&lt;Question&gt;();
    newQuestions = questionDaoMock.findAll();

    questionDaoMock.closeCurrentSessionwithTransaction();

    assertEquals(currentQuestions.size(), newQuestions.size());
}
}
</code></pre>

<p>This is my TestRunner:</p>

<pre><code>public class TestRunner {
   public static void main(String[] args) {
  Result result = JUnitCore.runClasses(TestJunit.class);

  for (Failure failure : result.getFailures()) {
     System.out.println(failure.toString());
  }

  System.out.println(result.wasSuccessful());
   }
}   
</code></pre>

<p>I tried already the code in the testAdd() function separately in the main function just to check if insertion works and it does. I compared the arrays size and it works as well when I'm running from main method. What am I doing wrong?</p>
",https://stackoverflow.com/questions/56793911/integration-testing-issue-on-inserting-in-data-base,"['java', 'hibernate', 'mockito', 'integration-testing']",374,True,0,3
Using Docker and Testcontainers for database integration testing,"<p>After a bit of research I was led to think that Docker containers could be a good fit for database integration testing using <a href=""https://www.testcontainers.org/modules/databases"" rel=""nofollow noreferrer"">test containers</a>, as this would only require a Docker container running a database image reproducing the database schema against which the tests would be executed. This instance can either be run locally on each developer’s machine or, even better, one single instance can be shared by multiple developers: an automated test can be configured to start a database instance from the same image in Docker for every test method if needed using the @Rule annotation.</p>

<p>While trying to install Docker for Windows 7 to play with it, I kept getting the following error which seems to be related to VirtualBox:</p>

<pre><code>docker Error creating machine: Error in driver during machine creation: Unable to start the VM: VBoxManage.exe startvm default --type headless failed:

Result code: E_FAIL (0x80004005)
Component: MachineWrap
Interface: IMachine
</code></pre>

<p>I will share how I worked around this problem to help other people who may have run into the same problem.</p>
",https://stackoverflow.com/questions/55705417/using-docker-and-testcontainers-for-database-integration-testing,"['java', 'oracle', 'docker', 'windows-7', 'testcontainers']",4297,True,0,1
Spring Framework integration testing with overriding DAO class,"<p>Im setting up integration tests in Spring to test if my API endpoints are working correctly.
There is no code because the question is a design problem question.</p>

<p>Right now i have a specific DAO class that talks to a real DB for IO operations.</p>

<p>I have a naive implementation of in-memory resource storage for testing that does not need any DB set up. </p>

<p>My question is how should I configure my tests in Spring so that the resource storing is done by the in-memory storage implementation.
(I need to mock the http requests and assert that they work properly, right now a test is up and running but the resource storing is done on the real db using the DAO for that)</p>

<p>P.S. i can replace the real db in the application.properties to a H2 db which would work with the current DAO, but i dont need that change to be in the DB layer, i need it to be in the DAO layer, to use a different implementation of resource storage class.</p>

<p>I'm relatively new to Spring testing, and i'm using jUnit for testing. </p>

<p>Thank you very much. All help is appreciated. </p>
",https://stackoverflow.com/questions/54267703/spring-framework-integration-testing-with-overriding-dao-class,"['java', 'spring', 'testing', 'integration-testing']",133,True,0,1
SignalR Service mock implementation for Service/Integration testing,"<p>I want to be able to simulate SignalR Hub for services tests. The idea is to be able to create a test in the following way:
Start a SignalR server (url, port and hub class should be configured at runtime) - the hub will be created in the test module for this purpose.
So the first part - starting a runtime configurable SignalR server Is possible:</p>

<pre><code>StartOptions so = new StartOptions(""http://127.0.0.1:8080"");
so.AppStartup = ""SrServer.Startup1""; // set the startup class (will be defined in the test module)
</code></pre>

<p>The following is an example for Startup1:</p>

<pre><code>class Startup1
{
    public void Configuration(IAppBuilder app)
    {

        app.UseCors(CorsOptions.AllowAll);
        app.MapSignalR();
    }
}
</code></pre>

<p>The only issue I'm missing is being able to set the hub to be used from my test module - is this possible?</p>
",https://stackoverflow.com/questions/54893256/signalr-service-mock-implementation-for-service-integration-testing,"['testing', 'service', 'signalr', 'integration']",161,False,0,1
How to perform integration testing on EF Core migrations,"<p>I've searched extensively on this subject and have found zero results for exactly what it is that I want to do.</p>
<p>From a high level, this is what I want to do:<br/></p>
<ul>
<li>Arrange: Within a test method, call appropriate services to seed the database.</li>
<li>Act: Run a migration to update the database schema.</li>
<li>Assert: Data integrity, i.e., seed data can be accessed as per the updated entity structure.</li>
</ul>
<p>What's the point of this?<br/>
Well it's pretty much described in the assertion above; data integrity. Migrations in this project are run on app startup using <code>Database.Migrate()</code>. I'd like to make sure that there's no loss/corruption of existing data.</p>
<p>All examples of integration testing I've come across pretty much run <code>Database.Migrate()</code> as part of the test setup, followed by seeding, and then making assertions. This however is only useful in testing the data access layer given the <em>latest</em> schema (with all migrations already applied). It's not useful in testing the effects of a specific migration on data that already exists.</p>
<p><strong>Question:</strong><br/></p>
<p>How have others tackled the issue of testing data integrity across migrations? I'm looking for a setup which would work well with a CI pipeline.</p>
",https://stackoverflow.com/questions/55086435/how-to-perform-integration-testing-on-ef-core-migrations,"['asp.net-web-api', 'integration-testing', 'entity-framework-migrations', 'ef-core-2.0']",1607,True,6,2
Selecting Email Account from google_sign_in during Flutter integration testing,"<p>I was trying to test sign-in to my home screen for my flutter app. I am using the google-signin ( <a href=""https://pub.dev/packages/google_sign_in"" rel=""noreferrer"">https://pub.dev/packages/google_sign_in</a>) package from Flutter to perform login and authentication. So once the login button is pressed, a popup appears asking the user to select the user account. At that point, I am unable to control the tap as this dialog screen is generated by the plugin. How do I implement selection of the user account in this case ?</p>

<pre><code>    test('Test Login', () async {
  final Timeline timeline = await driver.traceAction(() async {
    await driver.tap(find.byValueKey('GoogleLogin'));
    await driver.tap(find.text('myemail@gmail.com')); // This will not work !!!
  });

  TimelineSummary.summarize(timeline)
    ..writeSummaryToFile('home_scroll_perf', pretty: true)
    ..writeTimelineToFile('home_scroll_perf', pretty: true);
});
</code></pre>

<p>In my opinion, this could be a problem when testing with any third party plugin. Please help.</p>
",https://stackoverflow.com/questions/58052343/selecting-email-account-from-google-sign-in-during-flutter-integration-testing,"['flutter', 'dart', 'integration-testing', 'google-signin', 'flutter-test']",1595,False,5,2
ASP.NET Core 2.2 Integration Testing DbContext Service not registered,"

<p><strong>Setup</strong></p>

<ul>
<li>Windows 10</li>
<li>Visual Studio Professional 2017 v15.9.9</li>
<li>ASP.NET Core 2.2</li>
<li>EF Core 2.2</li>
<li>Dapper</li>
<li>xUnit 2.4.1</li>
</ul>

<p><strong>Description</strong></p>

<p>I'm using the <code>WebApplicationFactory</code> from the <code>Microsoft.AspNetCore.Mvc.Testing</code> package to setup my integration tests.</p>

<p>I've been following the <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2"" rel=""nofollow noreferrer"">official documentation</a> to customise the web host configuration.</p>

<p>The SUT uses Dapper to query from the database, so I'm not using the In-Memory provider that ships with EF Core for this particular integration test.</p>

<p>My code for setting up the <code>WebApplictionFactory</code> is below:</p>

<pre class=""lang-cs prettyprint-override""><code>public class CustomWebApplicationFactory&lt;TStartup&gt;
    : WebApplicationFactory&lt;TStartup&gt; where TStartup : class
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder
            .UseStartup&lt;TStartup&gt;()
            .ConfigureServices(services =&gt;
        {
            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 dbContext = scopedServices.GetRequiredService&lt;MyDbContext&gt;(); // &lt;-- service not found

                dbContext.Database.EnsureCreated();

                new MyDbContextSeed()
                    .SeedAsync(dbContext)
                    .Wait();
            }
        });
    }
}
</code></pre>

<p><strong>Issue</strong></p>

<p>The <code>MyDbContext</code> service isn't found, I understand why (I think) - because the <code>ServiceProvider</code> from my <code>Startup.cs</code> class hasn't built yet.</p>

<p>But the question is <em>How can I access the services from my Startup class here?</em></p>

<p>For context, the Integration test looks like this:</p>

<pre class=""lang-cs prettyprint-override""><code>public class MyAPITests
    : IClassFixture&lt;CustomWebApplicationFactory&lt;Startup&gt;&gt;
{
    private readonly HttpClient _client;
    private readonly CustomWebApplicationFactory&lt;Startup&gt; _factory;

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

    [Fact]
    public async Task Get_ItemAsync_WhenIdNotFound_ReturnsNotFoundStatusCode()
    {
        // Arrange
        var request = new HttpRequestMessage(HttpMethod.Get, ""api/v1/item/0"");

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

        // Assert
        Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
    }
}
</code></pre>
",https://stackoverflow.com/questions/55812037/asp-net-core-2-2-integration-testing-dbcontext-service-not-registered,"['c#', 'asp.net-core']",1595,True,3,1
.net core : Integration testing : Getting error : XUnitTestClassRunner.cs not found,"<p>PFB Error  : </p>

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

<p>TestFixture Setup :</p>

<pre><code>public TestServerFixture()
    {
        var configuration = new ConfigurationBuilder()
                        .AddJsonFile(@""appsettings.json"")
                        .Build();

        //Assembly startupAssembly = typeof(Startup).GetTypeInfo().Assembly;
        //var contentRoot = GetProjectPath(startupAssembly);

        var builder = new WebHostBuilder()
               .UseContentRoot(this.GetContentRootPath())
               .UseEnvironment(""Testing"").UseConfiguration(configuration)
               .UseStartup&lt;Startup&gt;();  // Uses Start up class from your API Host project to configure the test server

        this._testServer = new TestServer(builder);
        this.Client = this._testServer.CreateClient();
    }
</code></pre>

<p>TestMethods :</p>

<pre><code>public class SearchControllerTest : IClassFixture&lt;TestServerFixture&gt;
{
    private readonly TestServerFixture _fixture;

    public SearchControllerTest(TestServerFixture fixture)
    {
        _fixture = fixture;
    }

    [Fact]
    public async Task SearchData()
    {
        var response = await _fixture.Client.GetAsync(""/api/SearchController/Test"");

        response.EnsureSuccessStatusCode();

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

    }
}
</code></pre>

<blockquote>
  <p>After creating the client object <strong>Fact SearchData</strong> is not getting called
  and getting above mentioned error.</p>
</blockquote>
",https://stackoverflow.com/questions/55063564/net-core-integration-testing-getting-error-xunittestclassrunner-cs-not-fo,"['c#', '.net', '.net-core', 'xunit', 'xunit.net']",436,True,2,1
Using embedded gemfire locator and server for integration testing,"<p>I have a application that uses gemfire locator and servers. I would like to write an integration test that could help me start a locator &amp; a server within the JVM and also shut them down when ending the tests. I could not find any single documentation which could help me do this.</p>

<p>I have tried starting a locator and a server when the tests start using <code>LocatorLauncher</code> an <code>ServerLauncher</code>. It starts the locator but throws an exception stating <code>IllegalStateException: A connection to a distributed system already exists in this VM.</code></p>

<p>I am not very good with gemfire and do not understand what am I missing here, or is it that I am trying in a complete wrong direction.</p>
",https://stackoverflow.com/questions/54194383/using-embedded-gemfire-locator-and-server-for-integration-testing,"['java', 'gemfire', 'spring-data-gemfire']",538,True,2,1
How to get Hibernate Envers with Spring integration testing?,"<p><strong>Is there some way to get Hibernate Envers to run <em>immediately</em> on the call to save or update instead of going at the end of the transaction ?</strong></p>

<p>I have a <code>@Transactional</code> annotation on my (effectively end-to-end test). Since the code doesn't contain test methods I'm unable to put ""flush"" or whatever in it, (short of editing non-test code, which is not the desire). </p>

<p><strong>I'm not sure how to get Envers log working on the calls. I need it to work  as I'm using the Envers audit tables to check old entries at runtime, and would like to create test cases for this functionality.</strong> </p>

<p>I have the following code for unit testing :</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(""/src/webapp"")
@EnableWebMvc
@Transactional
@TestPropertySource(locations= {""classpath:/config/common.properties""}, properties = {""...""})
@ContextConfiguration(locations = {""...""})
public class Test {
    @Autowired
    private WebApplicationContext wac;

    @Autowired
    private UserDetailsService detailsService;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
            .build();
    }

    ...
}
</code></pre>
",https://stackoverflow.com/questions/58199711/how-to-get-hibernate-envers-with-spring-integration-testing,"['spring', 'hibernate', 'hibernate-envers']",706,False,2,0
How to do integration testing for custom mongo repository?,"<p>These are the following configuration that I have done in my project.</p>
<pre class=""lang-java prettyprint-override""><code>@Configuration
public class AppMongoConfig {
        
    @Autowired private MongoDbFactory mongoDbFactory;
        
    @Autowired private MongoMappingContext mongoMappingContext;
        
    @Bean
    public MappingMongoConverter mappingMongoConverter() {
        
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
        MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));
        
        return converter;
    }
}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(MultipleMongoProperties.class)
public class MultipleMongoConfig {
    
    private final MultipleMongoProperties mongoProperties;
    
    @Primary
    @Bean(name = &quot;primaryMongoTemplate&quot;)
    public MongoTemplate primaryMongoTemplate() throws Exception {
        return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
    }
    
    @Bean(name = &quot;secondaryMongoTemplate&quot;)
    public MongoTemplate secondaryMongoTemplate() throws Exception {
        return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));
    }
    
    @Bean
    @Primary
    public MongoDbFactory primaryFactory(final MongoProperties mongo) throws Exception {
        return new SimpleMongoDbFactory(new MongoClientURI(mongo.getUri()));
    }
    
    @Bean
    public MongoDbFactory secondaryFactory(final MongoProperties mongo) throws Exception {
        return new SimpleMongoDbFactory(new MongoClientURI(mongo.getUri()));
    }
}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>@Data
@ConfigurationProperties(prefix = &quot;mongodb&quot;)
public class MultipleMongoProperties {
    private MongoProperties primary = new MongoProperties();
    private MongoProperties secondary = new MongoProperties();
}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>@Configuration
@EnableMongoRepositories(
    basePackages = {&quot;com.student.repository.primary&quot;},
    mongoTemplateRef = &quot;primaryMongoTemplate&quot;)
    public class PrimaryMongoConfig {}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>@Configuration
@EnableMongoRepositories(
    basePackages = {&quot;com.student.repository.secondary&quot;},
    mongoTemplateRef = &quot;secondaryMongoTemplate&quot;)
public class SecondaryMongoConfig {}
</code></pre>
<p>Repository code:</p>
<pre class=""lang-java prettyprint-override""><code>public interface StudentDAO {
        
    Student save(StudentInfo studentInfo); 
} 
</code></pre>
<pre class=""lang-java prettyprint-override""><code>@Repository 
public class StudentDAOImpl implements StudentDAO {
       
    @Autowired   @Qualifier(&quot;primaryMongoTemplate&quot;)   
    private MongoTemplate mongoTemplate;
        
    @Override   public StudentInfo save(StudentInfo userWatchlist) {
        return mongoTemplate.save(userWatchlist);   
    } 
}
</code></pre>
<p>Integration Testing code:</p>
<pre class=""lang-java prettyprint-override""><code>@RunWith(SpringRunner.class)
@DataMongoTest(includeFilters = @Filter(Repository.class))
public class WatchListDAOImplIT {
    
    @Autowired private StudentDAO studentDAO;
    
    @Test
    public void save() {
        StudentInfo studentInfo = getStudentInfo();
        StudentInfo dbUserWatchlist = watchListDAO.save(studentInfo);
        Assert.assertEquals(studentInfo.getId(), dbUserWatchlist.getId());
    }
    
    private StudentInfo getStudentInfo() {
        StudentInfo studentInfo = new StudentInfo();
        studentInfo.setId(9999999l);
        return studentInfo;
    }
}
</code></pre>
<p>Which is giving me following error:-</p>
<pre><code>java.lang.IllegalStateException: Failed to load ApplicationContext
    at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
    at
org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
    at
org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:
: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'appMongoConfig': Unsatisfied dependency
expressed through field 'mongoDbFactory'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'primaryFactory' defined in class path
resource [.../config/mongo/MultipleMongoConfig.class]: Unsatisfied
dependency expressed through method 'primaryFactory' parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.boot.autoconfigure.mongo.MongoProperties'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations: {}

Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.boot.autoconfigure.mongo.MongoProperties'
available: expected at least 1 bean which
</code></pre>
",https://stackoverflow.com/questions/56002880/how-to-do-integration-testing-for-custom-mongo-repository,"['spring-boot', 'spring-data-mongodb', 'spring-properties']",375,False,1,0
How to do integration testing on an API wrapper,"<p>I have an api wrapper that is just your basic controller/service that is using a third party client to actually handle requests. Is it possible to mock this for integration testing somehow?</p>

<pre><code>Clientservice clientService = new ClientService(urlHere);
clientService.findBooks(); //Handles request within, my wrapper does not directly call endpoints
</code></pre>

<p>What's the proper way to integrate test this? Just call my controller with rest and mock the clientService return? Unsure if it's possible to do this another way.</p>

<p>Edit: changed title and info to try and make this clearer. </p>
",https://stackoverflow.com/questions/58249899/how-to-do-integration-testing-on-an-api-wrapper,"['java', 'integration-testing', 'wiremock']",180,False,0,1
Integration testing framework for rest Kafka and soap services,"<p>Hi there I would like to build an integration test framework that supports testing soap services mq Kafka and rest services - can someone say if citrus framework would be a better choice ? And some p tutorial to refer at ?
Thanks</p>
",https://stackoverflow.com/questions/57125185/integration-testing-framework-for-rest-kafka-and-soap-services,['citrus-framework'],165,False,0,1
CakePHP 3.6 Controller Integration Testing - HTTP requests not sent,"<p>I am trying to implement controller integration testing in CakePHP <strong>3.6</strong> using its testing tools. I assumed that this would be handled by making a 'real' (as in CURL) HTTP request against the running webserver, but it looks like it isn't. Below is the test case code I'm using.</p>

<p>The problems I'm running into:</p>

<ol>
<li>The test case is somehow managing to access the controler action,
even when the webserver is not running at all (Apache down and no
dev webserver running).</li>
<li>When running this test, the controller does not have access to
<code>$_SERVER</code> (see below) and any of the <code>$postData</code> defined in the test case appears empty on the controller side.</li>
<li>When I place <code>exit;</code> in the controller code, the whole test case
stops, which suggests that the controller code is run directly, not
via a HTTP request.</li>
</ol>

<p><strong>Question:</strong> How can I make a 'real' HTTP requests when testing controllers, apart from resorting to using CURL and handling the requests manually?</p>

<p>Clearly, I am either not understanding how the controller testing is done, or I'm doing something wrong.</p>

<p>Test case I'm using:</p>

<p><strong>/tests/TestCase/Controller/JobsControllerTest.php</strong></p>

<pre><code>&lt;?php
namespace App\Test\TestCase\Controller;

use Cake\ORM\TableRegistry;
use Cake\TestSuite\IntegrationTestCase;

/**
 * App\Controller\JobsController Test Case
 */
class JobsControllerTest extends IntegrationTestCase
{

    /**
     * Test add method
     *
     * @return void
     */
    public function testAdd()
    {
        $this-&gt;useHttpServer(true);

        $this-&gt;configRequest([
            'headers' =&gt; [
                'Content-Type' =&gt; 'application/json',
                'X-Api-Key' =&gt; '8f083c8f083c8f083c8f083c'
            ]
        ]);
        $postData = [
            'user_id' =&gt; 3,
            'job_status' =&gt; 'New'
        ];
        $this-&gt;post('/jobs/add', $postData);

        $this-&gt;assertResponseSuccess();
        $jobs = TableRegistry::get('Jobs');
        $query = $jobs-&gt;find()-&gt;where(['user_id' =&gt; $postData['user_id']]);
        $this-&gt;assertEquals(1, $query-&gt;count());
    }

}
</code></pre>

<p><strong>The dump of <code>$_SERVER</code> global</strong> from the controller that I'm testing:</p>

<pre><code>Array
(
    [LS_COLORS] =&gt; rs=0:di=01;34 [...]
    [LANG] =&gt; en_US.UTF-8
    [HOME] =&gt; /home/tomasz
    [TERM] =&gt; screen
    [PATH] =&gt; /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
    [MAIL] =&gt; /var/mail/root
    [LOGNAME] =&gt; root
    [USER] =&gt; root
    [USERNAME] =&gt; root
    [SHELL] =&gt; /bin/bash
    [SUDO_COMMAND] =&gt; vendor/bin/phpunit --verbose
    [SUDO_USER] =&gt; tomasz
    [SUDO_UID] =&gt; 1000
    [SUDO_GID] =&gt; 1000
    [PHP_SELF] =&gt; vendor/bin/phpunit
    [SCRIPT_NAME] =&gt; vendor/bin/phpunit
    [SCRIPT_FILENAME] =&gt; vendor/bin/phpunit
    [PATH_TRANSLATED] =&gt; vendor/bin/phpunit
    [DOCUMENT_ROOT] =&gt;
    [REQUEST_TIME_FLOAT] =&gt; 1546631688.0758
    [REQUEST_TIME] =&gt; 1546631688
    [argv] =&gt; Array
        (
            [0] =&gt; vendor/bin/phpunit
            [1] =&gt; --verbose
        )

    [argc] =&gt; 2
)
</code></pre>
",https://stackoverflow.com/questions/54045338/cakephp-3-6-controller-integration-testing-http-requests-not-sent,"['testing', 'cakephp', 'phpunit']",323,True,0,1
Integration testing a fetch calls in a node module,"<p><strong>Goal:</strong> Call a function that invokes a fetch call to validate it works with my backend rest-api (end to end testing basically).</p>

<p><strong>Project:</strong> node module built to be imported into several react web application. The module contains only fetch calls and minimal logic. Its basically a glorified wrapper for URLs and settings. Created to cut down work required to implement common end points used in applications.</p>

<p><strong>Setup:</strong> I have a docker compose building a docker test container and pulling in my rest-api docker image (built in a different system). The test container pulls in the packed module and installs it with dependencies. Then it brings up the tests alongside the backend + other images needed for the backend (DB, login system, etc).</p>

<p><strong>Problem:</strong> How to implement the tests to handle the calls. </p>

<p>Currently I've tried calling the fetch methods directly. This works for my login fetch but any additional call fails to send the cookie. As far as I understand the code I have depends on the browser for the cookie. I've tried several solutions to get said cookie but i've been unable to get fetch of node-fetch to send it properly. My best guess is each test was creating a new cookie but I lack the knowledge to full debug this solution path.</p>

<p>my send solution path was to attempt to use puppeteer to load a fake page and then evaluate the function in page following examples like:
<a href=""https://github.com/puppeteer/puppeteer/issues/2579"" rel=""nofollow noreferrer"">https://github.com/puppeteer/puppeteer/issues/2579</a>
<a href=""https://stackoverflow.com/questions/53676445/how-to-use-imported-function-inside-page-evaluate-in-puppeteer-with-jest"">How to use imported function inside page.evaluate in Puppeteer with Jest?</a></p>

<p>Problem with this is the tests kept failing to load libraries required or some other problem.</p>

<p><strong>Code:</strong></p>

<p>Here is the call I'm trying to test for the most part. Each function I have wraps around this providing {url: ""api/endpoint/path"", method: ""GET""}. With some passing in a body for larger data posts. </p>

<pre><code> export function request(options) {

    //Build options
    options = {
        headers: {
            'Content-Type': 'application/json'
        },
        ...options
    };

    return fetch(options.url, options)
        .then(response =&gt; {
            //...

            //Handle errors
            if (!response.ok) {
                return Promise.reject(`${response.status} - ${response.statusText}`);
            }

            try {
                return response.json();
            } catch (e) {
                if (e.name === 'SyntaxError') {
                    return Promise.reject(response.text());
                }
            }
        });
}
</code></pre>

<p>Test example i've tried:</p>

<pre><code>import puppeteer from ""puppeteer"";
import {myCall} from ""my-rest-bridge"";

it('Check response', async () =&gt; {

    //Load browser
    const browser = await puppeteer.launch({
        headless: true,
        args: ['--no-sandbox']
    });
    const page = await browser.newPage();

    //Load page
    await page.goto('http://docker:8888/index.html');

    //Do login
    expect(await page.evaluate(() =&gt; login('user', 'password')).toBe(expectedUserResponseJson);

    //Make call
    expect(await page.evaluate(() =&gt; myCall(input1, input2)).toBe(expectedCallResponseJson);

    //Close page
    await page.close();
})

</code></pre>
",https://stackoverflow.com/questions/59399272/integration-testing-a-fetch-calls-in-a-node-module,"['reactjs', 'rest', 'docker', 'node-fetch']",278,True,0,1
Azure Service Bus - Integration testing approach for a Java app,"<p>What is your approach for integration testing Java applications that use Azure Service Bus for messaging? </p>

<p>I don't want to use the cloud service in every CI build. Would much rather spawn an embedded version of Azure Service Bus or mock it somehow. Alternatively I'm considering coding to AMQP/JMS and using embedded ActiveMQ to emulate Azure Service Bus during CI builds.
Thanks.</p>
",https://stackoverflow.com/questions/54149552/azure-service-bus-integration-testing-approach-for-a-java-app,"['java', 'azure', 'continuous-integration', 'integration-testing', 'azureservicebus']",2050,True,5,1
C# Integration Testing Controller with FromForm binding to IFormFile property,"<p>I'm using:</p>

<ul>
<li>Visual Studio 2017 Pro</li>
<li>dotnet core sdk 2.2.102</li>
<li>XUnit 2.4.1</li>
</ul>

<p><strong>What I'm trying to do</strong></p>

<p>Integration test an API Controller Method that accepts Form Data.</p>

<p><strong>Setup</strong></p>

<ul>
<li>API route in my controller that accepts a CommandObject using the <code>[FromForm]</code> attribute</li>
<li>One of the properties of the CommandObject is of type <code>List&lt;IFormFile&gt;</code>, this is designed to manage any files that are part of the request</li>
<li>The Controller method works as expected when I test it manually from Postman.</li>
</ul>

<p><strong>The Problem</strong></p>

<p>The Files are not bound to the <code>List&lt;IFormFile&gt;</code> property.  Everything else works as expected, but the files do not.  The is the first time I've used Multipart Form Data, so am not sure what to try.</p>

<p>When I debug the test, you can see everything works except for the <code>Documents</code> property (Note, this doesn't match 100% with the code below, because I've had to obfuscate some stuff)</p>

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

<p><strong>Stuff I've looked at</strong></p>

<p>There is a lot of stuff relating to multipart form data, some of the solutions I've tried are:</p>

<ul>
<li><a href=""https://stackoverflow.com/questions/16416601/c-sharp-httpclient-4-5-multipart-form-data-upload"">This StackOverflow post</a></li>
<li><a href=""https://stackoverflow.com/questions/42212406/how-to-send-a-file-and-form-data-with-httpclient-in-c-sharp/42212590"">Another StackOverflow post</a></li>
<li><a href=""https://gist.github.com/bgrins/1789787"" rel=""nofollow noreferrer"">A custom class</a></li>
</ul>

<p><strong>MyIntegrationTest.cs</strong></p>

<p>There's a lot of code behind the setup of my integration tests.  If I post it all here I don't think it will be very helpful.  The most important piece of information is that variable <code>server</code> is of type <code>Microsoft.AspNetCore.TestHost.TestServer</code></p>

<pre class=""lang-cs prettyprint-override""><code>[Fact]
async Task Post_ItemAsync_HappyPath_ReturnsOKStatusCode()
{
    var fileDir = @""C:/path/to/files"";
    var fileNames = new string[] { ""test.docx"", ""test.txt"" };

    using (var server = CreateTestServer())
    {
        // Arrange
        var formData = new MultipartFormDataContent()
        {
            { new StringContent(""Test Title""), ""Title"" },
            { new StringContent(""Test Description""), ""Description"" },
            { new StringContent(""String_1""), ""AListOfStrings"" },
            { new StringContent(""String_2""), ""AListOfStrings"" },
            { new StringContent(""3""), ""NumberOfThings"" }
        };

        foreach (var fileName in fileNames)
        {
            var document = File.ReadAllBytes($""{fileDir}/{fileName}"");
            formData.Add(new ByteArrayContent(document), ""file"", fileName);
        }

        string formDataBoundary = String.Format(""----------{0:N}"", Guid.NewGuid());
        string contentType = ""multipart/form-data; boundary="" + formDataBoundary;

        var request = new HttpRequestMessage(HttpMethod.Post, ""api/v1/item"")
        {
            Headers =
            {
                { HttpRequestHeader.ContentType.ToString(), contentType }
            },
            Content = formData
        };

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

        // Assert
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        // Cleanup
        ...
    }
}
</code></pre>

<p><strong>MyController.cs</strong></p>

<pre class=""lang-cs prettyprint-override""><code>[HttpPost]
ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task&lt;IActionResult&gt; CreateItemAsync([FromForm]CreateItemCommand command)
{
    bool commandResult = false;

    commandResult = await _mediator.Send(command);

    if (!commandResult)
    {
        return BadRequest();
    }

    return Ok();
}
</code></pre>

<p><strong>CreateItemCommand.cs</strong></p>

<pre class=""lang-cs prettyprint-override""><code>[DataContract]
public class CreateItemCommand
    :IRequest&lt;bool&gt;
{
    [DataMember]
    public string Title { get; set; }

    [DataMember]
    public string Description { get; set; }

    [DataMember]
    public HashSet&lt;string&gt; AListOfThings { get; set; }

    [DataMember]
    public int NumberOfThings { get; set; }

    [DataMember]
    public List&lt;IFormFile&gt; Documents { get; private set; }

    public CreateITemCommand()
    {
        AListOfThings = new HashSet&lt;string&gt;();
    }

    public CreateItemCommand(string title, string description, HashSet&lt;string&gt; aListOfThings, int NumberOfThings, List&lt;IFormFile&gt; documents)
        : this()
    {
        Title = title;
        Description = description;
        AListOfStrings = aListOfStrings;
        NumberOfThings = numberOfThings;
        Documents = documents;
    }
}
</code></pre>
",https://stackoverflow.com/questions/56722267/c-integration-testing-controller-with-fromform-binding-to-iformfile-property,"['c#', 'asp.net-core', 'multipartform-data']",2708,True,4,1
How to implement integration testing for guards in nest js?,"<p>I want to implement unit testing for guards using nest js(Jest JS). I could nt find much documentation.</p>

<pre><code>import {Test, TestingModule} from '@nestjs/testing';
import {CatsController} from '../src/modules/cats/cats.controller';
import {CatsService} from '../src/modules/cats/cats.service';
import {ICat} from '../src/modules/cats/interfaces/ICat';
import {JwtStrategy} from '../src/strategy/AppId.strategy';

  beforeEach(async () =&gt; {
     const module = await Test.createTestingModule({
             controllers: [CatsController],
             providers: [CatsService],
         }).compile();

    catsService = module.get&lt;CatsService&gt;(CatsService);
    catsController = module.get&lt;CatsController&gt;(CatsController);

  });
  describe('findAll', () =&gt; {
    it('should return an array of cats', async () =&gt; {
      // const appIdAuthContext: AppIDAuthToken = tokenInfo;
      const result: ICat = {
        name: 'test',
        age: 1,
        breed: 'one'
      };
      jest.spyOn(catsService, 'findAll').mockImplementation(() =&gt; result);
      console.log(result);
      console.log(catsController.findAll());
      expect(await catsController.findAll()).toBe(result);
    });
  });
</code></pre>

<p>The above code will return array of cats. i want to implement guards for this unit test.</p>
",https://stackoverflow.com/questions/56218530/how-to-implement-integration-testing-for-guards-in-nest-js,"['node.js', 'angularjs', 'jestjs', 'nestjs']",4477,True,3,1
Should pytest be used for integration testing an embedded system?,"<p>I'm working on setting up my team's new unit test and integration test infrastructure and want to make sure I'm starting off by selecting the correct test frameworks. I'm  an embedded developer testing code running on a VxWorks operating system with a C/C++ production codebase. </p>

<p>We need a framework capable of directly testing C/C++ for unit testing, so for our unit tests I chose Googletest as our framework. </p>

<p>However, for integration tests we've generally tested using Python scripts (with no test framework). The Python scripts connect to the embedded system over a network and test cases via sending commands and receiving telemetry. </p>

<p>Would using pytest as a test framework be beneficial to the way we're currently using Python for integration testing an embedded system?  Most of the examples I've seen use pytest in a more unit test fashion by creating assertions for single functions in a Python production codebase.</p>

<p>EDIT:
Per hoefling's comment, i'll provide a (very simplified) example of one of our existing Python integration test cases, and also what I believe its corresponding Pytest implementation would be.</p>

<pre><code>#Current example
def test_command_counter():
    preTestCmdCount = getCmdCountFromSystem()
    sendCommandToSystem()
    postTestCmdCount = getCmdCountFromSystem()

    if (postTestCmdCount != (preTestCmdCount + 1)):
        print(""FAIL: Command count did not increment!"")
    else:
        print(""PASS"")


#Using Pytest?
def test_command_counter():
    preTestCmdCount = getCmdCountFromSystem()
    sendCommandToSystem()
    postTestCmdCount = getCmdCountFromSystem()

    assert postTestCmdCount == (preTestCmdCount + 1)
</code></pre>

<p>So, correct me if I'm wrong, but it appears that the advantages of using Pytest  over plain Python for this simplified case would be:</p>

<ol>
<li><p>Being able to make use of pytest's automated test case discovery, so that I can easily run all of my test functions instead of having to create custom code to do so.</p></li>
<li><p>Being able to make use of the 'assert' syntax which will automatically generate pass/fail statements for each test instead of having to manually implement pass/fail print statements for each test case</p></li>
</ol>
",https://stackoverflow.com/questions/56859750/should-pytest-be-used-for-integration-testing-an-embedded-system,"['python', 'pytest']",3916,True,3,2
Asp.Net Core Integration Testing with CustomWebApplicationFactory - How does it work?,"<p>I am trying to get a better understanding of integration testing. By default, a lot of example utilize <code>IClassFixture&lt;T&gt;</code> for integration testing (e.g. being <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#basic-tests-with-the-default-webapplicationfactory"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#basic-tests-with-the-default-webapplicationfactory</a>).</p>

<p>That works great for testing things like - is the page loading, is the form being displayed, am I getting the correct http status code etc. But when testing an API, you'll want some seed data to exist. In order to get seed data into your testing, typical go-to is EF in-memory database. This is achieved via a custom web application factory where you can create a scope, request the appropriate service (i.e. dbcontext), and seed it (e.g. being <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#customize-webapplicationfactory"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#customize-webapplicationfactory</a>).</p>

<p>I have an integration test project that is working and fully functional. But the nuances of how it works is still confusing to me. </p>

<hr>

<h2>Am I correct in assuming that when you create a <strong>CustomWebApplicationFactory</strong>, essentially you are creating a custom ""Program.cs"" (i.e. the typical entry point into the application) where you are free to add in additional testing services/filters as needed?</h2>

<hr>

<p>Below is my custom web application factory that I am using for my integration testing. My API has basic authentication for most endpoints so I added a global filter to bypass that. But what I am doing below is essentially the same in my <strong>Program.cs</strong> in my actual API (the only difference being I don't add the fake user and global anonymous filter). So I am lead to believe that my above point stands true. Is this a correct assumption?</p>

<p>Another point I wanted to verify is that in an actual unit test, I can replace a service with a mock. Is this possible in an integration test where I can swap out the DI instance for a requested service to be a test service instead? </p>

<hr>

<h2>E.g. my app has a <code>IUploadFileToAzure</code> service. Instead of using UploadFileToAzure as the DI instance, can I replace that implementation with a <code>TestUploadFileToAzure</code> service in my integration test?</h2>

<hr>

<p>Registering a service multiple times takes the last registration of the service so I was wondering if that can be used as a workaround for my above point. Is this even recommended? I understand it defeats the purpose of testing a service but wanted to verify if that was possible. I tried testing this locally and it did not work.</p>

<pre><code>public class CustomWebApplicationFactory&lt;TStartup&gt; : WebApplicationFactory&lt;Startup&gt;
    {
        protected override IWebHostBuilder CreateWebHostBuilder()
        {
            return WebHost
                .CreateDefaultBuilder&lt;Startup&gt;(new string[0])
                .ConfigureServices(services =&gt;
                {
                    services.AddSingleton&lt;IStartupFilter, AddCustomMiddlewareStartupFilter&gt;();
                });
        }


        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder
            .UseEnvironment(""Development"")
            .ConfigureServices(services =&gt;
            {
                services.AddMvc(opt =&gt;
                {
                    //add a global anonymous filter
                    opt.Filters.Add(new AllowAnonymousFilter());

                    //add a filter for adding a fake claimsprincipal so that the user service
                    //correctly identifies the user
                    opt.Filters.Add(new FakeClaimsPrincipalFilter(true, false));
                });

                services.AddEntityFrameworkInMemoryDatabase();

                // Create a new service provider.
                var provider = services
                    .AddEntityFrameworkInMemoryDatabase()
                    .BuildServiceProvider();

                // Add a database context using an in-memory 
                // database for testing.
                services.AddDbContext&lt;AppDbContext&gt;(options =&gt;
                {
                    options.UseInMemoryDatabase(""TestDb"");
                    options.UseInternalServiceProvider(provider);
                });

                // 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 apiDb = scopedServices.GetRequiredService&lt;AppDbContext&gt;();   

                    // Ensure the database is created.
                    apiDb.Database.EnsureCreated();
                }
            });
        }
    }
</code></pre>
",https://stackoverflow.com/questions/57485969/asp-net-core-integration-testing-with-customwebapplicationfactory-how-does-it,"['c#', 'asp.net-core']",4802,True,2,1
Hard-coded vs Soft-coded expected values for Integration Testing,"<p>I understand that in Unit Test, hard-coded is preferred as we don't want to write much code as possible.</p>

<p>For Integration Testing however, is the same principle still applied? For a context, here's a common scenario:</p>

<ul>
<li>TodoController</li>
<li>TodoService</li>
<li>Serializer/Transformer/Whatever you call it</li>
</ul>

<p>Here's an imaginary code on how both approach might look like:</p>

<ul>
<li>Hard Coded</li>
</ul>

<pre><code>// Arrange
$note = new Note('note123', 'John', 'example message');

$this-&gt;noteRepository-&gt;save($note);

// Act
$response = $this-&gt;json('GET', '/api/notes');

// Assert
$response-&gt;seeJsonEquals([
   'id' =&gt; 'note123',
   'author' =&gt; 'John',
   'message' =&gt; 'example message'
]);

</code></pre>

<ul>
<li>Soft Coded (Computed)</li>
</ul>

<pre><code>// Arrange
$note = new Note('note123', 'John', 'example message');

$this-&gt;noteRepository-&gt;save($note);

// Act
$response = $this-&gt;json('GET', '/api/notes');

// Assert
$noteSerializer = new NoteSerializer();

$response-&gt;seeJsonEquals($noteSerializer-&gt;serialize($note));
</code></pre>

<p>The only catch for the soft-coded approach is that if the Serializer is the problem, the test will still pass because both the controller and expected value uses it.</p>

<p>However, we can solve that by creating another test for the Serializer.</p>

<p>We might have lots of mini-tests but I think it'll us save lots of time compared to hard-coding. If we changed our response structure, the hard-coded tests will need some changes as well but the soft-coded one needs to change in its own test only.</p>

<p>I might be missing something but I already tried to Google it and all I see are always about Unit Tests so thought of asking if same principle is still applied in Integration Tests as well</p>
",https://stackoverflow.com/questions/54748034/hard-coded-vs-soft-coded-expected-values-for-integration-testing,"['testing', 'tdd', 'integration-testing']",1165,True,1,2
How to configure Spring Boot JPA for Cucumber Integration testing?,"<p>I have a Spring Boot project that is using PostgreSQL. I am using Spring Data and creating <code>CrudRepository</code>. This works fine for the application as I am able to use Auto Configuration and all the beans work. Now I am trying to write integration tests using Cucumber. For my tests, I want to use Spring JPA to connect to the embedded H2 database. I have created <code>DataSource</code> bean and also a repository interface that extends <code>CrudRepository</code>. When the tests boot up, it throws an exception along the lines of: </p>

<pre><code>Specified class is an interface
</code></pre>

<p>I have even tried to do this manually by creating <code>LocalContainerEntityManagerFactoryBean</code> but, I am running into this exception:</p>

<pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getEntityManagerFactory' defined in com.package.integration.repository.RepoConfig: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
</code></pre>

<p>My <code>ConfigLoaderStepDefs</code></p>

<pre><code>@SpringBootTest(classes = [IntegrationTestConfig::class, JMeterRunner::class,
    RepoConfig::class])
class ConfigLoaderStepDefs : StepDefs

</code></pre>

<p>My <code>RepoConfig</code></p>

<pre><code>@Configuration
@EnableJpaRepositories(""&lt;repo package&gt;"")
@EnableTransactionManagement
class RepoConfig {

    @Bean
    fun getEntityManagerFactory(): LocalContainerEntityManagerFactoryBean {
        return LocalContainerEntityManagerFactoryBean().also { factory -&gt;
            factory.setPackagesToScan(""&lt;entities package&gt;"")
            factory.jpaVendorAdapter = HibernateJpaVendorAdapter()
        }
    }

    @ConfigurationProperties(prefix = ""spring.datasource"")
    @Bean
    @Primary
    fun getDataSource(): DataSource {

        val dataSourceBuilder = DataSourceBuilder.create()
        dataSourceBuilder.url(""jdbc:h2:mem:memorydb"")
                .username(""sa"")

        return dataSourceBuilder.build()
    }
}
</code></pre>

<p>My <code>CucumberIT</code></p>

<pre><code>@Tag(""it"")
@RunWith(Cucumber::class)
@CucumberOptions(
        plugin = [""html:build/reports/cucumber/cucumber-html-report"",
            ""json:build/reports/cucumber/cucumber-json-report.json""],
        features = [""classpath:features""],
        glue = [""com.package.integration""])
@SpringBootTest
class CucumberIT

</code></pre>

<p>Does anyone know who to configure JPA repository when working with cucumber?</p>
",https://stackoverflow.com/questions/55619855/how-to-configure-spring-boot-jpa-for-cucumber-integration-testing,"['java', 'spring', 'spring-boot', 'kotlin', 'cucumber']",1237,False,2,0
Trying to mock Laravel Socialite Google Login for integration testing,"<p>I am trying to mock Laravel Socialite to test Google oAUTH Login using the guide <a href=""https://stefanzweifel.io/posts/how-i-write-integration-tests-for-laravel-socialite-powered-apps/"" rel=""nofollow noreferrer"">here</a>.</p>

<pre class=""lang-php prettyprint-override""><code>use Laravel\Socialite\Facades\Socialite;
use Laravel\Socialite\Two\GoogleProvider;
use Laravel\Socialite\Two\User as SocialUser;

public function mock_socialite ($email = 'foo@gmail.com', $token = 'foo', $id = 1)
    {
        // create a mock user
        $socialiteUser = $this-&gt;createMock(SocialUser::class);
        $socialiteUser-&gt;token = $token;
        $socialiteUser-&gt;id = $id;
        $socialiteUser-&gt;email = $email;

        // create a mock provider of the user
        $provider = $this-&gt;createMock(GoogleProvider::class);
        $provider-&gt;expects($this-&gt;any())
            -&gt;method('user')
            -&gt;willReturn($socialiteUser);

        // create a mock Socialite instance
        $stub = $this-&gt;createMock(Socialite::class);
        $stub-&gt;expects($this-&gt;any())
            -&gt;method('driver')
            //-&gt;with('google')
            -&gt;willReturn($provider);

        // Replace Socialite Instance with our mock
        $this-&gt;app-&gt;instance(Socialite::class, $stub);
    }
</code></pre>

<p>However, I am getting the below error:</p>

<pre><code>Trying to configure method ""driver"" which cannot be configured 
because it does not exist, has not been specified, is final, or is static
</code></pre>

<p>I checked and found that <code>driver()</code> method does exist in <code>Illuminate\Support\Manager</code> (from where <code>Socialite</code> is extended) and this method is a public method. Not sure why am I getting this error.</p>
",https://stackoverflow.com/questions/57053640/trying-to-mock-laravel-socialite-google-login-for-integration-testing,"['php', 'laravel', 'phpunit', 'laravel-socialite']",1120,True,1,1
Spring integration testing for REST call of some other Service,"<p>I've been searching it on the net , but most of the examples i found have the returning logic of rest call within the same project , but what if you want to test a rest call of some other service which you are using it in your project(calling a REST api from a REST API)</p>

<p>is there any way to integrate this . Integration testing for a REST call which is of some external service </p>

<p>can the normal Integration testing approach could work in this case.</p>
",https://stackoverflow.com/questions/54691241/spring-integration-testing-for-rest-call-of-some-other-service,"['spring-boot', 'integration-testing', 'spring-test']",336,True,0,1
Serilog console outputs doesn&#39;t show up during Integration Testing with WebApplicationFactory,"<p>The log entry shows up fine in the test console when I call <code>Log.Information(""Test"")</code> from my integration test file. If I call the same static function from within the controller being tested with a <strong>WebApplicationFactory</strong>, nothing will show up in the test console. </p>

<p>Oddly enough, <code>Console.WriteLine(""Test"")</code> also doesn't show up in the test console when called from a controller created with a <strong>WebApplicationFactory</strong></p>

<p>Is there a way to display in the test console log entries dispatched from controllers being tested using a <strong>WebApplicationFactory</strong>? Or simply a way to redirect console output from the created WebHost to the test output?</p>
",https://stackoverflow.com/questions/58792616/serilog-console-outputs-doesnt-show-up-during-integration-testing-with-webappli,"['asp.net-core', 'console', 'integration-testing', 'serilog']",256,False,3,0
Integration testing an application with Scheduler and Rest calls Spring Boot,"<p>I have an application with a Cron job that makes a REST call every couple of minutes and stores the data in hazelcast instance. It also exposes REST endpoints to provide the processed data from hazelcast instance to client. I want to write integration test case for the same preferably by mocking the REST call in the cron job as it is to a third system. Would need some suggestions or solution recommendations on how to do the same.</p>
",https://stackoverflow.com/questions/59154387/integration-testing-an-application-with-scheduler-and-rest-calls-spring-boot,"['rest', 'spring-boot', 'integration-testing', 'scheduler', 'hazelcast']",447,False,3,1
Start a process from another project for integration testing in C#,"<p>I have a .NET Framework project that requires running a built console application from a .NET Core project in the same solution.</p>

<p>Take the example file structure:</p>

<ul>
<li><code>Test/bin/Debug/Test.exe</code></li>
<li><code>Service/bin/Debug/netcoreapp2.2/Service.dll</code></li>
</ul>

<p>The current approach involves <a href=""https://stackoverflow.com/questions/181719/how-do-i-start-a-process-from-c"">starting a new process</a>, similar to the following:</p>

<pre><code>dotnet run ../../../Service/bin/Debug/netcoreapp2.2/Service.dll
</code></pre>

<p>I am fairly new to .NET, and so unsure if the following ideas are possible:</p>

<ul>
<li>Modifying the path when running the Test application so that I can start the Service process with <code>dotnet run Service.dll</code>.</li>
<li>Getting the Test project to copy the Service build files into the Test build folder.</li>
</ul>

<p>For bonus points, if/when the Framework project is upgraded to Core, is it possible to start a Core application process by <code>using</code> it in another application?</p>

<p><strong>Edit:</strong></p>

<p>For clarification, I'm hoping to avoid using that hard-coded relative path to build output folder, since it changes between Framework and Core and different versions of Core.
My hope is to find a built-in variable or functionality to get the build location of another project (even if I need to hard-code the Debug/Release part).</p>

<p>For example (excuse the pseudocode):</p>

<pre><code>using Service;
var path = getPathToDebugBuildFolder(Service);
startProcess(Path.Join(path, ""Service.dll""));
</code></pre>
",https://stackoverflow.com/questions/55653198/start-a-process-from-another-project-for-integration-testing-in-c,"['c#', '.net', '.net-core']",621,False,3,1
How you manage EM or EMF in integration testing with testcontainers?,"<p>I have java web application and I would like to write integration tests for service layer. I decided to use <a href=""https://www.testcontainers.org/"" rel=""nofollow noreferrer"">testcontainers</a>, so in test I would like to call service, which will work with database in docker container.</p>

<p>My test class looks like example below.</p>

<pre><code>@Testcontainers
class ITPlayerServiceImpl {

  @Container
  private static final PostgreSQLContainer POSTGRE_SQL_CONTAINER = 
  new PostgreSQLContainer()
            .withDatabaseName(""dbName"")
            .withUsername(""dbUserName"")
            .withPassword(""dbPassword"");
}
</code></pre>

<p>Tested service.</p>

<pre><code>@Stateless
public class PlayerServiceImpl implements PlayerService {

  @PersistenceContext(unitName = ""persistence_unit_name"")
  private EntityManager entityManager;

  //Methods
</code></pre>

<p>I need create EMF connected to DB in container and then populate EM from that EMF into tested service.</p>

<p>Thank you for help or hints.</p>
",https://stackoverflow.com/questions/55608369/how-you-manage-em-or-emf-in-integration-testing-with-testcontainers,"['java', 'integration-testing', 'entitymanager', 'testcontainers']",1190,True,2,1
Can&#39;t configure module for integration testing in Spring - no tasks available,"<p>I'm facing troubles in configuring module for integration tests for <code>Spring</code> using <code>Groovy</code> and <code>Spock</code>. After I click <code>run</code> button (in Intellij) it says  </p>

<blockquote>
  <p>no tasks available</p>
</blockquote>

<p>What I've done so far is:</p>

<pre><code>package gcptraindata


import gcptraindata.mysql.TestDataSourceConfig
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner
import org.springframework.test.context.web.WebAppConfiguration
import spock.lang.Specification

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = [TestDataSourceConfig])
@WebAppConfiguration
class IntegrationSpec extends Specification {

@Autowired
protected TestRestTemplate restTemplate

def 'sample test'(){
    given:
        def bla = 0

    when:
        bla += 2

    then:
        bla == 2
}


}
</code></pre>

<p>and datasource:  </p>

<pre><code>package gcptraindata.mysql

import org.springframework.boot.autoconfigure.flyway.FlywayDataSource
import org.springframework.boot.jdbc.DataSourceBuilder
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary

import javax.sql.DataSource

@Configuration
class TestDataSourceConfig {

@Primary
@Bean
@FlywayDataSource
DataSource dataSource() {
    return DataSourceBuilder.create()
            .driverClassName('com.mysql.jdbc.Driver')
            .username('gcpuser')
            .password('Domin')
            .url('jdbc:mysql://${MYSQL_HOST:localhost}:3306/test?serverTimezone=UTC')
            .build() as DataSource

}

}
</code></pre>

<p>I want to have configured everything in my build.gradle, so here it is:  </p>

<pre><code>    plugins {
    id 'java'
    id 'groovy'
    id 'application'
    id 'org.springframework.boot' version '2.1.7.RELEASE'
}

    apply plugin: 'java'
    apply plugin: 'groovy'
    apply plugin: 'io.spring.dependency-management'


    project.group = 'gcp-train-data'
    project.version = '0.0.1'
    mainClassName = 'gcptraindata.AppRunner'

repositories {
    mavenCentral()
    jcenter()
}

configurations {
    developmentOnly
    integrationCompile.extendsFrom testCompile
}

sourceSets {
    integration {
        java.srcDir file('src/integration/groovy')
    }
}

jar {
    enabled = true
}

dependencies {
    compile group:      'org.springframework.boot', name: 'spring-boot-starter-web'
    compile group:      'org.springframework.boot', name: 'spring-boot-starter-data-jpa'
    compile group:      'org.springframework.boot', name: 'spring-boot-starter-jdbc'
    compile group:      'org.springframework.boot', name: 'spring-boot-configuration-processor'
    compile group:      'org.codehaus.groovy',      name: 'groovy-all',             version: '2.5.7'
    compile group:      'mysql',                    name: 'mysql-connector-java',   version: '5.1.47'

    annotationProcessor    group: 'org.projectlombok',         name: 'lombok'

    integrationCompile group: 'org.spockframework',        name: 'spock-core',               version: '1.3-groovy-2.5'
    integrationCompile group: 'org.spockframework',        name: 'spock-spring',             version: '1.3-groovy-2.5'
    integrationCompile group: 'org.springframework.boot',  name: 'spring-boot-starter-test'
    integrationCompile group: 'org.codehaus.groovy',       name: 'groovy-all',               version: '2.5.7'
}
</code></pre>

<p>What did I miss here?</p>
",https://stackoverflow.com/questions/58205098/cant-configure-module-for-integration-testing-in-spring-no-tasks-available,"['java', 'spring', 'gradle', 'groovy', 'spock']",1339,True,2,1
Angular integration testing: how to specify the target on a MouseEvent,"<p>I am trying to invoke a click event in my integration testing by using ""triggerEventHandler"" on one of the HTML elements. I expected that the ""target"" property of the event to be set by ""triggerEventHandler"". That is not happening. When I execute the test, the following error is logged in console: ""<em>Cannot read property 'tagName' of null</em>"" and this happens when I try to get the tagName of the target element.</p>

<p>How should I implement this test?</p>

<p>VIEW</p>

<pre><code>&lt;h1 class=""h1-class"" (click)=""click($event)"" (contextmenu)=""rightClick($event)""&gt;H1&lt;/h1&gt;
&lt;h2 class=""h2-class"" (click)=""click($event)"" (contextmenu)=""rightClick($event)""&gt;H2&lt;/h2&gt;
</code></pre>

<p>COMPONENT</p>

<pre><code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'biq-dbg',
  templateUrl: './biq-dbg.component.html',
  styleUrls: ['./biq-dbg.component.less']
})

export class BiqDbgComponent implements OnInit {

  constructor() {
  }

  ngOnInit() {
  }

  click(event: MouseEvent) {
    console.log(event);
    let targetElement = event.target as HTMLElement;
    if (targetElement.tagName.toLocaleLowerCase() == ""h1"")
      console.log(""H1 was clicked"");
    if (targetElement.tagName.toLocaleLowerCase() == ""h2"")
      console.log(""H2 was clicked"");
  }

  rightClick(event: MouseEvent) {
    console.log(event);
    let targetElement = event.target as HTMLElement;
    if (targetElement.tagName.toLocaleLowerCase() == ""h1"")
      console.log(""H1 was right-clicked"");
    if (targetElement.tagName.toLocaleLowerCase() == ""h2"")
      console.log(""H2 was right-clicked"");
  }
}
</code></pre>

<p>SPEC</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'

import { BiqDbgComponent } from './biq-dbg.component';

fdescribe('BiqDbgComponent', () =&gt; {
  let component: BiqDbgComponent;
  let fixture: ComponentFixture&lt;BiqDbgComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ BiqDbgComponent ]
    })
    .compileComponents();
  }));

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

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

  it('h1 should react to click', () =&gt; {
    let h1 = fixture.debugElement.query(By.css("".h1-class""));
    let mouseEvent: MouseEvent = new MouseEvent(""click"", { clientX: 10, clientY: 20, button: 0});

    h1.triggerEventHandler(""click"", mouseEvent);
    fixture.detectChanges();
  })

  fit('h1 should react to right-click', () =&gt; {
    let h1 = fixture.debugElement.query(By.css("".h1-class""));
    let mouseEvent: MouseEvent = new MouseEvent(""contextmenu"", { clientX: 10, clientY: 20, button: 2});

    h1.triggerEventHandler(""contextmenu"", mouseEvent);
    fixture.detectChanges();
  })
});
</code></pre>
",https://stackoverflow.com/questions/55911516/angular-integration-testing-how-to-specify-the-target-on-a-mouseevent,"['angular', 'angular-test']",791,True,1,1
Architecture for integration-testing a web extension with a web-server,"<p>I have a web extension whose functionality needs to be tested against a web server. The web extension is built using Webpack and should run on Chrome and Firefox. It has its own unit tests, but what's important is that we perform behavioral tests against the web server.</p>

<p>The web server currently is a Docker Compose project consisting of a Rails web server (whose port 3000 is exposed to the localhost) and an internal Postgres database.</p>

<p>Currently, we perform testing a little bit manually: we build the extension code into Chrome/Firefox source code, load that code into Chrome, and call an extension-internal function that performs various actions. We then check on the server that everything was received as expected.</p>

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

<p>We'd like to turn this into a more automated process, particularly with the aim of testing new branches of client and/or server against each other. Ideally, this process should run in a CI pipeline (GitLab CI) whenever a new branch of client and/or server is being pushed.</p>

<p>We thought about the following setup:</p>

<ul>
<li>There will be a new integration testing repository containing a Selenium hub and Chrome/Firefox instance</li>
<li>That repository will pull the respective client/server code to be tested from a specified branch</li>
<li>There is a Selenium test script that executes the required tests</li>
<li>The server is run natively inside the test environment, and not via Docker Compose</li>
</ul>

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

<p>The reason for doing this is that the server currently runs in a Docker Compose project. My thinking is that I should not run that alongside yet another Docker Compose Selenium project. Hence the idea to build it natively. But then again, that means requiring an extra build process.</p>

<p>So another variant could look like this:</p>

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

<p>Here, I'd run the server as-is as a Docker Compose project, run Selenium inside another Docker Compose project, both within the same testing environment. The client would communicate with the server via the localhost.</p>

<p>I specifically do not want to put this functionality into the client alone, or the server alone, which is why I thought about a separate repository.</p>

<p>To me, variant 2 seems more reasonable, but perhaps I am missing something obvious, and there could be an even simpler solution?</p>

<p>To make the questions more concrete:</p>

<ol>
<li>Does it make sense to put this functionality into an extra repository?</li>
<li>Is there a simpler approach to running the server code from this extra repository?</li>
<li>How would one define which version of client/server is being tested at any given time? Would I use this testing repository within the CI pipeline of both server and client, and always checkout the master of the respective other component to test against?</li>
</ol>
",https://stackoverflow.com/questions/58482405/architecture-for-integration-testing-a-web-extension-with-a-web-server,"['ruby-on-rails', 'selenium', 'google-chrome-extension', 'docker-compose', 'gitlab-ci']",53,False,1,0
What&#39;s the proper way of integration testing libraries that run injected code?,"<p>I have two software components: My application and a library (which is owned by my company, but another team), which is used by the application. The library is a client library for some service and performs HTTP requests. The library also maps the HTTP response to the internal representation of the application. This is done by injecting a mapping class into the library by the application.</p>

<p>I already have unit tests for the mapping class and for the application, whereas the client library call is always mocked.</p>

<p>Now I'm thinking of integration test the library and I'm not sure what's the best way to do that:</p>

<ul>
<li><p><strong>Mock the library call and only check that it's called with the correct parameters</strong></p>

<ul>
<li>Pro: If the internals of the library change (with a non-breaking change) I don't have to adapt my tests.</li>
<li>Con: The mapping class isn't integration tested. I can't be sure that the library is correctly configured or that the parameters the mapper gets from the library are what I expect them to be.</li>
</ul></li>
<li><p><strong>Mock only the HTTP call done by the library</strong></p>

<ul>
<li>Pro: The mapping class and the configuration of the library (if I configured it correctly) are tested.</li>
<li>Con: I need to figure out the internals of the library and check how the HTTP call of each test case will look like. Also if the library upgrades to a new version of the service, I would need to adapt all the HTTP mocks as well and actually shouldn't care about how the library internally works.</li>
</ul></li>
<li><p><strong>Replace the HTTP call in the library with an in-memory fake (=dummy) implementation during testing</strong></p>

<ul>
<li>Pro: Everything is tested + the tests are resilient against library changes.</li>
<li>Con: It's an effort to implement and maintain a fake implementation. Depending on the service, this could mean rebuilding the functionalities of the service in the library.  Who should be responsible (implementation + maintenance) for the fake strategy? My team or the team that owns the library?</li>
</ul></li>
</ul>

<p>I'm in favor of the last point, but given that the internals of our library rarely changes, I'm not sure if a fake strategy is worth the effort. </p>

<p>What's your opinion on this? Can you think of another solution?</p>
",https://stackoverflow.com/questions/54862209/whats-the-proper-way-of-integration-testing-libraries-that-run-injected-code,"['dependency-injection', 'automated-tests', 'integration-testing']",994,True,6,1
Are there any frameworks available for Integration testing in Angular 5,"<p>I am trying to write integration tests for angular app, where I don't want to mock the backend and would want to test the response that is received. Is there any way by which I can do this in Angular.</p>
",https://stackoverflow.com/questions/55656446/are-there-any-frameworks-available-for-integration-testing-in-angular-5,['angular'],23,False,0,0
Unable to run play application using sbt Tests.setup for integration testing,"<p>I want to run my integration tests over play.test.TestServer. So all tests will be just sending Http requests to TestServer and asserting the Http results.</p>

<p>However if I start TestServer in the @BeforeClass method test suite, it takes so much time to run all integration tests since I need to start and stop play server for each suite.</p>

<p>So I decided to start play test server using sbt's Tests.Setup method</p>

<pre><code>Tests.Setup(loader=&gt;   
    loader.loadClass(""it.PlayTestRunner"")
       .getMethod(""startup"")
       .invoke(null)
)
</code></pre>

<p>I am able to call startup method but it throws below exception</p>

<pre><code>Caused by: java.lang.ClassNotFoundException: tyrex.naming.MemoryContextFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at com.sun.naming.internal.VersionHelper12.loadClass(VersionHelper12.java:72)
at com.sun.naming.internal.VersionHelper12.loadClass(VersionHelper12.java:61)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:672)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.init(InitialContext.java:244)
at javax.naming.InitialContext.&lt;init&gt;(InitialContext.java:216)
at play.api.libs.JNDI$.initialContext$lzycompute(JNDI.scala:40)
at play.api.libs.JNDI$.initialContext(JNDI.scala:22)
at play.api.db.HikariCPConnectionPool$$anonfun$1$$anonfun$apply$2.apply(HikariCPModule.scala:63)
</code></pre>

<p>I guess this problem is related with classloading JNDI objects.</p>

<p>Do you know any idea to overcome this problem?</p>
",https://stackoverflow.com/questions/54958636/unable-to-run-play-application-using-sbt-tests-setup-for-integration-testing,"['playframework', 'sbt', 'integration-testing']",51,True,0,1
How to fix this issue with running integration testing in Flutter?,"<p>When trying to do integration testing with this command</p>

<p><code>lutter drive --target=my_app/test_driver/my_test.dart</code></p>

<p>I always get this error:</p>

<pre><code>       The flutter tool requires Git in order to operate properly;
       to set up Flutter, run the following command:
       git clone -b stable https://github.com/flutter/flutter.git
</code></pre>

<p>When I follow what they said by running <code>git clone -b stable https://github.com/flutter/flutter.git</code> I always recieve this:</p>

<pre><code>fatal: destination path 'flutter' already exists and is not an empty directory.
macpros-MBP:flutter_app CompteEtudiant$ 
</code></pre>
",https://stackoverflow.com/questions/56132817/how-to-fix-this-issue-with-running-integration-testing-in-flutter,"['git', 'flutter', 'flutter-dependencies', 'flutter-test']",107,False,0,0
How to create apache spark standalone cluster for integration testing using TestContainers?,"<p>Is anyone knows how to create an apache-spark cluster for integration testing using testContainers <a href=""https://www.testcontainers.org/"" rel=""nofollow noreferrer"">https://www.testcontainers.org/</a></p>

<p>any running example please, i am struggling to find that.</p>
",https://stackoverflow.com/questions/59245356/how-to-create-apache-spark-standalone-cluster-for-integration-testing-using-test,"['spring-boot', 'docker', 'apache-spark', 'integration-testing', 'testcontainers']",974,True,4,1
How can I do an in-memory SQL Server for integration testing?,"<p>I want to be able to create a database and tables the same way Amazon's DynamoDb client does it but with Sql Server. Is that possible?</p>

<p>I'm using .net Core and this is for integration tests. Figured I can throw in the code in the fixture.</p>

<p>Anyone have any ideas?</p>
",https://stackoverflow.com/questions/54557795/how-can-i-do-an-in-memory-sql-server-for-integration-testing,"['sql-server', 'testing', '.net-core', 'amazon-dynamodb']",1443,True,4,2
Web API - Issues with HttpContext.Current in owin for integration testing using moq,"<p>I am building a Web API application which will be hosted in an IIS environment. In order to perform end to end integration testing of my service(no mocking), I am using OWIN.</p>

<p>The problem is deep down in my service architecture, at the repository layer I am making use of <code>HttpContext.Current</code> to retrieve values from the header(say UserId). <a href=""https://stackoverflow.com/a/54620606/1169180"">See this answer</a></p>

<p>If you look into the above code, I am making use <code>GetUserInfo</code> method throughout my application to fetch current user information. Another way to do is pass it as a parameter in all method(which I don't personally want to do).</p>

<p>I went through this great <a href=""https://stackoverflow.com/a/27826059/1169180"">answer</a> about including <code>IOwinContext</code> into the repository. I have tried it and it worked for self-hosting, but my end goal is to deploy the application on IIS.</p>

<p>My Questions:</p>

<ul>
<li>Is there any way my code can handle both the use cases of OWIN self-hosting for integration testing &amp; actual service deployment on IIS?</li>
<li>Is there any issue with my architecture? Something like I shouldn't be using OWIN at all, and use other tools like <code>POSTMAN</code> for testing.</li>
</ul>

<p>I can post some code if it's required.</p>

<p><strong>Edit:</strong></p>

<p>As suggested by @Nkosi I might have to mock my <code>HeaderService</code> in order to perform integration testing with owin. I am not sure how can I mock one certain method using <code>moq</code>. Here is my code. Its strip down version in order to make as simple as possible.</p>

<p>Code:</p>

<pre><code>public class CreditController : ApiController
{
    private readonly ICreditService _creditService;

    public CreditController(ICreditService creditService)
    {
        _creditService = creditService;
    }

    public IHttpActionResult CreditSummary([FromUri]string requestId)
    {
        var response = _creditService.GetCreditSummary(requestId);
        return Ok(response);
    }
}

public class CreditService : ICreditService
{
    private readonly IHeaderService _headerService;
    private readonly ICreditRepository _creditRepository;

    public CreditService(ICreditRepository creditRepository, IHeaderService headerService)
    {
        _headerService = headerService;
        _creditRepository = creditRepository;
    }

    public CreditObj GetCreditSummary(string req)
    {
        var userId = _headerService.GetHeaderFromHttpRequest();//Get User
        var response = _creditRepository.GetDataFromDatabase(req, userId);
        return response;
    }
}

public interface IHeaderService
{
    string GetHeaderFromHttpRequest();
}

public class HeaderService : IHeaderService
{
    public string GetHeaderFromHttpRequest()
    {
        return HttpContext.Current.Request.Headers[""USERID""];
    }
}
</code></pre>

<p>Below is my code for integration testing: I am using OWIN for self-host. So i want to call the controller method but my <code>GetHeaderFromHttpRequest</code> method should return mock response.</p>

<pre><code>[TestClass]
public class IntegrationTest
{
    private static HttpClient _client;
    private static IDisposable _webApp;

    [ClassInitialize]
    public static void Init(TestContext testContext)
    {
        _webApp = WebApp.Start&lt;Startup&gt;(url: Url);
        _client = new HttpClient
        {
            BaseAddress = new Uri(Url)
        };
    }

    [TestMethod]
    public void TestDashboard()
    {
        var headerStub = new Mock&lt;IHeaderService&gt;();
        headerStub.Setup(s =&gt; s.GetHeaderFromHttpRequest())
            .Returns(""MockUserId"");

        var builder = new UriBuilder(Url + ""api/Credit/CreditSummary"");

        HttpResponseMessage responseMessage = _client.GetAsync(builder.ToString()).Result;
        Assert.IsNotNull(responseMessage);
    }
}

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        WebApiConfig.Register(config); //This method having all routing/dependancy configuration
        app.UseWebApi(config);
    }
}
</code></pre>

<p><strong>Problem:</strong></p>

<ul>
<li>When I debug this test case, how do I make sure that <code>_headerService.GetHeaderFromHttpRequest()</code> return mock response. As of now I dont know how can i inject my mocking service to actual controller method call.</li>
</ul>

<p>Any advise?</p>
",https://stackoverflow.com/questions/55286550/web-api-issues-with-httpcontext-current-in-owin-for-integration-testing-using,"['c#', 'asp.net-web-api', 'owin', 'moq', 'httpcontext']",521,True,2,2
Spring Integration Testing does not pick up JPA beans from other modules,"<p>I have a multi module maven project. In one module I have all my persistence stuff like entities and repositories and in another module I import that persistence module and I want to run some integration tests.
The problem is that my tests do not pick up repositories and can't create the context because of the missing beans. Can someone help me with what I am missing?</p>

<p>The project structure looks like this</p>

<ul>
<li>persistence module</li>
<li>business logic module</li>
<li>web module</li>
</ul>

<p>In my business logic module pom I import the persistence module</p>

<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;com.acme&lt;/groupId&gt;
    &lt;artifactId&gt;persistence&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>

<p>My integration tests configuration</p>

<pre><code>@Configuration
@ComponentScan({""com.acme.persistence"", ""com.acme.business""})
@EnableAutoConfiguration
public class DataTestConfig {

}
</code></pre>

<p>and all my tests are annotated with the following</p>

<pre><code>@SpringJUnitConfig(DataTestConfig.class)
@DataJpaTest
</code></pre>

<p>If I move all the persistence module inside the business module then the tests work fine, but I want to keep them in separate modules.
Thanks</p>
",https://stackoverflow.com/questions/58904043/spring-integration-testing-does-not-pick-up-jpa-beans-from-other-modules,"['java', 'spring', 'spring-boot', 'spring-data-jpa', 'spring-data']",490,True,1,1
ASP.net core integration testing with inherited Startup class. Unable to locate View,"<p>I am attempting to write some integration tests against aspnet core 2.2.  I want to use a TestStartup class that inherits from the normal Startup class to configure resources and services for testing purposes.</p>

<p>A simple example (can be found here: <a href=""https://github.com/davidgouge/aspnet-integration-testing"" rel=""nofollow noreferrer"">https://github.com/davidgouge/aspnet-integration-testing</a>):</p>

<p>I have a solution that contains two projects:</p>

<p>IntegrationTestingWeb (a barebones aspnet mvc app)
IntegrationTestingTests (a testing project)</p>

<p>I have a test that uses the Web Startup class and asserts that OK is returned from <code>/Home/Privacy</code></p>

<pre><code>[Test]
public async Task GetPrivacy_Through_Normal_Startup()
{
    var builder = new WebHostBuilder().UseStartup&lt;Startup&gt;();
    var client = new TestServer(builder).CreateClient();
    var result = await client.GetAsync(""/Home/Privacy"");
    result.StatusCode.Should().Be(HttpStatusCode.OK);
}
</code></pre>

<p>This test passes.</p>

<p>If I create a TestStartupInTestProject class that inherites from Startup but place it in the Tests project, then I have to do some extra work when creating the WebHostBuilder but then the test fails.</p>

<pre><code>[Test]
    public async Task GetPrivacy_Through_Test_Startup_In_Test_Project()
    {
        var builder = new WebHostBuilder().ConfigureServices(services =&gt;
        {
            var startupAssembly = typeof(TestStartupInTestProject).GetTypeInfo().Assembly;

            var manager = new ApplicationPartManager();
            manager.ApplicationParts.Add(new AssemblyPart(startupAssembly));
            manager.ApplicationParts.Add(new AssemblyPart(typeof(HomeController).Assembly));
            manager.FeatureProviders.Add(new ControllerFeatureProvider());
            manager.FeatureProviders.Add(new ViewComponentFeatureProvider());
            services.AddSingleton(manager);
        }).UseStartup&lt;TestStartupInTestProject&gt;();
        var client = new TestServer(builder).CreateClient();

        var result = await client.GetAsync(""/Home/Privacy"");

        result.StatusCode.Should().Be(HttpStatusCode.OK);
    }
</code></pre>

<p>The error in the failure is:</p>

<pre><code>Tests.Tests.GetPrivacy_Through_Test_Startup_In_Test_Project

System.InvalidOperationException : The view 'Privacy' was not found. The 
following locations were searched:
/Views/Home/Privacy.cshtml
/Views/Shared/Privacy.cshtml
/Pages/Shared/Privacy.cshtml
</code></pre>

<p>So it looks like because my Startup class is located in the Test project, the views cannot be located.  What setting am I missing to be able to find the Views?</p>
",https://stackoverflow.com/questions/55021393/asp-net-core-integration-testing-with-inherited-startup-class-unable-to-locate,"['unit-testing', 'asp.net-core', 'integration-testing']",414,True,1,1
How do I set up a second remote database for integration testing?,"<p>I need advice on what method will suit better for my case.</p>

<p>I have a Java application with Spring Boot, and right now, for the testing part, I use a localhost PostgreSQL database. The setup is quite simple; I just have the datasource.url/username/password and port setup in the application.properties file.</p>

<p>Now, I need to use a remote PostgreSQL database for a particular integration test class. So, as far as I know, I can do this in at least two ways:</p>

<ul>
<li><p>I can set up in application.properties another configuration for the remote database, and use it in the test class with <code>environment.getProperty()</code>.</p></li>
<li><p>Or, I can make a bean to use those properties:</p>

<pre><code>@Bean
public DataSource dataSource() {
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.url(dbUrl);
        dataSourceBuilder.username(username);
        dataSourceBuilder.password(password);
        return dataSourceBuilder.build();   
}
</code></pre></li>
</ul>

<p>And the things are not as simple as they may seem.
I have a class for tests configuration, <strong>ClassA</strong>.</p>

<p>I have a second class with actual tests, let's call it <strong>ClassB</strong>.</p>

<p>ClassB extends Class A, and ClassA starts a JAR file, which is another Java application which exposes some rest APIs, which will be tested with the tests from ClassB.</p>

<p>Now I use a local database, but I will want to use the remote one, in the future.</p>

<p>I managed to download the JAR file from Artifactory with a Maven dependency, and in the configuration class I search for the JAR file, I get the directory of it, and use an array of commands to run it: <code>{""java"", ""-jar"", ""directory.getCanonicalPath()}</code>, and <code>ProcessStreamer</code> to process it.</p>

<p>After I check the JAR file is up and running, the tests from ClassB are triggered, and they do CRUD operations against the recently opened application making REST calls to the APIs.</p>

<p>Any suggestions on how I can set up the second remote database?</p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/54636227/how-do-i-set-up-a-second-remote-database-for-integration-testing,"['java', 'postgresql', 'spring-boot', 'integration-testing', 'urlconnection']",217,True,0,1
Integration testing using @SpringBootTest is not picking auto-configuration of library configured using spring.factories,"<p>We have a library ,in order to auto-configure the library we use spring.factories file under(<code>src/main/resources/META-INF</code>) which provides classes to auto-configure my library. </p>

<p>Reference : <a href=""https://docs.spring.io/spring-boot/docs/1.4.0.M3/reference/htmlsingle/#boot-features-custom-starter"" rel=""noreferrer"">https://docs.spring.io/spring-boot/docs/1.4.0.M3/reference/htmlsingle/#boot-features-custom-starter</a></p>

<p>I have below configuration in spring.factories file : </p>

<pre><code>org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.x.y.PubSubConfig
</code></pre>

<p>My understanding is spring.factories is an alternative to configure library and server purpose similar to <code>@SpringBootApplication</code> in a normal application.</p>

<p>I am doing integration using using <code>@SpringBootTest</code>, I expect my context to be configured from configuration classes provided by spring.factories. When i run these tests spring does not identify spring.factories and throws an error </p>

<blockquote>
  <p>java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test</p>
</blockquote>

<ul>
<li>If i annotate my <code>PubSubConfig</code> with SpringBootApplication then my integration tests run perfectly fine but since it is a library I don't wanna do so.</li>
<li>If I provide my configuration class specifically using <code>@SpringBootTest(classes = PubSubConfig.class)</code> my tests run fine. </li>
</ul>

<p>Now I am trying to understand why I need to do either of above dedicatedly as spring.factories is responsible to do my auto-configure</p>
",https://stackoverflow.com/questions/56594410/integration-testing-using-springboottest-is-not-picking-auto-configuration-of-l,"['spring', 'spring-boot', 'integration-testing', 'spring-test']",3985,True,9,2
How to provide a mock interface to Autofac in AspNet Core integration testing?,"<p>I have a web api project that I'm trying to integration test. The controller is:</p>

<pre><code>[Route(""hello"")]
public sealed class MyController : Controller
{
   private readonly IFoo _foo;

   public MyController(IFoo foo)
   {
      _foo = foo;
   }

   [HttpGet]
   public IActionResult Hello()
   {
       _foo.MethodToVerify();
       return Ok(""Foo"");
   }
}
</code></pre>

<p><code>IFoo</code> is registered in the WebApi using Autofac in <code>ContainerBuilder</code> (builder) like</p>

<pre><code>public void Load(ContainerBuilder builder)
{
    builder.RegisterType&lt;FooImplementation&gt;()
           .WithAnotherInterface(builder, ""hello"")
           .As&lt;IFoo&gt;();
}
</code></pre>

<p>Where <code>WithAnotherInterface(string)</code> is an extension method like:</p>

<pre><code>public static IRegistrationBuilder&lt;TLimit, TReflectionActivatorData, TStyle&gt; WithAnotherInterface&lt;TLimit, TReflectionActivatorData, TStyle&gt;(this IRegistrationBuilder&lt;TLimit, TReflectionActivatorData, TStyle&gt; reg, ContainerBuilder builder, string val)
  : where TReflectionActivatorData : ReflectionActivatorData
{
    builder.RegisterType&lt;AnotherInterfaceImplementation&gt;()
           .Named&lt;IAnotherInterface&gt;(""another"")
           .WithParameter(ResolvedParameter.ForNamed&lt;IErrorHandler&gt;(val))
           .AutoActivate()
           .SingleInstance();

    return registration;
}
</code></pre>

<p>Now in my test, I'm doing this:</p>

<pre><code>public class MyTest : IClassFixture&lt;WebApplicationFactory&lt;Startup&gt;&gt;
{
    private readonly IFoo _foo;
    private readonly HttpClient _client;
    private readonly WebApplicationFactory&lt;Startup&gt; _factory;

    MyTest(WebApplicationFactory&lt;Startup&gt; factory)
    {
        _foo = Mock.Of&lt;IFoo&gt;();
        _factory = factory;

        _client = _factory.WithWebHostBuilder(builder =&gt;
                  {
                       builder.ConfigureTestContainer&lt;ContainerBuilder&gt;(b =&gt;
                       {
                           b.Register(ctx =&gt; _foo).SingleInstance().As&lt;IFoo&gt;();
                       });
                  })
                  .CreateClient();
    }

    [Fact]
    public async Task Test()
    {
       var res = await _client.GetAsync(""hello"");

       var mock = Mock.Get(_foo);

       mock.Verify(v =&gt; v.MethodToVerify(), Times.Once);
    }
}
</code></pre>

<p>However, my verification is failing and recorded performed invocations are zero.</p>
",https://stackoverflow.com/questions/59101360/how-to-provide-a-mock-interface-to-autofac-in-aspnet-core-integration-testing,"['c#', 'integration-testing', 'autofac', 'xunit']",292,False,0,0
How to replace a bean with a testing mock in Spring Boot for integration testing,"<p>I have a spring app and integration tests for this app. I would like to replace a bean with a mock bean. </p>

<p>My real bean looks like this </p>

<pre><code>@Service
public class MyService {

}
</code></pre>

<p>and for testing I would like it to be replaced</p>

<pre><code>@Service
public class TestMyService {

}
</code></pre>

<p>All I can think of is to use profiles for different services. For example:</p>

<pre><code>@Service
@Profile(""!test"")
public class MyService implements IMyService {

}

@Service
@Profile(""test"")
public class TestMyService implements IMyService {

}
</code></pre>

<p>And then I autowire the bean like this</p>

<pre><code>@Autowired
private IMyService myService;
</code></pre>

<p>Is there a better way?</p>
",https://stackoverflow.com/questions/54051491/how-to-replace-a-bean-with-a-testing-mock-in-spring-boot-for-integration-testing,"['spring', 'spring-boot']",9679,True,11,4
Spring Cloud Stream Listener not pausing / waiting for the messages in Integration Testing Code,"<p>I am having a Application which connects to RabbitMQ through Spring Cloud Stream, which works prefectly.</p>

<p>For <strong>Integration test cases</strong> i am trying to use the sample - <a href=""https://github.com/piomin/sample-message-driven-microservices/blob/master/account-service/src/test/java/pl/piomin/services/account/OrderReceiverTest.java"" rel=""nofollow noreferrer"">https://github.com/piomin/sample-message-driven-microservices/blob/master/account-service/src/test/java/pl/piomin/services/account/OrderReceiverTest.java</a></p>

<p>However, in my case my application sends back 3 messages in some time Interval. So if i put the below Lines, it fetches the messages, but if the there is a delay in getting the messages.</p>

<pre><code> int i = 1;
    while (i &gt; 0) {
        Message&lt;String&gt; received = (Message&lt;String&gt;) collector.forChannel(channels.statusMessage()).poll();
        if (received != null) {
            LOGGER.info(""Order response received: {}"", received.getPayload());
        }
    }
</code></pre>

<ol>
<li>So Instead of my custom polling, is there any way i can wait and Poll for my messages, and stop when i get those ?</li>
<li>I want to get the pick Messages based on the Response Routing Key to different Channels. Is it possible ? 
--> Example: If the routingKey is ""InProcess"" , it should go to Inprocess Method.</li>
</ol>
",https://stackoverflow.com/questions/55697682/spring-cloud-stream-listener-not-pausing-waiting-for-the-messages-in-integrati,"['spring-boot', 'integration-testing', 'spring-cloud-stream']",265,False,-1,1
Integration Testing RabbitMQ listner - Intermittently failing because the message takes time to be queued,"<p>I have written an integration test for the following flow using RabbitMock (found it on github and it seems really cool):</p>

<p>Message gets added to Incoming-message-queue --> incoming message listner picks up the message --> processes it --> puts a new outgoing message to the new queue Outgoing-message-queue --> (only for tests) wrote a listner for this outgoing queue in src/test/resources. </p>

<p>Everything is working (with one important glitch - intermittent timeout) and I am doing asserts as shown below: </p>

<pre><code>List&lt;OutgoingData&gt; receivedMessages = new ArrayList&lt;&gt;();
            assertTimeoutPreemptively(ofMillis(15000L), () -&gt; {
                    while (receivedMessages.isEmpty()) {
                        OutgoingData data = 
receiver.getOutgoingData();
                        if(data != null){
                            receivedMessages.add(data);
                        }

                    }
                }
            );

            assertThat(receivedMessages.get(0)).isNotNull();

 assertThat
(receivedMessages.get(0).getRecipient())
.isEqualTo(""enabled@localhost"");
</code></pre>

<p>The timeout in this test is real issue I am facing. </p>

<ol>
<li>Because of the timeout, the tests are getting slow.</li>
<li>If I remove the timeout, tests are getting stuck in Jenkins and need to be killed forcefully.</li>
<li>At times, this 15000 milliseconds timeout is also not enough and the tests fail. </li>
</ol>

<p>I was wondering if there is a better way to deal with such a situation in the integration test.</p>

<p>Looking forward to your inputs. </p>

<p>Thanks a lot,
Banyanbat</p>
",https://stackoverflow.com/questions/54595653/integration-testing-rabbitmq-listner-intermittently-failing-because-the-messag,"['spring-rabbit', 'integration-testing']",302,True,0,1
How to use settings from integration testing project in the Startup class of api project?,"<p>I'm trying to write integration tests for web api, I have two appsettings.json files one for api project and other for integration tests. I want to use the values(azure storage connection strings) from integration testing project in Startup class of web api.</p>

<p>I have tried creating CustomWebApplicatonFactory it didn't work since the Startup class of web api gets settings like shown below.</p>

<pre><code>//Configure services method in Startup class
public virtual void ConfigureServices(IServiceCollection services)
{
      var settings = ConfigurationProvider.GetConfiguration();
      services.TryAddSingleton(settings);
      services.AddHttpClient();
      var azureTableStorageConnectionString = 
      settings[""AzureMainStoreConnectionStringSecretName""];

     //Other Startup related code
}
</code></pre>

<p>I want to change the value of ""azureTableStorageConnectionString"" from my integration test project. Help and suggestions are much appreciated.</p>
",https://stackoverflow.com/questions/58335095/how-to-use-settings-from-integration-testing-project-in-the-startup-class-of-api,"['c#', 'asp.net-core', 'asp.net-web-api', 'integration-testing']",493,True,2,1
React (Unit &amp; Integration): Which framework to use for react unit testing and Integration testing,"<p>I have just started with development in Reactjs. I am looking for testing framework(Javascript). Which can be used to do both ""Unit Testing"", ""Integration Testing"" and ""e2e testing"". </p>

<p>Please, help me if we can do the the required testing using Javascript.</p>
",https://stackoverflow.com/questions/57039857/react-unit-integration-which-framework-to-use-for-react-unit-testing-and-in,"['javascript', 'reactjs', 'unit-testing', 'integration-testing']",204,True,0,3
How to bypass [Authorize(Roles = &quot;Admin&quot;)] tag from all service calls when doing integration testing?,"<p>I would like to test an Asp.Net MVC Core 2.2 application locally using the Postman tool.
However, when I host my Asp.Net MVC application locally and call the APIs from another tool the calls are blocked due to [Authorize] tags. </p>
",https://stackoverflow.com/questions/58561417/how-to-bypass-authorizeroles-admin-tag-from-all-service-calls-when-doing,"['api', 'asp.net-core', 'authorize-attribute']",113,False,0,0
How to disable swagger function of startup class in web api core for integration testing,"<p>I am writing integration testing and came across a requirement to disable to calling adding swagger function in startup. I am using the same startup class without customizing it. </p>

<p>Please suggest some solution to get rid of swagger and it's inner function implementation like adding authentication.</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/59344652/how-to-disable-swagger-function-of-startup-class-in-web-api-core-for-integration,"['integration-testing', 'asp.net-core-webapi']",731,True,0,1
Flutter Integration Testing- How to go back to previous screen when no back button available on screen,"<p>How to go back to previous screen when no back button available on screen? 
Additional Information: I am trying to automate integration testing for flutter app. There is no back button on screen which I can use to go back screen. 
Additional information: I am writing integration tests, for same I need to go back to previous screen. And due to design there is no back button on screen, I need to do by scripts only.  </p>
",https://stackoverflow.com/questions/59044829/flutter-integration-testing-how-to-go-back-to-previous-screen-when-no-back-butt,"['flutter', 'dart', 'flutter-test']",3633,True,8,5
Can Redux DevTools be used to automate integration testing across a list of URLs or Actions?,"<p>Are there any good resources for using Redux DevTools for integration / end-to-end testing? </p>

<p>I see their Slider can replay events and Dispatcher executes just about anything. Can it somehow loop over a config file to replay common user flows on the site, and record the state changes along the way?</p>

<p><a href=""https://i.stack.imgur.com/SD6XP.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/SD6XP.png"" alt=""f ""></a></p>
",https://stackoverflow.com/questions/58180163/can-redux-devtools-be-used-to-automate-integration-testing-across-a-list-of-urls,"['reactjs', 'redux', 'automated-tests', 'integration-testing', 'redux-devtools']",86,False,2,0
How do I enable Windows Authentication on a Web API when using WebApplicationFactory for Integration Testing?,"<p>In ASP Net Core 3.0, how do I enable Windows Authentication to my WebAPI when using WebApplicationFactory to create Integration Tests.  Setting up the Test Host to Allow Anonymous requests is not an option due to the fact that my Domain Layer requires valid user information to perform systematic audit logging of all write requests and will throw an exception (by intention) if the UserPrincipal cannot be validated.</p>

<p>Thank you very much in advance for the assistance!</p>
",https://stackoverflow.com/questions/58087696/how-do-i-enable-windows-authentication-on-a-web-api-when-using-webapplicationfac,"['c#', 'asp.net-core', 'integration-testing']",173,False,1,0
How to test ImagePicker in Flutter Driver?,"<p>In Flutter integration testing, how can we handle ImagePicker? as well as other platform related plugins?</p>
",https://stackoverflow.com/questions/56588555/how-to-test-imagepicker-in-flutter-driver,['flutter-test'],4716,True,10,2
Embedded MongoDB configuration in .yml file in Spring Boot,"<p>Currently, we are using real MongoDB server for integration testing and it's connection configurations are defined in .yml file as follows:</p>

<pre><code>mongodb:
replica_set: ip/port,ip/port
dbname: mydb
username: abc
password: abc@123
</code></pre>

<p>Now we want to use below dependency for embedded MongoDB to mock MongoDB to perform integration testing.</p>

<pre><code>&lt;dependency&gt;
&lt;groupId&gt;de.flapdoodle.embed&lt;/groupId&gt;
&lt;artifactId&gt;de.flapdoodle.embed.mongo&lt;/artifactId&gt;
&lt;version&gt;1.50.5&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>

<p>How to define embedded MongoDB connection configurations in .yml file? Any help is really appreciated. </p>
",https://stackoverflow.com/questions/57213000/embedded-mongodb-configuration-in-yml-file-in-spring-boot,"['java', 'mongodb', 'spring-boot', 'integration-testing']",1131,False,0,0
"Gradle task dependencies: &quot;run integration tests&quot; vs &quot;deploy, run integration tests, kill deployment&quot;","<p>I have a somewhat complex deployment task as well as an integration testing task. At the moment, my integration testing task depends on the deployment task. However, I'd like to have a sort of wrapper task for the integration testing task such that I can build a task to just run the integration test against whatever is currently running <strong>and</strong> a task to deploy, run the integration test, and then take down the deployment again.</p>

<p>This is the current state:</p>

<pre><code>task integrationTest(type: Test, dependsOn: ""startWebappNodes"") {
  testClassesDirs = sourceSets.integrationTest.output.classesDirs
  classpath = sourceSets.integrationTest.runtimeClasspath
  outputs.upToDateWhen { false }
}

task runIntegrationTests(type: Exec, dependsOn: ""integrationTest"") {
    commandLine 'docker-compose', 'down'
    doLast {
        println ""Integration tests running finished""
    }
}
</code></pre>

<p>How can I write a task, let's call it <code>executeIntegrationTest</code>, that executes the integration test without depending on <code>startWebAppNodes</code> and then also have a test that runs <code>startWebAppNodes</code>, then <code>executeIntegrationTest</code>, then brings down the nodes again?</p>
",https://stackoverflow.com/questions/54022862/gradle-task-dependencies-run-integration-tests-vs-deploy-run-integration-te,"['gradle', 'build.gradle']",280,True,0,1
Bad state: Mock method was not called within `when()`. Was a real method called?,"<p>I'm trying to make a mock of an <code>httpRequest</code> in flutter using mockito.</p>

<p>Here I define a global http client:</p>

<pre class=""lang-dart prettyprint-override""><code>library utgard.globals;

import 'package:http/http.dart' as http;

http.Client httpClient = http.Client();
</code></pre>

<p>Then I replace in integration testing:</p>

<pre class=""lang-dart prettyprint-override""><code>import 'package:flutter_driver/driver_extension.dart';
import 'package:http/http.dart' as http;
import 'package:utgard/globals.dart' as globals;
import 'package:mockito/mockito.dart';

import 'package:utgard/main.dart' as app;

class MockClient extends Mock implements http.Client {}

void main() {
  final MockClient client = MockClient();
  globals.httpClient = client;

  enableFlutterDriverExtension();

  app.main();
}
</code></pre>

<p>Then I try to use <code>when</code> of mockito:</p>

<pre class=""lang-dart prettyprint-override""><code>test('login with correct password', () async {
      final client = MockClient();

      when(globals.httpClient.post('http://www.google.com'))
          .thenAnswer((_) async =&gt; http.Response('{""title"": ""Test""}', 200));

      await driver.enterText('000000');
      await driver.tap(loginContinuePasswordButton);
    });
</code></pre>

<p>But I receive the following error:</p>

<blockquote>
  <p>Bad state: Mock method was not called within <code>when()</code>. Was a real method called?</p>
</blockquote>
",https://stackoverflow.com/questions/55424575/bad-state-mock-method-was-not-called-within-when-was-a-real-method-called,"['dart', 'flutter', 'mockito', 'flutter-test']",19002,True,35,4
How to test controller action in Grails 3.3.6 without using services,"<p>I have created Grails Application with one domain and controller. In development environment i have inserted two entry for domain.I want to perform integration testing such that it fetch records from the database and return the total size.Below is my source code which i tried.</p>

<p>Below is my domain</p>

<pre><code>Student.groovy.

import grails.gorm.transactions.Transactional

@Transactional
class Student {

String name
String rollnumber
    static constraints = {
    }
}
</code></pre>

<p>Below is my controller:-</p>

<pre><code>import grails.gorm.transactions.Transactional

@Transactional
class StudentController {

 def readall(){
       println ""inside read all ""+Student.getAll().size()
       respond Student.getAll()
     }
}
</code></pre>

<p>Below is my Integration Testing code:</p>

<pre><code>import grails.testing.gorm.DomainUnitTest
import grails.testing.mixin.integration.Integration
import grails.testing.web.controllers.ControllerUnitTest
import grails.validation.ValidationException
import spock.lang.Specification
@Integration
class StudentControllerSpec extends Specification implements ControllerUnitTest&lt;StudentController&gt;, DomainUnitTest&lt;Student&gt; {

void ""getAllStudentList""(){
        given:
        def studentList=[]
        when:
        request.method = 'GET'
        controller.readall()
        println studentList.size()
        then:
        studentList.size()==1

    }
}
</code></pre>

<p>Below is my application.yml file</p>

<pre><code>---
hibernate:
    cache:
        queries: false
        use_second_level_cache: false
        use_query_cache: false
dataSource:
    pooled: true
    jmxExport: true
    driverClassName: org.h2.Driver
    username: sa
    password: ''

environments:
    development:
        dataSource:
            dbCreate: create-drop
            url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    test:
        dataSource:
            dbCreate: update
            url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    production:
        dataSource:
            dbCreate: none
            url: jdbc:h2:./prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
            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>

<p>i'm getting below exception while running test case </p>

<pre><code>
Configuring Spring Security Core ...
... finished configuring Spring Security Core

2019-04-21 16:05:07.979 ERROR --- [    Test worker] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'methodValidationPostProcessor' defined in class path resource [org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.class]: Unsatisfied dependency expressed through method 'methodValidationPostProcessor' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateDatastoreServiceRegistry': Cannot resolve reference to bean 'hibernateDatastore' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateDatastore': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.grails.orm.hibernate.HibernateDatastore]: Constructor threw exception; nested exception is org.hibernate.MappingException: Could not determine type for: org.springframework.transaction.PlatformTransactionManager, at table: student, for columns: [org.hibernate.mapping.Column(transaction_manager)]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1181)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1075)
    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:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:225)
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:703)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:528)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
</code></pre>
",https://stackoverflow.com/questions/55782038/how-to-test-controller-action-in-grails-3-3-6-without-using-services,"['testing', 'grails', 'groovy', 'integration', 'spock']",195,False,0,1
"Oauth minitest error, callback link giving an error","<p>I am trying to write tests for OmniAuth users and after setting up my test_helper, I am running into and a bad URI error.Sharing the details below: </p>

<blockquote>
  <p>test_helper.rb</p>
</blockquote>

<pre><code># OmniAuth auth mock for testing
  def setup_omniauth_mock (user)
    OmniAuth.config.test_mode = true
    OmniAuth::AuthHash.new ({
    'provider'            =&gt; 'google',
    'uid'                 =&gt; '123545',
    'user_id'             =&gt; '2',
    'first_name'          =&gt; 'X',
    'last_name'           =&gt; 'XYZ',
    'email'               =&gt; 'xxyz@example.com',
    'image'               =&gt; 'https://lh3.googleusercontent.com//photo.jpg',
    'oauth_token'         =&gt; 'abcdef12345',
    'oauth_expires_at'    =&gt; DateTime.now,
    })
    OmniAuth.config.add_mock(:google, OmniAuth::AuthHash.new)
    get '/auth/"":google""/callback'
    Rails.application.env_config[""omniauth.auth""] = OmniAuth.config.mock_auth[:google]
    get '/auth/:google/callback'
  end 
</code></pre>

<p>The error I am getting: </p>

<pre><code>    test_validating_a_Google_OAuth_user#SessionsControllerTest (0.49s)
URI::InvalidURIError:         URI::InvalidURIError: bad
URI(is not URI?): http://www.example.com:80/auth/"":google""/callback
test/test_helper.rb:42:in `setup_omniauth_mock'
</code></pre>

<p>Now I followed the documentation here [Oauth Integration Testing][1]</p>

<p>[1]: <a href=""https://github.com/omniauth/omniauth/wiki/Integration-Testing"" rel=""nofollow noreferrer"">https://github.com/omniauth/omniauth/wiki/Integration-Testing</a> but I think there is something I am doing wrong.</p>

<p>Can someone please help me guide through this. </p>

<p>Thank you!
J.</p>
",https://stackoverflow.com/questions/54528374/oauth-minitest-error-callback-link-giving-an-error,"['ruby-on-rails', 'oauth', 'minitest']",118,True,0,1
What is difference between @MicronautTest and EmbeddedServer,"<p>What is difference between starting a server using <code>MicronautTest</code> and <code>EmbeddedServer</code> while using them in Unit/Integration testing in <code>Micronaut</code> framework.</p>

<p>Option A:</p>

<pre class=""lang-java prettyprint-override""><code>@MicronautTest
public class Test{

    @Inject
    EmbeddedServer server;
}
</code></pre>

<p>Option B:</p>

<pre class=""lang-java prettyprint-override""><code>EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer.class);
</code></pre>
",https://stackoverflow.com/questions/57567802/what-is-difference-between-micronauttest-and-embeddedserver,['micronaut'],2954,True,3,3
Implement Integration Testing with ASP.NET Core and NUnit,"<p>I am new to use NUnit integration testing with Asp core 2.2, I have already core RESTful Api but have no idea how to configure NUnit to implement integration test.
Usually I Implement it using Configuration file from Migration Folder as the following but no more exists in ASP Core 2.2 and I don't know what the new alternative.</p>

<pre><code>        var configuration = new Migrations.ApplicationDbContextModelSnapshot();
        var migrator = new Migrator(configuration);
        migrator.Update();
</code></pre>

<p>So please If you don't understand my question I just need an explicit link to use NUnit Integration Testing with .Net Core 2.2.</p>
",https://stackoverflow.com/questions/58120227/implement-integration-testing-with-asp-net-core-and-nunit,"['c#', 'asp.net-core', 'nunit', 'integration-testing']",239,True,-1,1
How to use these @DataMongoTest and @SpringBootTest together in integration test,"<p>I am trying to write integration test case for one of my rest application which uses mongodb internally to persist the data </p>

<pre><code>@DataMongoTest 
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MainControllerTest {
@LocalServerPort
    private int port = 8080;
/* some test cases*/ 
}
</code></pre>

<p>but I am getting below error </p>

<pre><code>java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class [com.sample.core.controller.MainControllerTest]: [@org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTestContextBootstrapper), @org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.context.SpringBootTestContextBootstrapper)]
</code></pre>

<p>looks like these two are mutually exclusive, so how to do the integration testing .</p>
",https://stackoverflow.com/questions/55474104/how-to-use-these-datamongotest-and-springboottest-together-in-integration-test,"['junit', 'integration-testing', 'spring-boot-test']",12453,True,19,3
How to do integration testing for custom mongo repository?,"<p>These are the following configuration that I have done in my project.</p>
<pre class=""lang-java prettyprint-override""><code>@Configuration
public class AppMongoConfig {
        
    @Autowired private MongoDbFactory mongoDbFactory;
        
    @Autowired private MongoMappingContext mongoMappingContext;
        
    @Bean
    public MappingMongoConverter mappingMongoConverter() {
        
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
        MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));
        
        return converter;
    }
}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(MultipleMongoProperties.class)
public class MultipleMongoConfig {
    
    private final MultipleMongoProperties mongoProperties;
    
    @Primary
    @Bean(name = &quot;primaryMongoTemplate&quot;)
    public MongoTemplate primaryMongoTemplate() throws Exception {
        return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
    }
    
    @Bean(name = &quot;secondaryMongoTemplate&quot;)
    public MongoTemplate secondaryMongoTemplate() throws Exception {
        return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));
    }
    
    @Bean
    @Primary
    public MongoDbFactory primaryFactory(final MongoProperties mongo) throws Exception {
        return new SimpleMongoDbFactory(new MongoClientURI(mongo.getUri()));
    }
    
    @Bean
    public MongoDbFactory secondaryFactory(final MongoProperties mongo) throws Exception {
        return new SimpleMongoDbFactory(new MongoClientURI(mongo.getUri()));
    }
}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>@Data
@ConfigurationProperties(prefix = &quot;mongodb&quot;)
public class MultipleMongoProperties {
    private MongoProperties primary = new MongoProperties();
    private MongoProperties secondary = new MongoProperties();
}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>@Configuration
@EnableMongoRepositories(
    basePackages = {&quot;com.student.repository.primary&quot;},
    mongoTemplateRef = &quot;primaryMongoTemplate&quot;)
    public class PrimaryMongoConfig {}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>@Configuration
@EnableMongoRepositories(
    basePackages = {&quot;com.student.repository.secondary&quot;},
    mongoTemplateRef = &quot;secondaryMongoTemplate&quot;)
public class SecondaryMongoConfig {}
</code></pre>
<p>Repository code:</p>
<pre class=""lang-java prettyprint-override""><code>public interface StudentDAO {
        
    Student save(StudentInfo studentInfo); 
} 
</code></pre>
<pre class=""lang-java prettyprint-override""><code>@Repository 
public class StudentDAOImpl implements StudentDAO {
       
    @Autowired   @Qualifier(&quot;primaryMongoTemplate&quot;)   
    private MongoTemplate mongoTemplate;
        
    @Override   public StudentInfo save(StudentInfo userWatchlist) {
        return mongoTemplate.save(userWatchlist);   
    } 
}
</code></pre>
<p>Integration Testing code:</p>
<pre class=""lang-java prettyprint-override""><code>@RunWith(SpringRunner.class)
@DataMongoTest(includeFilters = @Filter(Repository.class))
public class WatchListDAOImplIT {
    
    @Autowired private StudentDAO studentDAO;
    
    @Test
    public void save() {
        StudentInfo studentInfo = getStudentInfo();
        StudentInfo dbUserWatchlist = watchListDAO.save(studentInfo);
        Assert.assertEquals(studentInfo.getId(), dbUserWatchlist.getId());
    }
    
    private StudentInfo getStudentInfo() {
        StudentInfo studentInfo = new StudentInfo();
        studentInfo.setId(9999999l);
        return studentInfo;
    }
}
</code></pre>
<p>Which is giving me following error:-</p>
<pre><code>java.lang.IllegalStateException: Failed to load ApplicationContext
    at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
    at
org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
    at
org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:
: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'appMongoConfig': Unsatisfied dependency
expressed through field 'mongoDbFactory'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'primaryFactory' defined in class path
resource [.../config/mongo/MultipleMongoConfig.class]: Unsatisfied
dependency expressed through method 'primaryFactory' parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.boot.autoconfigure.mongo.MongoProperties'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations: {}

Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.boot.autoconfigure.mongo.MongoProperties'
available: expected at least 1 bean which
</code></pre>
",https://stackoverflow.com/questions/56002880/how-to-do-integration-testing-for-custom-mongo-repository,"['spring-boot', 'spring-data-mongodb', 'spring-properties']",375,False,1,0
How to create apache spark standalone cluster for integration testing using TestContainers?,"<p>Is anyone knows how to create an apache-spark cluster for integration testing using testContainers <a href=""https://www.testcontainers.org/"" rel=""nofollow noreferrer"">https://www.testcontainers.org/</a></p>

<p>any running example please, i am struggling to find that.</p>
",https://stackoverflow.com/questions/59245356/how-to-create-apache-spark-standalone-cluster-for-integration-testing-using-test,"['spring-boot', 'docker', 'apache-spark', 'integration-testing', 'testcontainers']",974,True,4,1
Spring integration testing for REST call of some other Service,"<p>I've been searching it on the net , but most of the examples i found have the returning logic of rest call within the same project , but what if you want to test a rest call of some other service which you are using it in your project(calling a REST api from a REST API)</p>

<p>is there any way to integrate this . Integration testing for a REST call which is of some external service </p>

<p>can the normal Integration testing approach could work in this case.</p>
",https://stackoverflow.com/questions/54691241/spring-integration-testing-for-rest-call-of-some-other-service,"['spring-boot', 'integration-testing', 'spring-test']",336,True,0,1
How to fix this issue with running integration testing in Flutter?,"<p>When trying to do integration testing with this command</p>

<p><code>lutter drive --target=my_app/test_driver/my_test.dart</code></p>

<p>I always get this error:</p>

<pre><code>       The flutter tool requires Git in order to operate properly;
       to set up Flutter, run the following command:
       git clone -b stable https://github.com/flutter/flutter.git
</code></pre>

<p>When I follow what they said by running <code>git clone -b stable https://github.com/flutter/flutter.git</code> I always recieve this:</p>

<pre><code>fatal: destination path 'flutter' already exists and is not an empty directory.
macpros-MBP:flutter_app CompteEtudiant$ 
</code></pre>
",https://stackoverflow.com/questions/56132817/how-to-fix-this-issue-with-running-integration-testing-in-flutter,"['git', 'flutter', 'flutter-dependencies', 'flutter-test']",107,False,0,0
SpringBoot Integration testing Sybase and Testcontainers,"<p>Is it possible to use a sybase database with Testcontainers to do the integration testing with spring boot?</p>

<p>I can not install docker on my local machine.</p>
",https://stackoverflow.com/questions/55927232/springboot-integration-testing-sybase-and-testcontainers,"['java', 'spring-boot', 'integration-testing', 'junit5', 'testcontainers']",369,True,0,1
How to write the test script for tapping a screen point in flutter integration testing without using flutter_test.dart package?,"<p>I use flutter_driver for integration testing in my application. I need to tap a screen point by passing an offset value in flutter driver testing, without using a flutter_test package </p>
",https://stackoverflow.com/questions/58852912/how-to-write-the-test-script-for-tapping-a-screen-point-in-flutter-integration-t,"['flutter', 'integration-testing', 'flutter-test']",442,True,1,1
Difference between testSaga and expectSaga in redux-saga-test-plan,"<p>Is it correct to say that <code>expectSaga</code> is for integration testing and <code>testSaga</code> is for general assertions? </p>

<p>In reality, I can actually use them interchangeably for all my tests, so I am a bit confused about when to use which.</p>
",https://stackoverflow.com/questions/57965795/difference-between-testsaga-and-expectsaga-in-redux-saga-test-plan,"['reactjs', 'redux', 'redux-saga', 'redux-saga-test-plan']",2884,True,8,1
How to cancel the animation on opening and closing the navigation drawer in flutter?,"<p>I have to speed up my application integration testing. for that, I want to cancel the animation on opening and closing the navigation drawer in the flutter. Does anyone have an idea?</p>
",https://stackoverflow.com/questions/59389290/how-to-cancel-the-animation-on-opening-and-closing-the-navigation-drawer-in-flut,"['flutter', 'integration-testing', 'flutter-animation']",417,False,-1,1
Is there a localdb equivalent for PostgreSQL?,"<p>In Microsoft SQL Server, localdb can create shallow databases. This is a feature aimed at developers, that creates new databases, without fully copying all data, and it's great for integration testing. Is there an equivalent for PostgreSQL?</p>
",https://stackoverflow.com/questions/59405716/is-there-a-localdb-equivalent-for-postgresql,['postgresql'],603,False,3,0
Flutter Integration Testing- Is there any way to relaunch app while integration testing?,"<p>I am trying to do flutter integration testing. As it stays on same screen when previous test executed. I need to relaunch app for testing from first/launch screen. Is there any way to relaunch app in flutter testing?</p>
",https://stackoverflow.com/questions/59047356/flutter-integration-testing-is-there-any-way-to-relaunch-app-while-integration,"['testing', 'flutter', 'integration-testing', 'flutter-test']",535,False,4,1
VDM for Integration Tests,"<p>I had used VDM in order to consumer external ODATA service. It is working well. Now I am trying to use the VDM for Integration Testing in order to test the created ODATA service using CAP Model.</p>

<p>I was using restTemplate.exchange() in the Integration Testing to test the ODATA service. It was working well. Now I had decided to go with SDK VDM approach.
The VDM files were generated successfully. But while trying to run the Integration Tests, it fails with an exception</p>

<p>com.sap.cloud.sdk.cloudplatform.exception.ShouldNotHappenException: java.lang.NullPointerException: while trying to invoke the method com.google.gson.JsonObject.get(java.lang.String) of a null object loaded from local variable 'xsuaaServiceCredentials'</p>

<p>I do pass the local JWT token &amp; also VCAP_SERVICES set in the environment variable.</p>

<pre><code>package com.sap.crun.landscape;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;

import com.sap.cloud.sdk.odatav2.connectivity.ODataException;
import com.sap.cloud.sdk.s4hana.connectivity.ErpConfigContext;
import com.sap.cloud.sdk.testutil.MockUtil;

import com.sap.crun.landscape.vdm.odatalandscapeservice.namespaces.odatalandscapeservice.LandscapeObjects;
import com.sap.crun.landscape.vdm.odatalandscapeservice.namespaces.odatalandscapeservice.LandscapeObjectsCreateFluentHelper;
import com.sap.crun.landscape.vdm.odatalandscapeservice.namespaces.odatalandscapeservice.LandscapeObjectsFluentHelper;
import com.sap.crun.landscape.vdm.odatalandscapeservice.namespaces.odatalandscapeservice.Properties;
import com.sap.crun.landscape.vdm.odatalandscapeservice.services.DefaultOdataLandscapeserviceService;


@RunWith(SpringRunner.class)
@SpringBootTest(classes = { TestApplication.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(locations = ""classpath:LmsTest.properties"")
public class BusinessServiceIT {

    private static final Logger LOG = CloudLoggerFactory.getLogger(LisImporter.class);
    private static final MockUtil mockUtil = new MockUtil();
    private static final DefaultOdataLandscapeserviceService lmsService = new DefaultOdataLandscapeserviceService()
            .withServicePath(""/odata/v2/LandscapeService"");
    private ErpConfigContext erpConfCtx;
    private static final String jwToken = new JwtGenerator()
            .getTokenForAuthorizationHeader(LocalSecurityConfig.XSAPPNAME + "".d"", LocalSecurityConfig.XSAPPNAME + "".r"", LocalSecurityConfig.XSAPPNAME + "".a"");
    private static final LandscapeObjectsFluentHelper lsoCreateHelper = lmsService.getAllLandscapeObjects();

    @Autowired
    private WebApplicationContext context;

    @LocalServerPort
    int randomServerPort;


    @BeforeClass
    public static void beforeClass() {
        mockUtil.mockDefaults();
        mockUtil.mockAuditLog();

        lsoCreateHelper
        .withCustomHttpHeader(""Authorization"", new JwtGenerator().getTokenForAuthorizationHeader(
                LocalSecurityConfig.XSAPPNAME + "".d"", LocalSecurityConfig.XSAPPNAME + "".a"", LocalSecurityConfig.XSAPPNAME + "".r""))
        .onRequestAndImplicitRequests();

    }

    @Before
    public void beforeEach() throws URISyntaxException {
        mockUtil.mockDestination(""localhorst"", new URI(""http://localhost:"" + randomServerPort));
        erpConfCtx = new ErpConfigContext(""localhorst"");
    }

    @Test
    public void parseVcapServices() {
        final SAPPropertyPlaceholderConfigurer propertyHolder = new SAPPropertyPlaceholderConfigurer();
        final String xsappname = propertyHolder.readVcapServices(SAPPropertyPlaceholderConfigurer.propertyXsAppname,
                ""application"");
        assertEquals(LocalSecurityConfig.XSAPPNAME, xsappname);
    }

    @Test
    public void createBusinessService() {


        Properties properties = new Properties();
        List&lt;Properties&gt; propertySet = new ArrayList&lt;&gt;();
        properties.setName(""useCase"");
        properties.setValue(""XX"");
        properties.setSource(""XXX"");
        propertySet.add(properties);

        LandscapeObjects landscapeObjects = new LandscapeObjects(null, null, null, null, null, ""benufromit"", ""benufromit_test"", BusinessService.name(), ""123"", ""LMS"", null, null, propertySet);
        LOG.info(""benu-business1"");

        final LandscapeObjectsCreateFluentHelper lsoCreateHelper = lmsService.createLandscapeObjects(landscapeObjects)
                .withCustomHttpHeader(""Authorization"", new JwtGenerator().getTokenForAuthorizationHeader(
                        LocalSecurityConfig.XSAPPNAME + "".d"", LocalSecurityConfig.XSAPPNAME + "".a"")).onRequestAndImplicitRequests();

        try {
            lsoCreateHelper.execute(erpConfCtx); //It fails here
            LOG.info(""benu-business3 {}"", landscapeObjects.getId());
        } catch (ODataException e) {
            e.printStackTrace();
        }

    }
}
</code></pre>

<p><strong>Stack Trace</strong></p>

<pre><code> com.sap.cloud.sdk.cloudplatform.exception.ShouldNotHappenException: java.lang.NullPointerException: while trying to invoke the method com.google.gson.JsonObject.get(java.lang.String) of a null object loaded from local variable 'xsuaaServiceCredentials'
                   at com.sap.cloud.sdk.cloudplatform.servlet.RequestContextServletFilter.doFilter(RequestContextServletFilter.java:216) ~[servlet-2.15.0.jar:na]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:176) ~[spring-security-oauth2-2.0.16.RELEASE.jar:na]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
                   at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE]
                   at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
                   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:685) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_202]
                   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_202]
                   at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.13.jar:9.0.13]
                   at java.lang.Thread.run(Thread.java:836) [na:1.8.0_202] Caused by: java.lang.NullPointerException: while trying to invoke the method com.google.gson.JsonObject.get(java.lang.String) of a null object loaded from local variable 'xsuaaServiceCredentials'
                   at com.sap.cloud.sdk.cloudplatform.security.AuthTokenDecoder.getVerificationPublicKey(AuthTokenDecoder.java:86) ~[security-scp-cf-2.15.0.jar:na]
                   at com.sap.cloud.sdk.cloudplatform.security.AuthTokenDecoder.decode(AuthTokenDecoder.java:146) ~[security-scp-cf-2.15.0.jar:na]
                   at com.sap.cloud.sdk.cloudplatform.security.AuthTokenDecoder.decode(AuthTokenDecoder.java:195) ~[security-scp-cf-2.15.0.jar:na]
                   at com.sap.cloud.sdk.cloudplatform.security.AuthTokenRequestContextListener.getProperties(AuthTokenRequestContextListener.java:49) ~[security-scp-cf-2.15.0.jar:na]
                   at com.sap.cloud.sdk.cloudplatform.servlet.AbstractRequestContextListener.requestContextInitialized(AbstractRequestContextListener.java:40) ~[servlet-2.15.0.jar:na]
                   at com.sap.cloud.sdk.cloudplatform.servlet.RequestContextCallable.notifyContextInitialized(RequestContextCallable.java:68) ~[servlet-2.15.0.jar:na]
                   at com.sap.cloud.sdk.cloudplatform.servlet.RequestContextCallable.call(RequestContextCallable.java:129) ~[servlet-2.15.0.jar:na]
                   at com.sap.cloud.sdk.cloudplatform.servlet.RequestContextServletFilter.doFilter(RequestContextServletFilter.java:209) ~[servlet-2.15.0.jar:na]
                   ... 76 common frames omitted
</code></pre>
",https://stackoverflow.com/questions/56459465/vdm-for-integration-tests,['sap-cloud-sdk'],160,True,1,1
Web API - Issues with HttpContext.Current in owin for integration testing using moq,"<p>I am building a Web API application which will be hosted in an IIS environment. In order to perform end to end integration testing of my service(no mocking), I am using OWIN.</p>

<p>The problem is deep down in my service architecture, at the repository layer I am making use of <code>HttpContext.Current</code> to retrieve values from the header(say UserId). <a href=""https://stackoverflow.com/a/54620606/1169180"">See this answer</a></p>

<p>If you look into the above code, I am making use <code>GetUserInfo</code> method throughout my application to fetch current user information. Another way to do is pass it as a parameter in all method(which I don't personally want to do).</p>

<p>I went through this great <a href=""https://stackoverflow.com/a/27826059/1169180"">answer</a> about including <code>IOwinContext</code> into the repository. I have tried it and it worked for self-hosting, but my end goal is to deploy the application on IIS.</p>

<p>My Questions:</p>

<ul>
<li>Is there any way my code can handle both the use cases of OWIN self-hosting for integration testing &amp; actual service deployment on IIS?</li>
<li>Is there any issue with my architecture? Something like I shouldn't be using OWIN at all, and use other tools like <code>POSTMAN</code> for testing.</li>
</ul>

<p>I can post some code if it's required.</p>

<p><strong>Edit:</strong></p>

<p>As suggested by @Nkosi I might have to mock my <code>HeaderService</code> in order to perform integration testing with owin. I am not sure how can I mock one certain method using <code>moq</code>. Here is my code. Its strip down version in order to make as simple as possible.</p>

<p>Code:</p>

<pre><code>public class CreditController : ApiController
{
    private readonly ICreditService _creditService;

    public CreditController(ICreditService creditService)
    {
        _creditService = creditService;
    }

    public IHttpActionResult CreditSummary([FromUri]string requestId)
    {
        var response = _creditService.GetCreditSummary(requestId);
        return Ok(response);
    }
}

public class CreditService : ICreditService
{
    private readonly IHeaderService _headerService;
    private readonly ICreditRepository _creditRepository;

    public CreditService(ICreditRepository creditRepository, IHeaderService headerService)
    {
        _headerService = headerService;
        _creditRepository = creditRepository;
    }

    public CreditObj GetCreditSummary(string req)
    {
        var userId = _headerService.GetHeaderFromHttpRequest();//Get User
        var response = _creditRepository.GetDataFromDatabase(req, userId);
        return response;
    }
}

public interface IHeaderService
{
    string GetHeaderFromHttpRequest();
}

public class HeaderService : IHeaderService
{
    public string GetHeaderFromHttpRequest()
    {
        return HttpContext.Current.Request.Headers[""USERID""];
    }
}
</code></pre>

<p>Below is my code for integration testing: I am using OWIN for self-host. So i want to call the controller method but my <code>GetHeaderFromHttpRequest</code> method should return mock response.</p>

<pre><code>[TestClass]
public class IntegrationTest
{
    private static HttpClient _client;
    private static IDisposable _webApp;

    [ClassInitialize]
    public static void Init(TestContext testContext)
    {
        _webApp = WebApp.Start&lt;Startup&gt;(url: Url);
        _client = new HttpClient
        {
            BaseAddress = new Uri(Url)
        };
    }

    [TestMethod]
    public void TestDashboard()
    {
        var headerStub = new Mock&lt;IHeaderService&gt;();
        headerStub.Setup(s =&gt; s.GetHeaderFromHttpRequest())
            .Returns(""MockUserId"");

        var builder = new UriBuilder(Url + ""api/Credit/CreditSummary"");

        HttpResponseMessage responseMessage = _client.GetAsync(builder.ToString()).Result;
        Assert.IsNotNull(responseMessage);
    }
}

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        WebApiConfig.Register(config); //This method having all routing/dependancy configuration
        app.UseWebApi(config);
    }
}
</code></pre>

<p><strong>Problem:</strong></p>

<ul>
<li>When I debug this test case, how do I make sure that <code>_headerService.GetHeaderFromHttpRequest()</code> return mock response. As of now I dont know how can i inject my mocking service to actual controller method call.</li>
</ul>

<p>Any advise?</p>
",https://stackoverflow.com/questions/55286550/web-api-issues-with-httpcontext-current-in-owin-for-integration-testing-using,"['c#', 'asp.net-web-api', 'owin', 'moq', 'httpcontext']",521,True,2,2
React (Unit &amp; Integration): Which framework to use for react unit testing and Integration testing,"<p>I have just started with development in Reactjs. I am looking for testing framework(Javascript). Which can be used to do both ""Unit Testing"", ""Integration Testing"" and ""e2e testing"". </p>

<p>Please, help me if we can do the the required testing using Javascript.</p>
",https://stackoverflow.com/questions/57039857/react-unit-integration-which-framework-to-use-for-react-unit-testing-and-in,"['javascript', 'reactjs', 'unit-testing', 'integration-testing']",204,True,0,3
Spring boot integration test With Dockerized postgres,"<p>Trying to do integration testing using dockerzied postgres</p>

<pre><code>12:49:19.647 [main] ERROR org.testcontainers.dockerclient.EnvironmentAndSystemPropertyClientProviderStrategy - ping failed with configuration Environment variables, system properties and defaults. Resolved: 
    dockerHost=unix:///var/run/docker.sock
    apiVersion='{UNKNOWN_VERSION}'
    registryUrl='https://index.docker.io/v1/'
    registryUsername='aequalis'
    registryPassword='null'
    registryEmail='null'
    dockerConfig='DefaultDockerClientConfig[dockerHost=unix:///var/run/docker.sock,registryUsername=aequalis,registryPassword=&lt;null&gt;,registryEmail=&lt;null&gt;,registryUrl=https://index.docker.io/v1/,dockerConfigPath=/home/aequalis/.docker,sslConfig=&lt;null&gt;,apiVersion={UNKNOWN_VERSION},dockerConfig=&lt;null&gt;]'
 due to org.rnorth.ducttape.TimeoutException: Timeout waiting for result with exception
org.rnorth.ducttape.TimeoutException: Timeout waiting for result with exception
        at org.rnorth.ducttape.unreliables.Unreliables.retryUntilSuccess(Unreliables.java:51)
        at org.testcontainers.dockerclient.DockerClientProviderStrategy.ping(DockerClientProviderStrategy.java:190)
        at org.testcontainers.dockerclient.EnvironmentAndSystemPropertyClientProviderStrategy.test(EnvironmentAndSystemPropertyClientProviderStrategy.java:42)
        at org.testcontainers.dockerclient.DockerClientProviderStrategy.lambda$getFirstValidStrategy$2(DockerClientProviderStrategy.java:113)
        at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:267)
      org.testcontainers.dockerclient.DockerClientProviderStrategy.getFirstValidStrategy(DockerClientProviderStrategy.java:148)
        at org.testcontainers.DockerClientFactory.client(DockerClientFactory.java:105)
        at org.testcontainers.containers.GenericContainer.&lt;init&gt;(GenericContainer.java:142)
        at org.testcontainers.containers.JdbcDatabaseContainer.&lt;init&gt;(JdbcDatabaseContainer.java:45)
        at org.testcontainers.containers.PostgreSQLContainer.&lt;init&gt;(PostgreSQLContainer.java:30)
        at com.lava.configuration.management.activity.AbstractIntegrationTest.&lt;clinit&gt;(AbstractIntegrationTest.java:21)
        at sun.misc.Unsafe.ensureClassInitialized(Native Method)
        at sun.reflect.UnsafeFieldAccessorFactory.newFieldAccessor(UnsafeFieldAccessorFactory.java:43)
        at sun.reflect.ReflectionFactory.newFieldAccessor(ReflectionFactory.java:156)
        at java.lang.reflect.Field.acquireFieldAccessor(Field.java:1088)
        at java.lang.reflect.Field.getFieldAccessor(Field.java:1069)
        at java.lang.reflect.Field.get(Field.java:393)
        at org.junit.runners.model.FrameworkField.get(FrameworkField.java:73)
        at org.junit.runners.model.TestClass.getAnnotatedFieldValues(TestClass.java:230)
        at org.junit.runners.ParentRunner.classRules(ParentRunner.java:255)
        at org.junit.runners.ParentRunner.withClassRules(ParentRunner.java:244)
        at org.junit.runners.ParentRunner.classBlock(ParentRunner.java:194)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:362)
 org.rnorth.ducttape.unreliables.Unreliables.lambda$retryUntilSuccess$0(Unreliables.java:41)
        at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
        at java.util.concurrent.FutureTask.run(FutureTask.java)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: com.sun.jna.LastErrorException: [13] Permission denied
        at org.testcontainers.shaded.org.scalasbt.ipcsocket.UnixDomainSocketLibrary.connect(Native Method)
        at org.testcontainers.shaded.org.scalasbt.ipcsocket.UnixDomainSocket.&lt;init&gt;(UnixDomainSocket.java:57)
        ... 36 common frames omitted
</code></pre>

<p>Above error is thrown whiling connecting to dockerized postgres for integration test.  Below is the configuration code to connect.  It seems like permission issue on the docker image.  </p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = LibraryConfigurationApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@ContextConfiguration(initializers = AbstractIntegrationTest.Initializer.class)
public abstract class AbstractIntegrationTest {

    @ClassRule
    public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer(""kartoza/postgis:12.0"")
        .withDatabaseName(""integration-tests-db"")
        .withUsername(""docker"")
        .withPassword(""docker"");

    static class Initializer
        implements ApplicationContextInitializer&lt;ConfigurableApplicationContext&gt; {
        public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
            TestPropertyValues.of(
                ""spring.datasource.url="" + postgreSQLContainer.getJdbcUrl(),
                ""spring.datasource.username="" + postgreSQLContainer.getUsername(),
                ""spring.datasource.password="" + postgreSQLContainer.getPassword()
            ).applyTo(configurableApplicationContext.getEnvironment());
        }
    }

}
</code></pre>

<p>Please helpout to fix this issue</p>
",https://stackoverflow.com/questions/59369696/spring-boot-integration-test-with-dockerized-postgres,"['postgresql', 'spring-boot', 'docker', 'integration-testing']",1271,False,0,1
"In Django ORM, is their an equivalent of the EntityFramework command EnsureCreated and EnsureDeleted?","<p>In EntityFramework, in addition to migrations, you have a command that will drop a database and/or create a database in one go:</p>

<pre><code>_dbContext.Database.EnsureDeleted();
_dbContext.Database.EnsureCreated();
</code></pre>

<p>This is very useful for initial development, experiments, demos and integration testing. Is there a command in Django that does the equivalent?</p>
",https://stackoverflow.com/questions/56070069/in-django-orm-is-their-an-equivalent-of-the-entityframework-command-ensurecreat,"['django', 'entity-framework', 'orm']",187,False,1,0
Flink - Integration testing with multiple sources,"<p>I have a Flink job, which I am integration testing using the approach described here: <a href=""https://ci.apache.org/projects/flink/flink-docs-stable/dev/stream/testing.html#integration-testing"" rel=""noreferrer"">https://ci.apache.org/projects/flink/flink-docs-stable/dev/stream/testing.html#integration-testing</a></p>

<p>The job takes its input from two sources, which are combined in a <code>CoFlatMapFuntion</code>.  In the test environment, I'm currently using two simple SourceFunctions to emit the values, however this doesn't provide any control over the order in which the events are emitted.  This is necessary in order to properly test the functionality of the job.</p>

<p>How can I modify my test to ensure one source function emits all of its data before the second?</p>

<p>I've seen the approach suggested in <a href=""https://stackoverflow.com/questions/52153863/integration-test-for-complex-topology-multiple-inputs-in-flink"">Integration test for complex topology (multiple inputs) in Flink</a>, this is fine for unit testing but I'm looking for a solution which allows me to integration test the entire job.</p>
",https://stackoverflow.com/questions/54908476/flink-integration-testing-with-multiple-sources,"['java', 'apache-flink', 'flink-streaming']",1803,True,5,1
How to disable swagger function of startup class in web api core for integration testing,"<p>I am writing integration testing and came across a requirement to disable to calling adding swagger function in startup. I am using the same startup class without customizing it. </p>

<p>Please suggest some solution to get rid of swagger and it's inner function implementation like adding authentication.</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/59344652/how-to-disable-swagger-function-of-startup-class-in-web-api-core-for-integration,"['integration-testing', 'asp.net-core-webapi']",731,True,0,1
Net Core: Find Services from WebApplicationFactory,"<p>How do I grab all the Services from a CustomWebApplicationFactory?
Startup class has conducted dependency injection for IDepartmentRepository and IDepartmentAppService. Would like to grab the new DI repository or service.</p>

<p>We are creating integration test which points to original application startup.</p>

<pre><code>namespace Integrationtest
{
    public class CustomWebApplicationFactory&lt;TStartup&gt; : WebApplicationFactory&lt;TStartup&gt; where TStartup : class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration((hostingContext, configurationBuilder) =&gt;
            {
                var type = typeof(TStartup);
                var path = @""C:\\OriginalApplicationWebAPI"";

                configurationBuilder.AddJsonFile($""{path}\\appsettings.json"", optional: true, reloadOnChange: true);
                configurationBuilder.AddEnvironmentVariables();
            });
        }
    }
}

public class DepartmentAppServiceTest : IClassFixture&lt;CustomWebApplicationFactory&lt;OriginalApplication.Startup&gt;&gt;

{
    public testDbContext context;
    private readonly HttpClient _client;

    public DepartmentAppServiceTest(CustomWebApplicationFactory&lt;OriginalApplication.Startup&gt; factory)
    {
        _client = factory.CreateClient();
        factory.  // trying to find services here for IDepartmentRepository 
    }
</code></pre>

<p><a href=""https://fullstackmark.com/post/20/painless-integration-testing-with-aspnet-core-web-api"" rel=""nofollow noreferrer"">https://fullstackmark.com/post/20/painless-integration-testing-with-aspnet-core-web-api</a></p>
",https://stackoverflow.com/questions/57381948/net-core-find-services-from-webapplicationfactory,"['c#', 'asp.net-core', 'dependency-injection', '.net-core']",2617,True,3,2
How to configure In-memory mongodb?,"<p>I am working with integration testing for my <strong>NodeJS-Typescript</strong> application using a <strong>MongoDB</strong> database. I am using <strong>Jest</strong> as a testing framework. How to replace real db configuration with In-memory database(mongoDb) which I can use for testing. Can anyone help me with the configuration ?</p>
<p>config.ts</p>
<pre><code>/**
 * @file Configuration file - Testing Configuration.
 */

export default {
    jwtPrivateKey: '11234.xsdfcswfe.23rcscdsfg',
    // Testing Database configuration
    MongoDB: {
        dbConfig: {
            user: 'xxxx',
            password: 'xxxx',
            host: '11.222.333.444',
            port: '27017',
            authMechanism: 'SCRAM-SHA-1',
            authSource: 'permissionlevel',
            dbName: 'sample_db'
        }
    }

};

</code></pre>
",https://stackoverflow.com/questions/59334618/how-to-configure-in-memory-mongodb,"['javascript', 'node.js', 'mongodb', 'typescript', 'jestjs']",601,False,0,3
Thorntail not running for integration testing but I have the same pom.xml of a working project,"<p>All this afternoon I've been trying to solve a mysterious problem about an error :</p>

<pre><code>[ERROR] Tests run: 3, Failures: 0, Errors: 3, Skipped: 0, Time elapsed: 9.783 s &lt;&lt;&lt; FAILURE! - in api.rest.AdRestServiceTest
[ERROR] testGet  Time elapsed: 4.351 s  &lt;&lt;&lt; ERROR!
java.net.ConnectException: Connection refused: connect
        at api.rest.AdRestServiceTest.testGet(AdRestServiceTest.java:32)

[ERROR] testCount  Time elapsed: 2.013 s  &lt;&lt;&lt; ERROR!
java.net.ConnectException: Connection refused: connect
        at api.rest.AdRestServiceTest.testCount(AdRestServiceTest.java:27)

[ERROR] testGetAll  Time elapsed: 2.022 s  &lt;&lt;&lt; ERROR!
java.net.ConnectException: Connection refused: connect
        at api.rest.AdRestServiceTest.testGetAll(AdRestServiceTest.java:21)
</code></pre>

<p>I can successfully run a working project (<a href=""https://github.com/hostettler/microservices/tree/integration_tests"" rel=""nofollow noreferrer"">https://github.com/hostettler/microservices/tree/integration_tests</a>) with <code>mvn clean install</code>.</p>

<p>I have some nice <code>Thorntail is ready</code> for the working example.</p>

<pre><code>2019-05-21 16:29:26,235 INFO  [org.wildfly.swarm] (main) THORN99999: Thorntail is Ready
[INFO]
[INFO] --- jacoco-maven-plugin:0.8.2:prepare-agent (integration-tests-preaparation) @ counterparty-service ---
[INFO] argLineForIntegration set to -javaagent:C:\\Users\\Admin\\.m2\\repository\\org\\jacoco\\org.jacoco.agent\\0.8.2\\org.jacoco.agent-0.8.2-runtime.jar=destfile=C:\\Users\\Admin\\Desktop\\ProjetINFO\\microservices\\counterparty-service\\target\\jacoco-it.exec
[INFO]
[INFO] --- maven-failsafe-plugin:2.22.1:integration-test (default) @ counterparty-service ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running api.CounterpartyRestServiceIT
2019-05-21 16:29:34,220 INFO  [stdout] (default task-1) Hibernate: ...
</code></pre>

<p>I just copied those pom.xml (Parent pom and counterparty-service's pom) but it still doesn't work ..</p>

<p>Here is the Parent pom.xml :</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns=""http://maven.apache.org/POM/4.0.0""
    xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
    xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;groupId&gt;ch.unige&lt;/groupId&gt;
    &lt;artifactId&gt;PInfo2&lt;/artifactId&gt;
    &lt;version&gt;0.2.0-SNAPSHOT&lt;/version&gt;
    &lt;name&gt;Parent Pom of the PInfo2&lt;/name&gt;

    &lt;packaging&gt;pom&lt;/packaging&gt;

    &lt;!--&lt;scm&gt;
        &lt;url&gt;https://github.com/hostettler/microservices&lt;/url&gt;
        &lt;connection&gt;scm:git:git@github.com/hostettler/microservices.git&lt;/connection&gt;
        &lt;developerConnection&gt;scm:git:git@github.com/hostettler/microservices&lt;/developerConnection&gt;
    &lt;/scm&gt; --&gt;

    &lt;properties&gt;
        &lt;version.thorntail&gt;2.3.0.Final&lt;/version.thorntail&gt;
        &lt;version.h2&gt;1.4.197&lt;/version.h2&gt;
        &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt;
        &lt;maven.compiler.source&gt;1.8&lt;/maven.compiler.source&gt;
        &lt;maven.compiler.target&gt;1.8&lt;/maven.compiler.target&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;skip-docker-build&gt;true&lt;/skip-docker-build&gt;
        &lt;skip-docker-compose&gt;false&lt;/skip-docker-compose&gt;
        &lt;dockerHost&gt;tcp://localhost:2375&lt;/dockerHost&gt;
    &lt;/properties&gt;


    &lt;modules&gt;
        &lt;module&gt;image-service&lt;/module&gt;
        &lt;module&gt;stats-service&lt;/module&gt;
        &lt;module&gt;chat-service&lt;/module&gt;
        &lt;module&gt;ad-service&lt;/module&gt;
        &lt;module&gt;category-service&lt;/module&gt;
        &lt;module&gt;user-service&lt;/module&gt;
        &lt;module&gt;search-service&lt;/module&gt;
        &lt;module&gt;api-gateway&lt;/module&gt;
    &lt;/modules&gt;


    &lt;dependencyManagement&gt;
        &lt;dependencies&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;io.thorntail&lt;/groupId&gt;
                &lt;artifactId&gt;bom&lt;/artifactId&gt;
                &lt;version&gt;${version.thorntail}&lt;/version&gt;
                &lt;scope&gt;import&lt;/scope&gt;
                &lt;type&gt;pom&lt;/type&gt;
            &lt;/dependency&gt;
            &lt;!--&lt;dependency&gt;
                &lt;groupId&gt;org.aerogear.kafka&lt;/groupId&gt;
                &lt;artifactId&gt;kafka-cdi-extension&lt;/artifactId&gt;
                &lt;version&gt;0.1.0&lt;/version&gt;
            &lt;/dependency&gt; --&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;com.github.dadrus.jpa-unit&lt;/groupId&gt;
                &lt;artifactId&gt;jpa-unit-bom&lt;/artifactId&gt;
                &lt;version&gt;0.5.0&lt;/version&gt;
                &lt;type&gt;pom&lt;/type&gt;
                &lt;scope&gt;import&lt;/scope&gt;
            &lt;/dependency&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
                &lt;artifactId&gt;lombok&lt;/artifactId&gt;
                &lt;version&gt;1.18.4&lt;/version&gt;
            &lt;/dependency&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;javax.enterprise&lt;/groupId&gt;
                &lt;artifactId&gt;cdi-api&lt;/artifactId&gt;
                &lt;version&gt;1.2&lt;/version&gt;
                &lt;scope&gt;provided&lt;/scope&gt;
            &lt;/dependency&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.jboss.spec.javax.ws.rs&lt;/groupId&gt;
                &lt;artifactId&gt;jboss-jaxrs-api_2.0_spec&lt;/artifactId&gt;
                &lt;version&gt;1.0.0.Final&lt;/version&gt;
                &lt;scope&gt;provided&lt;/scope&gt;
            &lt;/dependency&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;com.h2database&lt;/groupId&gt;
                &lt;artifactId&gt;h2&lt;/artifactId&gt;
                &lt;version&gt;${version.h2}&lt;/version&gt;
            &lt;/dependency&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.aerogear.kafka&lt;/groupId&gt;
                &lt;artifactId&gt;kafka-cdi-extension&lt;/artifactId&gt;
                &lt;version&gt;0.1.0&lt;/version&gt;
            &lt;/dependency&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;io.thorntail&lt;/groupId&gt;
                &lt;artifactId&gt;swagger&lt;/artifactId&gt;
                &lt;version&gt;2.2.1.Final&lt;/version&gt;
            &lt;/dependency&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.junit&lt;/groupId&gt;
                &lt;artifactId&gt;junit-bom&lt;/artifactId&gt;
                &lt;version&gt;5.3.2&lt;/version&gt;
                &lt;scope&gt;test&lt;/scope&gt;
                &lt;type&gt;pom&lt;/type&gt;
            &lt;/dependency&gt;
            &lt;!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api --&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;5.3.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-engine&lt;/artifactId&gt;
                &lt;version&gt;5.3.2&lt;/version&gt;
                &lt;scope&gt;test&lt;/scope&gt;
            &lt;/dependency&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.junit.platform&lt;/groupId&gt;
                &lt;artifactId&gt;junit-platform-launcher&lt;/artifactId&gt;
                &lt;version&gt;1.3.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-core&lt;/artifactId&gt;
                &lt;version&gt;2.23.4&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.23.4&lt;/version&gt;
                &lt;scope&gt;test&lt;/scope&gt;
            &lt;/dependency&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;javax.xml.bind&lt;/groupId&gt;
                &lt;artifactId&gt;jaxb-api&lt;/artifactId&gt;
                &lt;version&gt;2.3.1&lt;/version&gt;
                &lt;scope&gt;test&lt;/scope&gt;
            &lt;/dependency&gt;
        &lt;/dependencies&gt;
    &lt;/dependencyManagement&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&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;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.platform&lt;/groupId&gt;
            &lt;artifactId&gt;junit-platform-launcher&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.mockito&lt;/groupId&gt;
            &lt;artifactId&gt;mockito-core&lt;/artifactId&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;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;javax.xml.bind&lt;/groupId&gt;
            &lt;artifactId&gt;jaxb-api&lt;/artifactId&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;build&gt;
        &lt;pluginManagement&gt;
            &lt;plugins&gt;
                &lt;plugin&gt;
                    &lt;artifactId&gt;maven-release-plugin&lt;/artifactId&gt;
                    &lt;version&gt;2.5.3&lt;/version&gt;
                    &lt;configuration&gt;
                        &lt;autoVersionSubmodules&gt;true&lt;/autoVersionSubmodules&gt;
                        &lt;tagNameFormat&gt;@{project.version}&lt;/tagNameFormat&gt;
                        &lt;releaseProfiles&gt;release&lt;/releaseProfiles&gt;
                    &lt;/configuration&gt;
                &lt;/plugin&gt;
                &lt;plugin&gt;
                    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                    &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
                    &lt;version&gt;3.8.0&lt;/version&gt;
                    &lt;configuration&gt;
                        &lt;configuration&gt;
                            &lt;source&gt;${maven.compiler.source}&lt;/source&gt;
                            &lt;target&gt;${maven.compiler.target}&lt;/target&gt;
                        &lt;/configuration&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-M3&lt;/version&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-M6&lt;/version&gt;
                &lt;/plugin&gt;

                &lt;plugin&gt;
                    &lt;groupId&gt;org.jacoco&lt;/groupId&gt;
                    &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;
                    &lt;version&gt;0.8.2&lt;/version&gt;
                &lt;/plugin&gt;
                &lt;plugin&gt;
                    &lt;groupId&gt;io.thorntail&lt;/groupId&gt;
                    &lt;artifactId&gt;thorntail-maven-plugin&lt;/artifactId&gt;
                    &lt;version&gt;${version.thorntail}&lt;/version&gt;
                &lt;/plugin&gt;
                &lt;plugin&gt;
                    &lt;groupId&gt;io.fabric8&lt;/groupId&gt;
                    &lt;artifactId&gt;fabric8-maven-plugin&lt;/artifactId&gt;
                    &lt;version&gt;4.0.0-M2&lt;/version&gt;
                &lt;/plugin&gt;
            &lt;/plugins&gt;
        &lt;/pluginManagement&gt;

        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;io.thorntail&lt;/groupId&gt;
                &lt;artifactId&gt;thorntail-maven-plugin&lt;/artifactId&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;package&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.jacoco&lt;/groupId&gt;
                &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;id&gt;unit-tests&lt;/id&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;prepare-agent&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                    &lt;execution&gt;
                        &lt;id&gt;integration-tests-preaparation&lt;/id&gt;
                        &lt;phase&gt;pre-integration-test&lt;/phase&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;prepare-agent&lt;/goal&gt;
                        &lt;/goals&gt;
                        &lt;configuration&gt;
                            &lt;propertyName&gt;argLineForIntegration&lt;/propertyName&gt;                      
                            &lt;destFile&gt;${project.build.directory}/jacoco-it.exec&lt;/destFile&gt;
                        &lt;/configuration&gt;                        
                    &lt;/execution&gt;                    
                    &lt;execution&gt;
                        &lt;id&gt;merge&lt;/id&gt;
                        &lt;phase&gt;post-integration-test&lt;/phase&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;merge&lt;/goal&gt;
                        &lt;/goals&gt;
                        &lt;configuration&gt;
                            &lt;fileSets&gt;
                                &lt;fileSet&gt;
                                    &lt;directory&gt;${project.build.directory}&lt;/directory&gt;
                                    &lt;includes&gt;
                                        &lt;include&gt;*.exec&lt;/include&gt;
                                    &lt;/includes&gt;
                                &lt;/fileSet&gt;
                            &lt;/fileSets&gt;
                            &lt;destFile&gt;${project.build.directory}/jacoco-merged.exec&lt;/destFile&gt;
                        &lt;/configuration&gt;
                    &lt;/execution&gt;
                    &lt;execution&gt;
                        &lt;id&gt;report&lt;/id&gt;
                        &lt;phase&gt;post-integration-test&lt;/phase&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;report&lt;/goal&gt;
                        &lt;/goals&gt;
                        &lt;configuration&gt;
                        &lt;dataFile&gt;${project.build.directory}/jacoco-merged.exec&lt;/dataFile&gt;
                        &lt;/configuration&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;


    &lt;profiles&gt;
        &lt;profile&gt;
            &lt;id&gt;activate_windows&lt;/id&gt;
            &lt;activation&gt;
                &lt;os&gt;
                    &lt;family&gt;unix&lt;/family&gt;
                &lt;/os&gt;
            &lt;/activation&gt;
            &lt;properties&gt;
                &lt;dockerHost&gt;tcp://localhost:2375&lt;/dockerHost&gt;
            &lt;/properties&gt;
        &lt;/profile&gt;
        &lt;profile&gt;
            &lt;id&gt;activation_unix&lt;/id&gt;
            &lt;activation&gt;
                &lt;os&gt;
                    &lt;family&gt;unix&lt;/family&gt;
                &lt;/os&gt;
            &lt;/activation&gt;
            &lt;properties&gt;
                &lt;dockerHost&gt;unix:///var/run/docker.sock&lt;/dockerHost&gt;
            &lt;/properties&gt;
        &lt;/profile&gt;
        &lt;profile&gt;
            &lt;id&gt;package-docker-image&lt;/id&gt;
            &lt;activation&gt;
                &lt;property&gt;
                    &lt;name&gt;docker-build&lt;/name&gt;
                &lt;/property&gt;
            &lt;/activation&gt;
            &lt;build&gt;
                &lt;plugins&gt;
                    &lt;plugin&gt;
                        &lt;groupId&gt;io.fabric8&lt;/groupId&gt;
                        &lt;artifactId&gt;fabric8-maven-plugin&lt;/artifactId&gt;
                        &lt;configuration&gt;
                            &lt;skip&gt;${skip-docker-build}&lt;/skip&gt;
                            &lt;useColor&gt;true&lt;/useColor&gt;
                            &lt;dockerHost&gt;${dockerHost}&lt;/dockerHost&gt;
                            &lt;images&gt;
                                &lt;image&gt;
                                    &lt;name&gt;%g/%a:%l&lt;/name&gt;
                                    &lt;run&gt;
                                        &lt;ports&gt;
                                            &lt;port&gt;8080:8080&lt;/port&gt;
                                        &lt;/ports&gt;
                                    &lt;/run&gt;
                                    &lt;build&gt;
                                        &lt;from&gt;java:openjdk-8-jdk&lt;/from&gt;
                                        &lt;ports&gt;
                                            &lt;port&gt;8080&lt;/port&gt;
                                        &lt;/ports&gt;
                                        &lt;assembly&gt;
                                            &lt;basedir&gt;/&lt;/basedir&gt;
                                            &lt;inline&gt;
                                                &lt;files&gt;
                                                    &lt;file&gt;
                                                        &lt;source&gt;${project.build.directory}/${project.build.finalName}-thorntail.jar&lt;/source&gt;
                                                        &lt;outputDirectory&gt;/opt&lt;/outputDirectory&gt;
                                                    &lt;/file&gt;
                                                &lt;/files&gt;
                                            &lt;/inline&gt;
                                        &lt;/assembly&gt;
                                        &lt;entryPoint&gt;
                                            &lt;shell&gt;java -Djava.net.preferIPv4Stack=true -jar \
                                                /opt/${project.build.finalName}-thorntail.jar&lt;/shell&gt;
                                        &lt;/entryPoint&gt;
                                    &lt;/build&gt;
                                &lt;/image&gt;
                            &lt;/images&gt;
                        &lt;/configuration&gt;
                        &lt;executions&gt;
                            &lt;execution&gt;
                                &lt;phase&gt;package&lt;/phase&gt;
                                &lt;goals&gt;
                                    &lt;goal&gt;build&lt;/goal&gt;
                                &lt;/goals&gt;
                            &lt;/execution&gt;
                        &lt;/executions&gt;
                    &lt;/plugin&gt;
                &lt;/plugins&gt;
            &lt;/build&gt;
        &lt;/profile&gt;
    &lt;/profiles&gt;

&lt;/project&gt;

</code></pre>

<p>And here is the pom.xml located in ad-service (our project's microservice) :</p>

<pre><code>&lt;project xmlns=""http://maven.apache.org/POM/4.0.0""
    xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
    xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;parent&gt;
        &lt;groupId&gt;ch.unige&lt;/groupId&gt;
        &lt;artifactId&gt;PInfo2&lt;/artifactId&gt;
        &lt;version&gt;0.2.0-SNAPSHOT&lt;/version&gt;
    &lt;/parent&gt;

    &lt;artifactId&gt;ad-service&lt;/artifactId&gt;
    &lt;name&gt;Ad Service&lt;/name&gt;
    &lt;packaging&gt;war&lt;/packaging&gt;

    &lt;properties&gt;
        &lt;skip-docker-build&gt;false&lt;/skip-docker-build&gt;
    &lt;/properties&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.thorntail&lt;/groupId&gt;
            &lt;artifactId&gt;jaxrs&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;io.thorntail&lt;/groupId&gt;
            &lt;artifactId&gt;jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.thorntail&lt;/groupId&gt;
            &lt;artifactId&gt;swagger&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.thorntail&lt;/groupId&gt;
            &lt;artifactId&gt;cdi&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.thorntail&lt;/groupId&gt;
            &lt;artifactId&gt;transactions&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;javax.enterprise&lt;/groupId&gt;
            &lt;artifactId&gt;cdi-api&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.jboss.spec.javax.ws.rs&lt;/groupId&gt;
            &lt;artifactId&gt;jboss-jaxrs-api_2.0_spec&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.thorntail&lt;/groupId&gt;
            &lt;artifactId&gt;datasources&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.thorntail&lt;/groupId&gt;
            &lt;artifactId&gt;logging&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.h2database&lt;/groupId&gt;
            &lt;artifactId&gt;h2&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
            &lt;artifactId&gt;lombok&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.postgresql&lt;/groupId&gt;
            &lt;artifactId&gt;postgresql&lt;/artifactId&gt;
            &lt;version&gt;42.2.5&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;javax&lt;/groupId&gt;
            &lt;artifactId&gt;javaee-api&lt;/artifactId&gt;
            &lt;version&gt;7.0&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
            &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt;
            &lt;version&gt;5.0.10.Final&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.aerogear.kafka&lt;/groupId&gt;
            &lt;artifactId&gt;kafka-cdi-extension&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;com.github.dadrus.jpa-unit&lt;/groupId&gt;
            &lt;artifactId&gt;jpa-unit5&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.github.dadrus.jpa-unit&lt;/groupId&gt;
            &lt;artifactId&gt;jpa-unit-rdbms&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-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;dependency&gt;
            &lt;groupId&gt;io.rest-assured&lt;/groupId&gt;
            &lt;artifactId&gt;rest-assured&lt;/artifactId&gt;
            &lt;version&gt;3.3.0&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.hamcrest&lt;/groupId&gt;
            &lt;artifactId&gt;hamcrest-all&lt;/artifactId&gt;
            &lt;version&gt;1.3&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

    &lt;/dependencies&gt;



    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt;
                &lt;version&gt;2.22.1&lt;/version&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;integration-test&lt;/goal&gt;
                            &lt;goal&gt;verify&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;

            &lt;plugin&gt;
                &lt;groupId&gt;org.jacoco&lt;/groupId&gt;
                &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;id&gt;unit-tests-1&lt;/id&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;prepare-agent&lt;/goal&gt;
                        &lt;/goals&gt;
                        &lt;configuration&gt;
                        &lt;destFile&gt;jacoco.exec&lt;/destFile&gt;
                        &lt;/configuration&gt;
                    &lt;/execution&gt;
                    &lt;execution&gt;
                        &lt;id&gt;unit-tests-2&lt;/id&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;prepare-agent&lt;/goal&gt;
                        &lt;/goals&gt;
                        &lt;configuration&gt;
                            &lt;append&gt;false&lt;/append&gt;
                        &lt;/configuration&gt;
                    &lt;/execution&gt;                    
                    &lt;execution&gt;
                        &lt;id&gt;report&lt;/id&gt;
                        &lt;phase&gt;post-integration-test&lt;/phase&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;report&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;

            &lt;plugin&gt;
                &lt;groupId&gt;io.thorntail&lt;/groupId&gt;
                &lt;artifactId&gt;thorntail-maven-plugin&lt;/artifactId&gt;
                &lt;configuration&gt;
                    &lt;!--PLACEHOLDER:configuration --&gt;
                &lt;/configuration&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;package&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                    &lt;execution&gt;
                        &lt;id&gt;start&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;jvmArguments&gt;${}&lt;/jvmArguments&gt;
                            &lt;properties&gt;
                                &lt;thorntail.port.offset&gt;20000&lt;/thorntail.port.offset&gt;
                            &lt;/properties&gt;
                        &lt;/configuration&gt;
                    &lt;/execution&gt;
                    &lt;execution&gt;
                        &lt;id&gt;stop&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;
        &lt;/plugins&gt;
    &lt;/build&gt;
&lt;/project&gt;

</code></pre>

<p>They are nearly the same with the working repo (just added kafka dependencies and changed name).
I don't know why it doesn't launch a server in background for integration testing but it does for the working repo.. </p>

<p>THE REPO I AM WORKING ON IS : <a href=""https://github.com/bigotromain/PInfo2/tree/integration_tests"" rel=""nofollow noreferrer"">https://github.com/bigotromain/PInfo2/tree/integration_tests</a></p>

<p>Here is my ""dumb"" test file :</p>

<pre><code>package api.rest;

import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.containsString;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import io.restassured.RestAssured;

public class AdRestServiceTest {

    @BeforeAll
    public static void setup() {
        RestAssured.baseURI = ""http://localhost:28080/ad"";
        RestAssured.port = 8080;
    }

    @Test
    public void testGetAll() {
        when().get(""/"").then().body(containsString(""984500C2EEUEB4A0C629""));

    }

    @Test
    public void testCount() {
        when().get(""/count"").then().body(containsString(""5""));
    }

    @Test
    public void testGet() {
        when().get(""/984500C2EEUEB4A0C629"").then().body(containsString(""984500C2EEUEB4A0C629""));
    }

}

</code></pre>

<p>I clearly don't see why Thorntail won't launch for the integration testing.. any help ??
Thanks</p>
",https://stackoverflow.com/questions/56244941/thorntail-not-running-for-integration-testing-but-i-have-the-same-pom-xml-of-a-w,"['maven', 'compiler-errors', 'integration-testing', 'pom.xml', 'thorntail']",324,True,0,1
"Azure policies, integration testing","<p>I'm new to azure and I have some azure policies to implement controls over azure services.</p>

<p>I was wondering if there exist any integration testing frameworks or tooling support to test azure policies?</p>

<p>Can I create mock objects for azure services and test if the policies work as expected or not?</p>
",https://stackoverflow.com/questions/58230014/azure-policies-integration-testing,"['azure', 'integration-testing', 'azure-policy']",39,False,0,1
WebApplicationFactory Use Startup.Cs in Another Project Directory,"<p>How do I customize WebApplicationFactory to use Startup from another project directory?</p>

<p>Using startup, appsettings from this project below. Creating integration test which points to original application startup.</p>

<p>Startup is in this folder along with appsettings, 
C:\Test\Test.WebAPI</p>

<pre><code>new WebHostBuilder()
                .UseContentRoot(""C:\\Test\\Test.WebAPI"")
                .UseEnvironment(""Development"")
                .UseConfiguration(new ConfigurationBuilder()
                    .SetBasePath(""C:\\Test\\Test.WebAPI"")
                    .AddJsonFile(""appsettings.json"")
                    .Build()).UseStartup&lt;Startup&gt;());
</code></pre>

<p><a href=""https://fullstackmark.com/post/20/painless-integration-testing-with-aspnet-core-web-api"" rel=""nofollow noreferrer"">https://fullstackmark.com/post/20/painless-integration-testing-with-aspnet-core-web-api</a></p>
",https://stackoverflow.com/questions/57380574/webapplicationfactory-use-startup-cs-in-another-project-directory,"['c#', 'asp.net-core', '.net-core']",671,True,0,1
is controller testing functional testing?,"<p>I am really interested in different aspects of testing. I hope you can really read this and just give me your ideas if you have experience with this. Let's break down.</p>

<p>Fact 1: It's said that when we write a test from user perspective(going to uri, and getting results and if user sees the correct result, then test is right). They say this is called functional testing.</p>

<p>Sum up 1: So turns out when we write tests for controller, it's always functional as we must make the request to endpoint and observe the result. SO writing tests for controllers are always functional tests.  <strong>Is that right?</strong></p>

<p>==========================================================================</p>

<p>Fact 2: So, Integration testing is not controller testing. Let's imagine we have some functions (not controller functions) in our app. For example in our helper classes or models. and we want to test those functions like integration testing. So we won't mock anything and just test it.</p>

<p>Sum up 2: So, integration testing can be done on functions that are not controller functions, are written on other places(where request doesn't need to be done) and they must use external dependencies. By external dependencies, anything can be thought (such as file,database or another class itself) . <strong>Is that right?</strong></p>

<p>==========================================================================</p>

<p>Sum up 3: what if I have just an api and instead of returning views, I return json and status codes from controllers. If i write test for controllers, it will still be called functional tests. <strong>right?</strong></p>
",https://stackoverflow.com/questions/55716347/is-controller-testing-functional-testing,"['testing', 'model-view-controller', 'integration-testing', 'functional-testing']",454,True,2,1
end to end or integration or system testing,"<p>What kind of testing is this? Is the following considered end to end testing or is it an integration testing or a system testing? If not if you can elaborate on the types of testing in context of the code example.</p>

<p>I'm basically calling the endpoint on localhost and asserting on the status/output.</p>

<pre><code>let assert = require(""assert"");
let http = require(""http"");

describe(""EndToEndTesting"", function() {

    describe(""GET /users"", function() {
        it(""should return list of users"", function(done) {
            http.request({
                method: ""GET"",
                hostname: ""localhost"",
                port: 3000,
                path: ""/users""
            }, function(response){
                let buffers = [];
                response.on(""data"", buffers.push.bind(buffers));
                response.on(""end"", function(){
                    let body = JSON.parse(Buffer.concat(buffers).toString());
                    assert(response.statusCode == 200);
                });
            }).on(""error"", console.error).end();
        });
    }
}
</code></pre>
",https://stackoverflow.com/questions/58621937/end-to-end-or-integration-or-system-testing,"['node.js', 'testing', 'integration-testing', 'end-to-end', 'system-testing']",797,True,2,1
Corda integration test never finishes,"<p>After reaching the following line, the test just seems to endlessly churn.</p>

<pre><code>partyBHandle.rpc.startFlow(::MyIssueFlow, state).returnValue.getOrThrow()
</code></pre>

<p>Seeing a lot of console output to the effect of:</p>

<pre><code>13:28:41.930 [InProcessNode-3-2] DEBUG net.corda.node.services.network.NodeInfoWatcher - Number of removed NodeInfo files 0
13:28:43.862 [InProcessNode-1-2] DEBUG net.corda.node.services.network.NodeInfoWatcher - Read 0 NodeInfo files from NotaryService\additional-node-infos
13:28:43.862 [InProcessNode-1-2] DEBUG net.corda.node.services.network.NodeInfoWatcher - Number of removed NodeInfo files 0
13:28:45.828 [InProcessNode-2-2] DEBUG net.corda.node.services.network.NodeInfoWatcher - Read 0 NodeInfo files from BankA\additional-node-infos
13:28:45.828 [InProcessNode-2-2] DEBUG net.corda.node.services.network.NodeInfoWatcher - Number of removed NodeInfo files 0
</code></pre>

<p>I know the flow works because a regular Flow test using MockNetwork completes successfully. In this case I want to use integration testing so I can test some client API methods.</p>
",https://stackoverflow.com/questions/57731685/corda-integration-test-never-finishes,['corda'],78,False,0,1
headless VTK for tests,"<p>I have a simple VTK Python code that plots a tetrahedron:</p>

<pre class=""lang-py prettyprint-override""><code># plot a tetrahedron
import numpy
import vtk

node_coords = numpy.array(
    [
        [1.0, 0.0, -1.0 / numpy.sqrt(8)],
        [-0.5, +numpy.sqrt(3.0) / 2.0, -1.0 / numpy.sqrt(8)],
        [-0.5, -numpy.sqrt(3.0) / 2.0, -1.0 / numpy.sqrt(8)],
        [0.0, 0.0, numpy.sqrt(2.0) - 1.0 / numpy.sqrt(8)],
    ]
) / numpy.sqrt(3.0)
cells = numpy.array([[0, 1, 2, 3]])
cell_id = 0
line_width = 3.0


def get_line_actor(x0, x1, line_width=1.0):
    source = vtk.vtkLineSource()
    source.SetPoint1(x0)
    source.SetPoint2(x1)
    # mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(source.GetOutputPort())
    # actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    # color actor
    actor.GetProperty().SetColor(0, 0, 0)
    actor.GetProperty().SetLineWidth(line_width)
    return actor


# Visualize
renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)

for ij in [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]:
    x0, x1 = node_coords[cells[cell_id][ij]]
    renderer.AddActor(get_line_actor(x0, x1, line_width))
renderer.SetBackground(1.0, 1.0, 1.0)

renderWindow.Render()
renderWindowInteractor.Start()
</code></pre>

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

<p>I would now like to add continuous integration testing for this code (which runs in in a headless environment), but all I'm getting is</p>

<pre><code>Received 'aborted' signal
</code></pre>

<p>Adding code for closing the window</p>

<pre class=""lang-py prettyprint-override""><code># renderWindowInteractor.Start()

render_window.Finalize()
del render_window, render_window_interactor
</code></pre>

<p>does not help.</p>

<p>How to use VTK in a headless environment?</p>
",https://stackoverflow.com/questions/56241563/headless-vtk-for-tests,"['python', 'vtk', 'headless']",592,True,0,1
Set dynamically created Java String to Json Values to perform Karate Integration Testing as a dynamically,"<p>I need to set the randomString/randomNumber to a Json Values. Current to complete my Karate Integration testing, I am passing hardcoded values as payload, But need to set the randomString/randomNumber as value for Json. I am having PUT HTTP verb.</p>

<p>I need to store the JSON values in DB as well.</p>
",https://stackoverflow.com/questions/57253925/set-dynamically-created-java-string-to-json-values-to-perform-karate-integration,"['json', 'spring-boot', 'karate']",614,True,-2,2
Most RESTFUL API functions cannot be unit-tested,"<pre><code>postAdmin(req, res, cb) {
    const admin = await Admin.findOne({ req.body.username });

    if (!admin) {
        error(""Admin doesn't exist"");
    } //split here? adminValidationDAO();

    const isMatch = await bcrypt.compare(password, user.password);

    if(!isMatch){
        error(""Wrong password"");
    } //split here? passwordValidationDAO();
    const email = new Email ({
        text: req.body.text,
        title: req.body.title,
    });
    const response = await email.save();
    //split here? saveResponseDAO()?
}
</code></pre>

<blockquote>
  <p>Unit testing is the practice of testing small pieces of code,
  typically individual functions, alone and isolated. If your test uses
  some <strong>external resource, like the network or a database, it’s not a
  unit test.</strong></p>
</blockquote>

<p>I was thinking of testing the code I have above, but I realized after doing some research about unit testing that what I thought was unit testing was integration testing. Testing the whole chunk of code inside postAdmin would be integration testing. Then I was wondering if I could divide the code inside postAdmin into three chunks and make them unit testable, but here are the following issues:</p>

<p>The first one makes a database call with findOne().</p>

<p>The second one relies on a library, isn't that an external resource?</p>

<p>The third one makes a database call with save().</p>

<p>So would you agree that there's nothing that can be unit tested?</p>
",https://stackoverflow.com/questions/58896849/most-restful-api-functions-cannot-be-unit-tested,"['node.js', 'unit-testing', 'tdd']",57,True,0,2
Azure Service Bus - Integration testing approach for a Java app,"<p>What is your approach for integration testing Java applications that use Azure Service Bus for messaging? </p>

<p>I don't want to use the cloud service in every CI build. Would much rather spawn an embedded version of Azure Service Bus or mock it somehow. Alternatively I'm considering coding to AMQP/JMS and using embedded ActiveMQ to emulate Azure Service Bus during CI builds.
Thanks.</p>
",https://stackoverflow.com/questions/54149552/azure-service-bus-integration-testing-approach-for-a-java-app,"['java', 'azure', 'continuous-integration', 'integration-testing', 'azureservicebus']",2050,True,5,1
Spring Integration WS outbound gateway SSL,"<p>We have an external soap service and the below works</p>

<pre><code>&lt;bean id=""WSACallbackKlen"" class=""nbr.ei.util.LctionCallback""&gt;
        &lt;constructor-arg index=""0"" value=""http://serviations.bnst.n/toezicht/ka/km/KkService/tnRequest""&gt;&lt;/constructor-arg&gt;
        &lt;constructor-arg index=""1"" value=""http://servtions.bnst.n.tst.st3/toet/ka/km/Kervice""&gt;&lt;/constructor-arg&gt;
    &lt;/bean&gt; 
    &lt;int:chain input-channel=""kkChannel"" output-channel=""dest-channel""&gt;
        &lt;ws:header-enricher&gt;       
            &lt;ws:soap-action value=""http://servicons.belt.n/toet/ka/kk/KKserice/tnRequest""/&gt;
        &lt;/ws:header-enricher&gt;           
        &lt;ws:outbound-gateway uri=""http://bb-k1.ts.nst.n/wsb/router"" request-callback=""WSACallbackKlen"" message-sender=""kkMsageSender""/&gt;
    &lt;/int:chain&gt; 
</code></pre>

<p>It was made secure and so updated uri in outbound gateway to
uri=""<strong>https</strong>://bb-k1.ts.nst.n/wsb/router""</p>

<p>Error when doing integration testing with spring context -</p>

<pre><code>org.springframework.ws.client.WebServiceIOException: I/O error: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:561)
at org.springframework.integration.ws.SimpleWebServiceOutboundGateway.doHandle(SimpleWebServiceOutboundGateway.java:98)
..

Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1964)
</code></pre>

<p>How to create ws:outbound-gateway work for https type? I dont know how to specify certificate, if required</p>
",https://stackoverflow.com/questions/54255310/spring-integration-ws-outbound-gateway-ssl,['spring-integration'],546,True,0,1
Parse LocalDateTime in TestRestTemplate not working (Bad request ),"<p>A newbie to Spring boot running integration testing. Using exchange method of <code>TestRestTemplate</code> I am unable to pass LocalDateTime request params to test method. Here's my <code>MemberController</code> method and <code>MemberControllerTest</code> method. I guess it has to do with the date and format because the same exchange method works when I test for get member with id as integer. </p>

<pre><code>    @Test
        @Transactional
        public void getTopMembersss() throws Exception {

            LocalDateTime startTime = LocalDateTime.of(2015, Month.JULY, 29, 19, 30, 40);
            LocalDateTime endTime = LocalDateTime.of(2019, Month.JANUARY, 01, 19, 30, 40);

            ResponseEntity&lt;List&lt;TopMemberDTO&gt;&gt; response = template.exchange(
                    ""/api/member/top-member?startTime={startTime}&amp;endTime={endTime}"", HttpMethod.GET, null,
                    new ParameterizedTypeReference&lt;List&lt;TopMemberDTO&gt;&gt;() {
                    }, startTime.toString(), endTime.toString());

            // , ""2018-12-31T12:12:12"", ""2018-12-31T12:12:12""

            Assert.assertEquals(200, response.getStatusCode().value());

        }

@GetMapping(path = ""/api/member/top-member?startTime={startTime}&amp;endTime={endTime}"")
    public ResponseEntity&lt;List&lt;TopMemberDTO&gt;&gt; getTopMembers(
            @RequestParam(value = ""startTime"", required = true) @DateTimeFormat(pattern = ""yyyy-MM-dd'T'HH:mm:ss"") LocalDateTime startTime,
            @RequestParam(value = ""endTime"", required = true) @DateTimeFormat(pattern = ""yyyy-MM-dd'T'HH:mm:ss"") LocalDateTime endTime) {
        List&lt;TopMemberDTO&gt; topDrivers = new ArrayList&lt;&gt;();
        /**
         * Your Implementation Here.
         * 
         */

        topDrivers = memberService.findTopMembersCount(startTime, endTime);

        if (topDrivers.isEmpty()) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(topDrivers);

    }

}


java.lang.AssertionError: expected:&lt;200&gt; but was:&lt;400&gt;
    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.Assert.failNotEquals(Assert.java:834)
    at org.junit.Assert.assertEquals(Assert.java:645)
    at org.junit.Assert.assertEquals(Assert.java:631)
    at com.thankgod.controller.MemberControllerTest.getTopMembersss(MemberControllerTest.java:137)
    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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
</code></pre>
",https://stackoverflow.com/questions/54050714/parse-localdatetime-in-testresttemplate-not-working-bad-request,"['spring', 'spring-boot']",217,True,0,1
How to configure jest-mongodb(@shelf/jest-mongodb) in typescript-node project?,"<p>I am working on integration testing, So getting a data from database makes testcase execution slower. Tried with jest-mongodb to set up a temp db. but could not find a proper documentation for setting up jest-mongodb in typescript-nodejs project. please help me to overcome this issue.</p>
<p>test.ts(db configuration file based on this test suites connect to db)</p>
<pre><code>export default {    
    jwtPrivateKey: 'secretkey',
    // Testing Database configuration
    MongoDB: {
        dbConfig: {
            user: 'user name',
            host: 'some host',
            port: 'some port',
            authMechanism: 'some mechanism',
            authSource: 'access level',
            dbName: 'database name',
            metadata: 'initializer'
        }
    }
};
</code></pre>
",https://stackoverflow.com/questions/59298007/how-to-configure-jest-mongodbshelf-jest-mongodb-in-typescript-node-project,"['javascript', 'node.js', 'typescript', 'jestjs']",6635,False,4,5
CommandAcceptanceException When Running Integration tests in Spring,"<p>I am using the h2 database for my integration testing in my spring application. I've added the h2 dependency in my <code>pom.xml</code> file:</p>

<pre><code>&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;
</code></pre>

<p>and created the following files under <code>src/test/resources</code></p>

<p>application.yml</p>

<pre><code>spring:
  application:
    name: scratch-app
  jpa:
    hibernate:
      show_sql: true
      format_sql: true
      ddl-auto: create-drop
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
</code></pre>

<p>and import.sql</p>

<pre><code>CREATE TABLE CustomerMaster(
    customerID INT PRIMARY KEY,
    firstName VARCHAR(50) NULL,
    lastName VARCHAR(50) NULL
)

INSERT  INTO CustomerMaster (cFirst, cLast)
VALUES  ('Generic', 'Customer');
</code></pre>

<p>and created the following integration test class</p>

<pre><code>@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@TestPropertySource(locations = ""classpath:application.yml"")
public class CustomerControllerIT {
    private MockMvc mockMvc;

    @Autowired
    private CustomerController controller;
    @Autowired
    private ObjectMapper objectMapper;

    @Before
    public void setUp() throws Exception {
        mockMvc = standaloneSetup(controller).build();
    }

    @Test
    @Sql(scripts = ""file:src/test/sql/import.sql"")
    public void testFindCustomerById_valid() throws Exception {
        mockMvc.perform(get(""/customer/1"").contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath(""$.firstName"").value(""Generic""))
                .andReturn();
    }
}
</code></pre>

<p>When I try to run my test, a <code>CommandAcceptanceException</code> is thrown:</p>

<pre><code>org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL ""CREATE TABLE CustomerMaster("" via JDBC Statement
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applyImportSources(SchemaCreatorImpl.java:491) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:180) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:155) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.internal.SessionFactoryImpl.&lt;init&gt;(SessionFactoryImpl.java:310) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:467) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:939) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1804) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1083) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:853) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127) ~[spring-boot-test-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) ~[junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) ~[junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) ~[junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) ~[junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) ~[junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) ~[junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) ~[junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) ~[junit-4.12.jar:4.12]
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) ~[junit-rt.jar:na]
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) ~[junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) ~[junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) ~[junit-rt.jar:na]
Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement ""CREATE TABLE CUSTOMERMASTER( [*]""; expected ""identifier""; SQL statement:
CREATE TABLE CustomerMaster( [42001-197]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:357) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.message.DbException.getSyntaxError(DbException.java:217) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.command.Parser.readColumnIdentifier(Parser.java:3507) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.command.Parser.parseTableColumnDefinition(Parser.java:6661) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.command.Parser.parseCreateTable(Parser.java:6570) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.command.Parser.parseCreate(Parser.java:4615) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.command.Parser.parsePrepared(Parser.java:380) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.command.Parser.parse(Parser.java:335) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.command.Parser.parse(Parser.java:307) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.command.Parser.prepareCommand(Parser.java:278) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.engine.Session.prepareLocal(Session.java:611) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.engine.Session.prepareCommand(Session.java:549) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1247) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:217) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:205) ~[h2-1.4.197.jar:1.4.197]
    at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:95) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-3.2.0.jar:na]
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    ... 56 common frames omitted
</code></pre>

<p>Could anyone tell me why my <code>import.sql</code> script is failing? Thanks.</p>
",https://stackoverflow.com/questions/54831688/commandacceptanceexception-when-running-integration-tests-in-spring,"['spring', 'integration-testing', 'h2', 'spring-test', 'spring-test-mvc']",417,True,0,1
Spring boot integration testing not working JUnit5,"<p>I am trying to do integration testing in spring boot application using JUnit5 but it gives me Null Pointer Exception at that line <code>String response = restTemplate.getForObject(""/v1/students"", String.class);</code>. All unit tests are working fine but I can't figure out what's wrong with the integration test.
Here is the Integration Test class:</p>

<pre><code>package com.demo.student.demo;

import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class DemoApplicationTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void contextLoads() throws Exception {
        String response = restTemplate.getForObject(""/v1/students"", String.class);
        JSONAssert.assertEquals(""[{'id':1,'email':'test@test.test'}]"", response, false);
    }

}
</code></pre>

<p>Here is the stacktrace:</p>

<pre><code>java.lang.NullPointerException
    at com.demo.student.demo.DemoApplicationTest.contextLoads(DemoApplicationTest.java:18)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:513)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:170)
    at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:166)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:113)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:113)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:121)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:121)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
    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)
</code></pre>

<p>And the REST endpoint I am testing against:</p>

<pre><code>package com.demo.student.demo.service;

import com.demo.student.demo.entity.Student;
import com.demo.student.demo.exception.StudentNotFoundException;
import com.demo.student.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class StudentServiceImpl implements StudentService {

    private StudentRepository studentRepository;

    @Autowired
    public StudentServiceImpl(StudentRepository studentRepository){
        this.studentRepository = studentRepository;
    }

    @Override
    public List&lt;Student&gt; findAl() {
        return studentRepository.findAll();
    }

    @Override
    public Student findById(long id) {
        return  studentRepository.findById(id).orElseThrow(() -&gt; new StudentNotFoundException(id));
    }

    @Override
    public Student saveOrUpdate(Student student) {
        studentRepository.save(student);
        return student;
    }

    @Override
    public void deleteById(long id) {
        if(this.findById(id) != null)
            studentRepository.deleteById(id);
    }

}
</code></pre>
",https://stackoverflow.com/questions/59057032/spring-boot-integration-testing-not-working-junit5,"['spring', 'spring-boot', 'integration-testing', 'junit5']",1329,False,0,1
What is the difference between using `react-testing-library` and `cypress`?,"<p>So, <code>react-testing-library</code> is used for unit/integration testing, and <code>cypress</code> is used for e2e testing.  However, both appear to do the same thing:</p>

<p><code>react-testing-library</code></p>

<ul>
<li>Facilitates mocking</li>
<li>Tests as a user would</li>
<li>Starts with the top-level component (not a hard and fast requirement, but if you don't you end up with a bunch of duplicate test cases in your sub-component testing)</li>
<li>Instant feedback, fast</li>
</ul>

<p><code>cypress</code></p>

<ul>
<li>Facilitates mocking</li>
<li>Tests as a user would</li>
<li>Starts with the top-level component (the page)</li>
<li>Delayed feedback, slow, but provides extra tooling (video proof, stepping through tests, etc.)</li>
</ul>

<p>Aside from the feedback cycle, they appear to be almost identical.  Can somebody clarify what the differences are?  Why would you want to use both?</p>
",https://stackoverflow.com/questions/59162638/what-is-the-difference-between-using-react-testing-library-and-cypress,"['cypress', 'react-testing-library']",12741,True,42,2
Spring Boot repository not working during testing,"<p>I've searched Google and SO answers and have tried many variations with no luck. I'm trying to enable integration testing for my Spring Boot endpoints for the past few days now. Here are the details:</p>

<p>The error is a NullPointerException found in the EnclosureController class (where I've marked the object in a comment with NULL)</p>

<p>If there exists a more efficient way to perform integration testing, as compared to MockMvc, I'm very open to suggestions.</p>

<p>TestClass (in root.package.test )</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(EnclosureController.class)
public class EnclosureControllerTest {

@Autowired
private MockMvc mvc;

@MockBean
private EnclosureRepository enclosureRepository;

//static final strings for Enclosure initialization

@Test
public void createEnclosureAPI() throws Exception
{
    mvc.perform( MockMvcRequestBuilders
            .post(""/enclosure"")
            .header(""Authorization"", ""TEST"")
            .content(asJsonString(new Enclosure(ENCLOSURE_TITLE, ENCLOSURE_LOCATION, DIMENSIONAL_UNITS, ENCLOSURE_LENGTH, ENCLOSURE_WIDTH, ENCLOSURE_HEIGHT)))
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isCreated())
            .andDo(print())
            .andExpect(MockMvcResultMatchers.jsonPath(""$.enclosureId"").exists());
}
}
</code></pre>

<p>EnclosureController (I removed the authentication checks since the error pertains to the repo)</p>

<pre><code>@RestController
public class EnclosureController {

final
private EnclosureRepository repository;

@Autowired
public EnclosureController(EnclosureRepository repository) {
    this.repository = repository;
}

@RequestMapping(value = {""/enclosure""},
        method = RequestMethod.POST,
        consumes = ""application/json"",
        produces = APPLICATION_JSON_VALUE)
@ResponseBody
@Async(""asyncExecutor"")
public CompletableFuture&lt;Enclosure&gt; createEnclosure(
        @Valid @RequestBody Enclosure request,
        @RequestHeader(value = ""Authorization"") String auth,
        HttpServletResponse response
) {

    //NULL on repository (Optional is never returned. NullPointerExcep thrown on repository.save)
    int enclosureId = Optional.of(repository.save(request)).orElse(new Enclosure(0)).getEnclosureId();

    if (enclosureId &gt; 0)
        response.setStatus(HttpServletResponse.SC_CREATED);

    return CompletableFuture.completedFuture(repository.findByEnclosureId(enclosureId));

}

}
@RequestMapping(value = {""/enclosure/{id}""},
        method = RequestMethod.GET)
@ResponseBody
@Async(""asyncExecutor"")
public CompletableFuture&lt;Enclosure&gt; getSingleEnclosure(
        @PathVariable(""id"") int id,
        @RequestHeader(value = ""Authorization"") String auth,
        HttpServletResponse response
) {

    return  CompletableFuture.completedFuture(repository.findByEnclosureId(id));

}
</code></pre>

<p>Repository</p>

<pre><code>@Repository
public interface EnclosureRepository extends CrudRepository&lt;Enclosure, Integer&gt; {
Enclosure findByEnclosureId(Integer enclosureId);
List&lt;Enclosure&gt; findAll();
}
</code></pre>

<p>RepositoryImpl (for bean decleration. Note removed unneeded methods for this post)</p>

<pre><code>public class EnclosureRepositoryImpl implements EnclosureRepository {

private static ConcurrentHashMap&lt;Integer, Optional&lt;Enclosure&gt;&gt; repo = new ConcurrentHashMap&lt;&gt;();
private static AtomicInteger maxId = new AtomicInteger();

@Override
public Enclosure findByEnclosureId(Integer enclosureId) {
    return repo.get(enclosureId).orElse(new Enclosure());
}

@Override
public Enclosure save(Enclosure entity) {

    repo.put(maxId.incrementAndGet(), Optional.of(entity));

    return repo.get(maxId).orElse(new Enclosure());
}

@Override
public Optional&lt;Enclosure&gt; findById(Integer integer) {
    return repo.get(integer);
}

@Override
public boolean existsById(Integer integer) {
    return repo.containsKey(integer);
}
}
</code></pre>

<p>Application</p>

<pre><code>@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
</code></pre>

<p>Configuration</p>

<pre><code>@Configuration
@EnableJpaRepositories(basePackages = {
    ""root.package.model.repository""
})
@EnableTransactionManagement
@EnableAsync
public class BeanConfig {

@Override
@Bean(name = ""asyncExecutor"")
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(3);
    executor.setMaxPoolSize(100);
    executor.setQueueCapacity(100);
    executor.setThreadNamePrefix(""AGMSpringAsyncThread-"");
    executor.initialize();

    return executor;
}

@Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(entityManagerFactory);
    return transactionManager;
}

@Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,
                                                            Environment env) {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setDataSource(dataSource);
    entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    entityManagerFactoryBean.setPackagesToScan(""io.colby.model.repository"");

    Properties jpaProperties = new Properties();

    //Configures the used database dialect. This allows Hibernate to create SQL
    //that is optimized for the used database.
    jpaProperties.put(""hibernate.dialect"", env.getRequiredProperty(""hibernate.dialect""));

    //Specifies the action that is invoked to the database when the Hibernate
    //SessionFactory is created or closed.
    jpaProperties.put(""hibernate.hbm2ddl.auto"",
            env.getRequiredProperty(""hibernate.hbm2ddl.auto"")
    );

    //Configures the naming strategy that is used when Hibernate creates
    //new database objects and schema elements
    jpaProperties.put(""hibernate.ejb.naming_strategy"",
            env.getRequiredProperty(""hibernate.ejb.naming_strategy"")
    );

    //If the value of this property is true, Hibernate writes all SQL
    //statements to the console.
    jpaProperties.put(""hibernate.show_sql"",
            env.getRequiredProperty(""hibernate.show_sql"")
    );

    //If the value of this property is true, Hibernate will format the SQL
    //that is written to the console.
    jpaProperties.put(""hibernate.format_sql"",
            env.getRequiredProperty(""hibernate.format_sql"")
    );

    entityManagerFactoryBean.setJpaProperties(jpaProperties);

    return entityManagerFactoryBean;
}

@Bean(destroyMethod = ""close"")
DataSource dataSource(Environment env) {
    HikariConfig dataSourceConfig = new HikariConfig();
    dataSourceConfig.setDriverClassName(env.getRequiredProperty(""db.driver""));
    dataSourceConfig.setJdbcUrl(env.getRequiredProperty(""db.url""));
    dataSourceConfig.setUsername(env.getRequiredProperty(""db.username""));
    dataSourceConfig.setPassword(env.getRequiredProperty(""db.password""));

    return new HikariDataSource(dataSourceConfig);
}

@Bean
public EnclosureRepository enclosureRepository(){
    return new EnclosureRepositoryImpl();
}
}
</code></pre>

<p>Enclosure</p>

<pre><code>@Component
@Entity
@Table(name=""enclosure"")
public class Enclosure {


@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = ""enclosure_id"", nullable = false, updatable = false)
@JsonProperty(""enclosure-id"")
private Integer enclosureId;

@Column(name = ""title"")
@Size(max = 255)
@NotBlank
private String title;

@Column(name = ""location"")
@Size(max = 255)
private String location;

@Column(length = 25, name = ""dimension_units"")
@Size(max = 25)
@JsonProperty(""dimension-units"")
private String dimensionUnits;

@CreationTimestamp
@Column(nullable = false, name = ""insert_timestamp"")
@JsonProperty(""created-date-time"")
private LocalDateTime insertTimestamp;

@UpdateTimestamp
@Column(name = ""update_timestamp"")
@JsonProperty(""last-updated-date-time"")
private LocalDateTime updateTimestamp;


@Column(length = 5, precision = 2)
private double length;
@Column(length = 5, precision = 2)
private double width;
@Column(length = 5, precision = 2)
private double height;

public Enclosure(String title,
                 String location,
                 String dimensionUnits,
                 double length, double width, double height) {
    this.title = title;
    this.location = location;
    this.dimensionUnits = dimensionUnits;
    this.length = length;
    this.width = width;
    this.height = height;
}

public Enclosure(int enclosureId){
    this.enclosureId = enclosureId;
}

public Enclosure(){

}
//Getters and setters...
</code></pre>

<p>Directory Tree</p>

<pre><code>.
└── main
    ├── java
    │   └── root
    │       └── package
    │           ├── Application.java
    │           ├── configuration
    │           │   ├── BeanConfig.java
    │           ├── model
    │           │   ├── entity
    │           │   │   ├── Enclosure.java
    │           │   └── repository
    │           │       ├── EnclosureRepository.java
    │           │       ├── EnclosureRepositoryImpl.java
    │           ├── routes
    │           │   ├── enclosure
    │           │   │   └── controller
    │           │   │       └── EnclosureController.java
    │           └── test
    │               └── routes
    │                   └── enclosure
    │                       └── EnclosureControllerTest.java
    ├── resources
    │   ├── application.properties
    └── test
        └── java
</code></pre>

<p>application.properties</p>

<pre><code> #Database Configuration
    db.driver=org.h2.Driver
    db.url=jdbc:h2:mem:datajpa
    db.username=sa
    db.password=

    spring.jackson.default-property-inclusion=non_null

    # Details for our datasource
    spring.datasource.url = jdbc:postgresql://host/db
    spring.datasource.username = user
    spring.datasource.password = pass

    # Hibernate properties
    spring.jpa.database-platform = org.hibernate.dialect.PostgreSQL94Dialect
    spring.jpa.show-sql = true
    spring.jpa.hibernate.ddl-auto = create-drop
    spring.jpa.hibernate.naming.implicit-strategy = org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
    spring.jpa.properties.hibernate.format_sql=true
</code></pre>

<p>Note I had the test class in test.java, however I wanted to get the test working in root.package subdirectory, then use @ComponentScan to point to the package tree to scan.</p>

<p>I was looking at the following tutorials to try and get the testing working:</p>

<pre><code>http://www.springboottutorial.com/integration-testing-for-spring-boot-rest-services
https://www.baeldung.com/spring-boot-testing
</code></pre>
",https://stackoverflow.com/questions/55089558/spring-boot-repository-not-working-during-testing,"['java', 'spring', 'database', 'spring-boot', 'java-8']",1316,True,0,1
How to test a GraphQL query providing an auth token with Apollo Server?,"<p><a href=""https://www.apollographql.com/docs/apollo-server/features/testing.html"" rel=""noreferrer"">Apollo Server Integration testing documentation</a> shows how to test simple queries using <code>createTestClient</code>:</p>

<pre class=""lang-js prettyprint-override""><code>const { query } = createTestClient(server);
const res = await query({ query: GET_LAUNCH, variables: { id: 1 } });
</code></pre>

<p>In the attempt to test <em>a query which requires an authorization token</em>, I have tried passing the <code>jwtToken</code> as an extra field to the object passed to query like below:</p>

<pre class=""lang-js prettyprint-override""><code>const res = await query({ 
  query: MY_QUERY, 
  http: { headers: { authorization: `Bearer ${jwtToken}` } },
});
</code></pre>

<p>Unfortunately this doesn't work. When trying to run it I get the following response:</p>

<pre><code>{
  ""http"": {
    ""headers"": {}
  },
  ""errors"": [{
    ""message"": ""must authenticate"",
    ""locations"": [{
      ""line"": 2,
      ""column"": 3
    }],
    ""path"": [""myQuery""],
    ""extensions"": {
      ""code"": ""UNAUTHENTICATED""
    }
  }],
  ""data"": {
    ""myQuery"": null
  }
}
</code></pre>

<p>Any idea how to properly test queries which require an authorization token?</p>

<p>Using:</p>

<pre><code>  ""devDependencies"": {
    ""jest"": ""^23.6.0"",
    ""apollo-server-testing"": ""^2.4.8""
  }
</code></pre>
",https://stackoverflow.com/questions/54928141/how-to-test-a-graphql-query-providing-an-auth-token-with-apollo-server,"['typescript', 'graphql', 'jestjs', 'apollo-server']",5302,True,9,3
Wiremock testing with Dynamic HEADERS,"<p>I have one wiremock test case which is being used for integration testing. Everything is good but I am stuck at place where I am generating <code>HttpHeaders</code> dynamically i.e. <code>timestamp</code> etc.
Since I have to mention some dummy values in <code>JSON</code> File(like below). 
Can you please help me putting something there which will pass any string that is being generated in my code dynamically.</p>

<pre><code>{
  ""request"": {
    ""method"": ""GET"",
    ""url"": ""&lt;SOME_URL&gt;"",
    ""headers"" : {
      ""signature"" : {
        ""contains"" : ""some dynamically string""
      },
      ""timestamp"": {
        ""contains"" : ""dynamic timestamp""
      },
      ""traceid"" : {
        ""contains"" :""dynamic alpha numeric string""
      }
    }
  },
  ""response"": {
    ""status"": 200,
    ""jsonBody"": {
        //Some response
    }
  }
}
</code></pre>
",https://stackoverflow.com/questions/58204580/wiremock-testing-with-dynamic-headers,"['json', 'spring-boot', 'junit', 'junit4', 'wiremock']",314,False,0,1
How can i add multiple user roles to single pathMatcher/Route in Spring WebFlux Security(Reactive Spring Security) Config?,"<p>i have a route that needs to authenticated for more than one user. performing integration testing on <strong>spring cloud gateway</strong> service to test all the routes security working as expected or not. how can i add more than 1 user role to single pathMatcher/route? </p>

<p>Using Spring Boot 2.1.6, Spring Cloud Finchely.SR2, Spring Cloud Gateway, Spring WebFlux Security(Reactive Spring Security)</p>

<pre><code>@EnableWebFluxSecurity
public class SecurityConfig {

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {

http.csrf().disable()        
           .formLogin().disable()
           .logout().disable()
           .authorizeExchange()
           .pathMatchers(prefix + ""/publish/**"")
           .hasRole(""XYZ_ROLE"") //Here i want to add more than one user role
           .anyExchange()
           .authenticated().and().httpBasic();
        }
}
</code></pre>
",https://stackoverflow.com/questions/57633276/how-can-i-add-multiple-user-roles-to-single-pathmatcher-route-in-spring-webflux,"['java', 'spring-security', 'spring-webflux', 'spring-cloud-gateway']",2649,True,0,2
Only run integration test when deploying from staging to production,"<p>I have 3 main branches in my gitlab project: <code>dev</code> , <code>staging</code>, <code>production</code>. I'm using postman newman for integration testing like this in <code>.gitlab-ci.yml</code>:</p>

<pre><code>postman_tests:
    stage: postman_tests
    image: 
        name: postman/newman_alpine33
        entrypoint: [""""] 
    only:
      - merge_requests
    script:
        - newman --version
        - newman run https://api.getpostman.com/collections/zzz?apikey=zzz  --environment https://api.getpostman.com/environments/xxx?apikey=xxxx
</code></pre>

<p>this script only run in merge request approval process from dev to staging , or staging to production. The problem is i need to only run this postman newman test when  the process of merge request approval from staging to production, how can i achieve this?</p>
",https://stackoverflow.com/questions/57247066/only-run-integration-test-when-deploying-from-staging-to-production,"['continuous-integration', 'gitlab', 'integration-testing', 'gitlab-ci', 'gitlab-ci-runner']",247,True,3,1
TestServer returns 404 not found,"<p>I'm using aspnetcore 3.0 preview 7 for my web api project. Currently I'm implementing the integration tests. (To make the tests easier first, I commented out the Authorize attribute on the controllers.)</p>

<p>The server responds ""404 not found"".
I'm confused about not having ""usemvc"" in the startup anymore - should I do something different in setting up the test server now?
Or does anybody have an idea what causes the 404?
(The MS docs for integration testing with 3.0 are not updated yet).
I also tried with preview 8, but same issue.</p>

<p>Test class:</p>

<pre><code>   [OneTimeTearDown]
    public virtual void Cleanup()
    {
        _unAuthenticatedServer.Dispose();
    }

    [OneTimeSetUp]
    public virtual void Initialize()
    {
        _unAuthenticatedServer = CreateServer(null);
    }

    protected TestServer CreateServer(
        string currentDirectory = null)
    {
        IWebHostBuilder webHostBuilder = WebHost.CreateDefaultBuilder();

        webHostBuilder.UseContentRoot(currentDirectory == null
            ? Directory.GetCurrentDirectory()
            : Directory.GetCurrentDirectory() + $""\\{currentDirectory}"");


        webHostBuilder.UseStartup&lt;TestStartup&gt;();
        webHostBuilder.UseEnvironment(""Test"");

        webHostBuilder.ConfigureAppConfiguration((_, config) =&gt; config.AddJsonFile(""appsettings.Test.json""));

        return new TestServer(webHostBuilder);
    }

    [Test, Order(1)]
    public async Task Should_Get_Games_Return_StatusCode_Ok()
    {
        //Arrange
        IList&lt;GameDto&gt; expectedDtos = GameDtoTestData.Games;

        //Act
        HttpResponseMessage responseMessage = await _unAuthenticatedServer
            .CreateClient()
            .GetAsync(""api/games"");

        //Assert
        responseMessage.StatusCode.Should().Be(HttpStatusCode.OK); // but is: 404 NotFound

        var responseString = await responseMessage.Content.ReadAsStringAsync();
        IEnumerable&lt;GameDto&gt; result = JsonConvert.DeserializeObject&lt;IEnumerable&lt;GameDto&gt;&gt;(responseString);

        result.Should().BeEquivalentTo(expectedDtos);
    }
</code></pre>

<p>Controller:</p>

<pre><code>[Route(""api/[controller]"")]
[ApiController]
public class GamesController : ControllerBase
{
    private readonly IGameService _gameService;

    public GamesController(IGameService gameService)
    {
        _gameService = gameService;
    }

    [HttpGet]
    public async Task&lt;ActionResult&lt;IEnumerable&lt;GameDto&gt;&gt;&gt; Get()
    {
        return Ok(await _gameService.GetAsync());
    }
}
</code></pre>

<p>Installed Nuget packages test project:</p>

<pre><code> &lt;ItemGroup&gt;
    &lt;PackageReference Include=""FluentAssertions"" Version=""5.8.0"" /&gt;
    &lt;PackageReference Include=""Microsoft.AspNetCore.Mvc.Testing"" Version=""3.0.0-preview7.19365.7"" /&gt;
    &lt;PackageReference Include=""Microsoft.AspNetCore.TestHost"" Version=""3.0.0-preview7.19365.7"" /&gt;
    &lt;PackageReference Include=""Microsoft.EntityFrameworkCore.InMemory"" Version=""2.2.6"" /&gt;
    &lt;PackageReference Include=""nunit"" Version=""3.12.0"" /&gt;
    &lt;PackageReference Include=""NUnit3TestAdapter"" Version=""3.14.0"" /&gt;
    &lt;PackageReference Include=""Microsoft.NET.Test.Sdk"" Version=""16.2.0"" /&gt;
  &lt;/ItemGroup&gt;
</code></pre>

<p>Installed Nuget packages api project:</p>

<pre><code>  &lt;ItemGroup&gt;
    &lt;PackageReference Include=""MediatR.Extensions.Microsoft.DependencyInjection"" Version=""7.0.0"" /&gt;
    &lt;PackageReference Include=""Microsoft.AspNetCore.Authentication.AzureADB2C.UI"" Version=""3.0.0-preview6.19307.2"" /&gt;
    &lt;PackageReference Include=""Microsoft.EntityFrameworkCore"" Version=""2.2.6"" /&gt;
    &lt;PackageReference Include=""Microsoft.EntityFrameworkCore.Design"" Version=""2.2.6"" /&gt;
    &lt;PackageReference Include=""Microsoft.EntityFrameworkCore.SqlServer"" Version=""2.2.6"" /&gt;
    &lt;PackageReference Include=""Microsoft.EntityFrameworkCore.Tools"" Version=""2.2.6""&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;
</code></pre>
",https://stackoverflow.com/questions/57504788/testserver-returns-404-not-found,"['c#', 'asp.net-core', 'nunit', 'integration-testing', 'asp.net-core-webapi']",9217,True,29,1
Kill Python thread running a web server,"<p>I'm trying to reboot a web server written in Python during some integration testing. The server runs as a thread during the tests, so I can continue sending POST \ GET requests to it, and asserting the answers.</p>

<p>I tried killing the thread by force:</p>

<pre><code>t = threading.Thread(name='server', target=main, daemon=True)
.....
t._tstate_lock = None
t._stop()
t.join()
</code></pre>

<p>While debugging, I can actually see that the thread is stopped, but the webserver is still up, for some reason.</p>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/56314485/kill-python-thread-running-a-web-server,"['python', 'multithreading', 'web', 'server', 'kill']",342,False,0,1
Flutter Integration Testing- How to go back to previous screen when no back button available on screen,"<p>How to go back to previous screen when no back button available on screen? 
Additional Information: I am trying to automate integration testing for flutter app. There is no back button on screen which I can use to go back screen. 
Additional information: I am writing integration tests, for same I need to go back to previous screen. And due to design there is no back button on screen, I need to do by scripts only.  </p>
",https://stackoverflow.com/questions/59044829/flutter-integration-testing-how-to-go-back-to-previous-screen-when-no-back-butt,"['flutter', 'dart', 'flutter-test']",3633,True,8,5
@AutoConfigureWebTestClient(timeout = &quot;600000&quot;) has no effect,"<p>I'm using <code>WebTestClient</code> to do some integration testing of a controller. If I set a breakpoint inside the controller I hit the standard timeout of 5s of the <code>WebTestClient</code>. The solution to this is to add <code>@AutoConfigureWebTestClient(timeout = ""600000"")</code> to my test as stated her <a href=""https://stackoverflow.com/a/49496309/671639"">Timeout on blocking read for 5000 MILLISECONDS in Spring WEBFLUX</a>.</p>

<p>For me <code>@AutoConfigureWebTestClient(timeout = ""600000"")</code> does not change anything. I still get the timout exception after 5s.</p>

<p>Any ideas what's wrong?</p>

<pre><code>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ActiveProfiles(""test"")
@Transactional
@Import(EntityFactoryConfiguration.class)
@AutoConfigureWebTestClient(timeout = ""600000"") // giv me 10 min for debugging
public class LogControllerIntegrationTest {

    ...

    @Autowired
    private WebTestClient webTestClient;

    ...

    @Test
    public void myTest() {
        ...
        webTestClient.post().uri(""/log"")
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .accept(MediaType.APPLICATION_JSON_UTF8)
                .body(BodyInserters.fromObject(protocolLine))
                .exchange()
                .expectStatus().isOk();

    }
</code></pre>
",https://stackoverflow.com/questions/56784289/autoconfigurewebtestclienttimeout-600000-has-no-effect,"['java', 'spring-boot', 'junit', 'spring-boot-test']",5699,True,1,3
Need Guidance for Intregration Testing with the new .Net Core 3.0 grpc service,"<p>I am playing around with the new GRPC Service for .Net Core 3.0 template.  I have successfully created the Hello World service.  I am now trying to add a test project to this solution.</p>

<p>I can see how to make an in-memory server for integration testing for a regular HTTP Client/Server .Net Core service.  But I can find no example or guidance anywhere on the net for when using grpc protodef client/server. The issue appears to be with the CreateClient() method which returns a plain old HTTP client, and not a grpc one.</p>

<p>It would be good if a barebones integration test was included with the project created by the VS 2019 template. The main reason for me to look at Microservices and in particular using grpc was the idea that I can have small blocks that are easily testable with an automated testing framework.  But I seem to have fallen at the first hurdle.</p>

<p>[Added]</p>

<p>Below is the simple test class. It uses NUnit.  The issue I have is finding a way to run the in-memory TestHost, the same way as I do for a .Net Core API or MVC app to allow integration testing.</p>

<pre><code>namespace Project.Tests
{
    public class Tests 
    {
        private Greeter.GreeterClient _client;
        private TestServer _server;

        [OneTimeSetUp]
        public void OneTimeSetup()
        {
            var server = new TestServer(WebHost.CreateDefaultBuilder()
                .UseStartup&lt;TestStartup&gt;()
                .UseEnvironment(""Development"")
                .UseUrls(""https://localhost:5001""));
        }

        [SetUp]
        public void Setup()
        {
            var channel = GrpcChannel.ForAddress(""https://localhost:5001"");
            _client = new Greeter.GreeterClient(channel);
        }

        [Test]
        public async Task Test1()
        {
            var reply = await _client.SayHelloAsync(new HelloRequest { Name = ""GreeterClient"" });
            Assert.IsTrue(reply.Message == ""Hello GreeterClient"");
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/58255190/need-guidance-for-intregration-testing-with-the-new-net-core-3-0-grpc-service,"['c#', 'asp.net-core', 'integration-testing', 'grpc']",2953,True,10,3
Embedded Postgres cannot obtain process PID on Mac OS,"<p>I'm using <a href=""https://github.com/yandex-qatools/postgresql-embedded"" rel=""nofollow noreferrer"">embedded PostgreSQL</a> with Java 11 for integration testing. On Windows it runs fine, but on Mac it first downloads Mac OS binaries (which is expected):</p>

<pre><code>Extract /Users/fubar/.embedpostgresql/postgresql-11.1-1-osx-binaries.zip START
</code></pre>

<p>But then it fails with the following stacktrace:</p>

<pre><code>java.lang.NoSuchFieldException: handle
at java.base/java.lang.Class.getDeclaredField(Class.java:2411)
at de.flapdoodle.embed.process.runtime.Processes.windowsProcessId(Processes.java:109)
at de.flapdoodle.embed.process.runtime.Processes.access$200(Processes.java:51)
at de.flapdoodle.embed.process.runtime.Processes$PidHelper$2.getPid(Processes.java:209)
</code></pre>

<p>When I look into <code>Processes</code> source code I see that internally it uses <code>PidHelper.LEGACY</code>, that fails the first attempt to obtain pid via <code>unixLikeProcessId()</code>. </p>

<p>Could anyone, please, give a hint why this is happenning or how to fix that?</p>
",https://stackoverflow.com/questions/56596979/embedded-postgres-cannot-obtain-process-pid-on-mac-os,"['macos', 'java-11', 'embedded-postgres']",909,False,0,1
Docker - Selenium Hub,"<p>I'm using a Docker image for Selenium (selenium/standalone-chrome).
My goal is to use it for integration testing with some python scripts.
Everything works pretty fine, I'm using the driver with remote:</p>

<pre><code>browser = webdriver.Remote(command_executor='http://192.168.99.100:4444/wd/hub',   desired_capabilities=DesiredCapabilities.CHROME)
</code></pre>

<p>My goal is to create a Chrome profile that will be persistend on the docker image, and I can reuse it in the scripts with a command like:</p>

<pre><code>options.addArguments(""user-data-dir=/path/to/your/custom/profile"");
</code></pre>

<p>How can I create the persisten profile?
Thx</p>
",https://stackoverflow.com/questions/57328887/docker-selenium-hub,"['python', 'selenium', 'docker', 'selenium-docker']",68,False,0,0
Testing Custom Factory Middleware,"<p>I am creating an asp.net core web app, which creates routes from user defined sources (config, database etc). I have used a middleware factory based approach which works fine, except I do not know how to isolate a middleware for unit/integration testing. I use the route data from the HttpContext to validate the incoming request against the user defined configuration source, so I need the HttpContext to have RouteData, which is why I am leaning towards Integration testing with xUnit.</p>

<p>If I make a request using a httpclient created via AspNetCore.TestHost.TestServer.CreateCLient(), I work my way through my entire call chain, which is what I expect. What I need to be able to do is terminate the middleware or provide the HttpContext with RouteData. </p>

<p>I have tried an ugly unit test using AutoFixture and the DefaultHttpContext(), but as expected, I don't get any RouteData on my HttpContext, so my tests can never pass.</p>

<p>Middleware</p>

<pre><code>public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
     try 
     {
         if (_flowApis.Count == 0)
              throw new ArgumentNullException();

          var doesMatch = false;
          var routeData = context.GetRouteData();

          foreach (var api in _flowApis)
          {
             if (!RequestType.IsValidRequestType(api.Request.Type))
                  throw new InvalidOperationException();
             else
                 foreach (Route route in routeData.Routers.Where(r =&gt; r.GetType() == typeof(Route)))
                 {
                     if (route.RouteTemplate == api.Route)
                     {
                        if (route.Constraints.TryGetValue(""httpMethod"", out IRouteConstraint routeConstraint))
                        {
                             var value = (HttpMethodRouteConstraint)routeConstraint;
                             if (value.AllowedMethods.Contains(api.Method))
                             {
                                 doesMatch = true;
                                 var routeValues = GetRouteValues(routeData);
                                 var request = new Core.Request(context.Request, api, routeValues);
                                        context.Items.Add(nameof(Core.Request), request);
                                        break;
                                    }
                                }
                            }
                        }
                    if (doesMatch)
                        break;
                }

                if (!doesMatch)
                {
                    context.Response.StatusCode = 404;
                    await context.Response.WriteAsync("""", new CancellationToken());
                }
                else
                    await next(context);
            }
            catch(ArgumentNullException ex)
            {
                var mex = new MiddleWareException&lt;MatchRouteToFlowApiMiddleware&gt;(""Flow Configuration in app.settings has not been set."", ex);
                context.Response.StatusCode = 500;
                await context.Response.WriteAsync("""", new CancellationToken());
            }
            catch (InvalidOperationException ex)
            {
                var mex = new MiddleWareException&lt;MatchRouteToFlowApiMiddleware&gt;(""Invalid Request Type"", ex);
                context.Response.StatusCode = 500;
                await context.Response.WriteAsync("""", new CancellationToken());
            }
        }
</code></pre>

<p>Unit Test</p>

<pre><code>[TestMethod]
public async Task Request_path_matches_an_api_route_and_method()
{
var fixture = ScaffoldFixture();
var flowApi = fixture.Build&lt;FlowApi&gt;()
                     .With(p =&gt; p.Route, ""/some/path"")
                     .With(m =&gt; m.Method, ""GET"")
                     .Create();
var flowApiRequest = fixture.Build&lt;Request&gt;()
                            .With(t =&gt; t.Type, ""CData"")
                            .Create();
flowApi.Request = flowApiRequest;
var flowConfiguration = fixture.Create&lt;FlowConfiguration&gt;();
flowConfiguration.FlowApis.Clear();
flowConfiguration.FlowApis.Add(flowApi);

var middleware = new MatchRouteToFlowApiMiddleware(flowConfiguration: flowConfiguration);
var context = new DefaultHttpContext();
context.Request.Method = ""GET"";
context.Request.Path = ""/some/path"";
context.Response.Body = new MemoryStream();

await middleware.InvokeAsync(context, (httpContext) =&gt; Task.FromResult(0));

context.Items.ContainsKey(nameof(Core.Request)).Should().BeTrue();
}

</code></pre>

<p>Integration test</p>

<pre><code>
[Fact]
public async Task Request_path_matches_an_api_route_and_method()
{
            //Arrange
   var response = await _httpClient.GetAsync(""/some/route"");

   response.StatusCode.Should().Be(500);
}

</code></pre>

<p>When executing the unit test, I can never satisfy the inner for each beacuse I don't have route data on the HttpContext.</p>

<p>When executing the integration test, the middleware executes as expected but since it does not terminate, i cannot validate</p>
",https://stackoverflow.com/questions/57767111/testing-custom-factory-middleware,"['c#', 'asp.net-core', 'xunit', 'asp.net-core-middleware']",1934,True,3,1
Not able to execute DataJpaTest,"<p>I have a <code>spring-data-jpa</code> repository called <code>TagRepository</code>. My <code>spring-boot</code> version is 2.1.2. I am using H2 dependency with runtime scope and I intend to use it for both the application and integration testing. I want to write a <code>DataJpaTest</code> for the TagRepository. I have written the following code:</p>

<pre><code>@RunWith(SpringRunner.class)
@EnableAutoConfiguration
@DataJpaTest
@ContextConfiguration(classes={TagRepository.class})
public class TagRepositoryTest {

    @Autowired
    private TestEntityManager testEntityManager;

    @Autowired
    private TagRepository tagRepository;

    @Test
    public void findByTagTest() {
        Tag tag = new Tag(""java"");
        testEntityManager.persistAndFlush(tag);

        Optional&lt;Tag&gt; optionalTag = tagRepository.findByTag(tag.getTag());
        if(!optionalTag.isPresent()) {
            fail(""Tag not found hence test failed"");
        }

        assertThat(optionalTag.get()).isEqualTo(tag);
    }
}
</code></pre>

<p>However, when I execute the test it says Application failed to start and I get following error:</p>

<pre><code>Invalid bean definition with name 'tagRepository' defined in null: Cannot register bean definition [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] for bean 'tagRepository': There is already [Generic bean: class [com.upday.task.repository.TagRepository]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] bound.

The bean 'tagRepository', defined in null, could not be registered. A bean with that name has already been defined in null and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
</code></pre>

<p>The test class itself resides in a different package than jpa repository.</p>
",https://stackoverflow.com/questions/54481897/not-able-to-execute-datajpatest,"['spring', 'spring-boot', 'testing', 'integration-testing']",1271,True,2,1
Integration Test powered by S4 SDK VDM fails during the maven build,"<p>I had used S4SDK VDM on my Integration Testing to test my ODATA services. There were some issues during the implementation &amp; Alexander bestowed me to get it working. (<a href=""https://stackoverflow.com/questions/56459465/vdm-for-integration-tests"">VDM for Integration Tests</a>)</p>

<p>When I had executed the JUnit in eclipse it works well. However when the JUnit runs during the Maven Build/ in the pipeline, it fails with the below error</p>

<pre><code>[INFO] 
[INFO] Results:
[INFO] 
[ERROR] Errors: 
[ERROR]   BusinessServiceIT.createBusinessService:132-&gt;createLandscapeObject:214 » ErpOData
[INFO] 
[ERROR] Tests run: 21, Failures: 0, Errors: 1, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 09:34 min
[INFO] Finished at: 2019-06-13T16:00:26+02:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:3.0.0-M3:test (default-test) on project x-srv-landscapeManagement-integration-tests: There are test failures.
[ERROR] 
[ERROR] Please refer to C:\Users\xxxxx\git\x-service-landscapeManagement\srv\integration-tests\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
[ERROR] -&gt; [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
[ERROR] 
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn &lt;goals&gt; -rf :x-srv-landscapeManagement-integration-tests
</code></pre>

<pre><code>    public static void beforeClass() {
        mockUtil.mockDefaults();
        mockUtil.mockAuditLog();

        lsoCreateHelper.withCustomHttpHeader(""Authorization"", jwToken).onRequestAndImplicitRequests();
        connectionHelper.withCustomHttpHeader(""Authorization"", jwToken).onRequestAndImplicitRequests();

    }```

``` @Before
    public void beforeEach() throws URISyntaxException, IOException, ODataException {
        mockUtil.mockDestination(""localhorst"", new URI(""http://localhost:"" + randomServerPort));
        erpConfCtx = new ErpConfigContext(""localhorst"");
        final String publicKey = FileUtils.readFile(""publicKey.txt"");
        final Map&lt;String, String&gt; verificationkey = ImmutableMap.of(""verificationkey"", publicKey);
        final JsonObject xsuaaServiceCredentials = new Gson().toJsonTree(verificationkey).getAsJsonObject();
        when(((ScpCfCloudPlatform) CloudPlatformAccessor.getCloudPlatform())
                .getXsuaaServiceCredentials(org.mockito.ArgumentMatchers.any(DecodedJWT.class)))
                        .thenReturn(xsuaaServiceCredentials);
    }```

</code></pre>

<pre><code>private UUID createLandscapeObject(String lsoType, String name, String customerNumber, String source,
        String usecase, String tenantId, String tenantType) throws ODataException {
    Properties properties = new Properties();
    List&lt;Properties&gt; propertySet = new ArrayList&lt;&gt;();

    if (usecase != null) {
        properties.setName(""useCase"");
        properties.setValue(usecase);
        properties.setSource(source);
        propertySet.add(properties);
    }

    if (tenantId != null) {
        propertySet = new ArrayList&lt;&gt;();
        properties.setName(""TenantId"");
        properties.setValue(tenantId);
        properties.setSource(source);
        propertySet.add(properties);
    }

    if (tenantType != null) {
        propertySet = new ArrayList&lt;&gt;();
        properties.setName(""TenantType"");
        properties.setValue(tenantType);
        properties.setSource(source);
        propertySet.add(properties);
    }

    LandscapeObjects landscapeObjects = new LandscapeObjects(null, null, null, null, null, name, ""benufromit_test"",
            lsoType, customerNumber, source, null, null, propertySet);
    LOG.info(""benu-business1"");

    final LandscapeObjectsCreateFluentHelper lsoCreateHelper = lmsService.createLandscapeObjects(landscapeObjects)
            .withCustomHttpHeader(""Authorization"", jwToken).onRequestAndImplicitRequests();

    landscapeObjects = lsoCreateHelper.execute(erpConfCtx);
    return landscapeObjects.getId();

}```
</code></pre>

<p>[ERROR] Errors: 
[ERROR]   BusinessServiceIT.createBusinessService:132->createLandscapeObject:214 » ErpOData</p>

<p><strong>target\surefire-reports</strong> </p>

<pre><code>-------------------------------------------------------------------------------
Test set: com.sap.crun.landscape.BusinessServiceIT
-------------------------------------------------------------------------------
Tests run: 3, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 66.107 s &lt;&lt;&lt; FAILURE! - in com.sap.crun.landscape.BusinessServiceIT
createBusinessService(com.sap.crun.landscape.BusinessServiceIT)  Time elapsed: 2.463 s  &lt;&lt;&lt; ERROR!
com.sap.cloud.sdk.s4hana.datamodel.odata.helper.ODataVdmErrorResultHandler$ErpODataException: 
The endpoint responded with HTTP error code 500.
. . 
Full error message: 
&lt;?xml version='1.0' encoding='UTF-8'?&gt;&lt;error xmlns=""http://schemas.microsoft.com/ado/2007/08/dataservices/metadata""&gt;&lt;code/&gt;&lt;message xml:lang=""en""&gt;Service not available: LandscapeService.&lt;/message&gt;&lt;/error&gt;
    at com.sap.crun.landscape.BusinessServiceIT.createLandscapeObject(BusinessServiceIT.java:214)
    at com.sap.crun.landscape.BusinessServiceIT.createBusinessService(BusinessServiceIT.java:132)```


**TestApplication**

package com.sap.crun.landscape;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.servlet.ServletComponentScan;
    import org.springframework.context.annotation.ComponentScan;

    @SpringBootApplication
    @ComponentScan(basePackages = {""com.sap.cloud.servicesdk.spring"", ""com.sap.crun.landscape""})
    @ServletComponentScan( ""com.sap.cloud.sdk"" )
    public class TestApplication {
        public static void main(String[] args) {
            SpringApplication.run(TestApplication.class, args);
        }
    }



</code></pre>
",https://stackoverflow.com/questions/56585795/integration-test-powered-by-s4-sdk-vdm-fails-during-the-maven-build,"['s4sdk', 'sap-cloud-sdk']",137,False,2,0
How to reconfigure LocalContainerEntityManagerFactoryBean in test,"<p>If I have a programmatically managed LocalContainerEntityManagerFactoryBean, like with a @Bean-annotated method:</p>

<pre><code>@Configuration
@EnableJpaRepositories(
  entityManagerFactoryRef = ""myEntityManager"",
  transactionManagerRef = ""myTransactionManager"",
  basePackages = {""com.mycompany.my.repository""}
)
public class MyDbConfig {

    @Bean
    public LocalContainerEntityManagerFactoryBean mcEntityManager() {
      LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
      //some production config here
      return em;
    }
}
</code></pre>

<p>How do I add this little JPA property only to be used for integration testing, ideally via something like a listener below (in the test classpath)</p>

<pre><code>public class AfterAllBeansCreatedListener {

    @Autowired
    private LocalContainerEntityManagerFactoryBean em

    @PostConstruct
    private void reconfigure() {
        HashMap&lt;String, Object&gt; properties = em.getJpaPropertyMap()
        properties.put(""hibernate.hbm2ddl.auto"", ""create"");
        em.setJpaPropertyMap(properties);
    }
}
</code></pre>

<p>Currently, I am using another @Bean-annotated method producing LocalContainerEntityManagerFactoryBean in a nested @TestConfiguration, but this means that I need to duplicate all the other creation logic for that bean, which is of course pure evil.</p>
",https://stackoverflow.com/questions/57433959/how-to-reconfigure-localcontainerentitymanagerfactorybean-in-test,"['spring', 'spring-boot', 'spring-boot-test']",265,False,1,1
How to override services that mocked using IWebHostBuilder.ConfigureTestServices in some tests,"<p>I have a custom <code>WebApplicationFactory&lt;Startup&gt;</code> for that i mocked some services to use for integration testing, like <code>DatabaseSeeder</code> in order to make the tests run faster.</p>

<p>Now i want to test the database seeding so I want to override the configuration to use the real database seeder this test.</p>

<p>I tried using <code>WithWebHostBuilder</code>, it returns a new <code>WebApplicationFactory&lt;Startup&gt;</code> but the <code>builder.ConfigureTestServices</code> method in this new factory run before the original so it get override by the original factory <code>ConfigureTestServices</code></p>

<pre><code>  /// &lt;summary&gt;
    /// custom web application factory for testing.
    /// &lt;/summary&gt;
    public class LwtTestWebApplicationFactory : WebApplicationFactory&lt;Startup&gt;
    {
        ....

        /// &lt;inheritdoc /&gt;
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureTestServices(
                services =&gt;
                {
                    // Replace database seeder.
                    ServiceDescriptor databaseSeederDescriptor =
                        services.Single(s =&gt; s.ServiceType == typeof(IDatabaseSeeder));

                    services.Remove(databaseSeederDescriptor);

                    var mock = new Mock&lt;IDatabaseSeeder&gt;();
                    mock.Setup(s =&gt; s.SeedData())
                        .Returns(Task.CompletedTask);
                    services.AddTransient(resolver =&gt; mock.Object);

                    // Replace index creator.
                    ServiceDescriptor indexCreatorDescriptor =
                        services.Single(s =&gt; s.ServiceType == typeof(IIndexCreator));

                    services.Remove(indexCreatorDescriptor);

                    var indexCreatorMock = new Mock&lt;IIndexCreator&gt;();
                    indexCreatorMock.Setup(s =&gt; s.CreateIndexesAsync())
                        .Returns(Task.CompletedTask);
                    services.AddTransient(resolver =&gt; indexCreatorMock.Object);

                    // Remove the app's ApplicationDbContext registration.
                    ServiceDescriptor descriptor = services.SingleOrDefault(
                        d =&gt; d.ServiceType == typeof(DbContextOptions&lt;IdentityDbContext&gt;));

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

                    // Add ApplicationDbContext using an in-memory database for testing.
                    services.AddDbContext&lt;IdentityDbContext&gt;(
                        (options, context) =&gt; { context.UseInMemoryDatabase(""InMemoryDbForTesting""); });

                    ServiceDescriptor appSettingDescriptor = services.SingleOrDefault(
                        d =&gt; d.ServiceType == typeof(AppSettings));

                    if (appSettingDescriptor != null)
                    {
                        var appSetting = (AppSettings)appSettingDescriptor.ImplementationInstance;
                        services.Remove(appSettingDescriptor);
                        services.AddSingleton(
                            new AppSettings
                            {
                                MongoDatabase = appSetting.MongoDatabase,
                                Secret = appSetting.Secret,
                                MongoConnectionString = this.mongoDbRunner.ConnectionString,
                            });
                    }
                });
        }

        .....
    }
}
</code></pre>

<p>What i tried.</p>

<pre><code>    using (var factory = new LwtTestWebApplicationFactory())
    using (WebApplicationFactory&lt;Startup&gt; seedEnabledFactory = factory.WithWebHostBuilder(
                builder =&gt;
                {
                    builder.ConfigureTestServices(
                        services =&gt;
                        {
                            // Replace database seeder.
                            ServiceDescriptor databaseSeederDescriptor =
                                services.Single(s =&gt; s.ServiceType == typeof(IDatabaseSeeder));

                            services.Remove(databaseSeederDescriptor);

                            services.AddTransient&lt;IDatabaseSeeder, DatabaseSeeder&gt;();

                            // Replace index creator.
                            ServiceDescriptor indexCreatorDescriptor =
                                services.Single(s =&gt; s.ServiceType == typeof(IIndexCreator));

                            services.Remove(indexCreatorDescriptor);

                            services.AddTransient&lt;IIndexCreator, MongoDbIndexCreator&gt;();
                        });
                }))
</code></pre>
",https://stackoverflow.com/questions/58576638/how-to-override-services-that-mocked-using-iwebhostbuilder-configuretestservices,"['c#', 'asp.net-core', '.net-core', 'integration-testing']",1190,False,3,1
How to do integration testing on an API wrapper,"<p>I have an api wrapper that is just your basic controller/service that is using a third party client to actually handle requests. Is it possible to mock this for integration testing somehow?</p>

<pre><code>Clientservice clientService = new ClientService(urlHere);
clientService.findBooks(); //Handles request within, my wrapper does not directly call endpoints
</code></pre>

<p>What's the proper way to integrate test this? Just call my controller with rest and mock the clientService return? Unsure if it's possible to do this another way.</p>

<p>Edit: changed title and info to try and make this clearer. </p>
",https://stackoverflow.com/questions/58249899/how-to-do-integration-testing-on-an-api-wrapper,"['java', 'integration-testing', 'wiremock']",180,False,0,1
Detect rejected promises from Express route handlers during testing,"<p>When an Express async route handler throws an error (which it does not catch), then it will not be passed to <code>next()</code>, so will not end up in an error handling middleware.</p>

<p>I want to simulate that in a test:</p>

<pre><code>import * as request from ""supertest"";

const router = express.Router();
router.route(""/boom"").post(async (req, res, next) =&gt; { throw new Error(); });
router.use((err, req, res, next) =&gt; { res.status(500).json(""caught!""); });

const app = express();
app.use(router);

test(""uncaught error""), done =&gt; {
  request(app)
    .post(""/boom"")
    .end((err, res) =&gt; {               // never gets here
      expect(err).toBeTruthy();
      expect(res.status).not.toBe(500);
      expect(res.body).not.toBe(""caught!"");
      done();
    });
});
</code></pre>

<p>However even in the test, the error is uncaught, and times out. So the test fails.</p>

<p>How can I detect this?</p>

<hr>

<p><em>(BTW: supertest does integration testing... can I do it without supertest, just a Jest unit test?)</em></p>
",https://stackoverflow.com/questions/54761776/detect-rejected-promises-from-express-route-handlers-during-testing,"['node.js', 'express', 'jestjs', 'supertest']",168,False,2,0
How to clean up database with JdbcTemplate after all junit 5 tests are finished?,"<p>I'm writting integration tests and I need to clean up database after one suite test (via @TestMethodOrder) is finished, either successfuly or with failure. </p>

<p>Obviously first thing come to mind was to use method with @AfterAll annotation, but it needs to be static. I'm using @Autowired JdbcTemplate, which cannot be static. Actually after few searches I found out, that no database connection should be static.</p>

<p>Is there any good solution for integration testing optionally with suits?</p>
",https://stackoverflow.com/questions/55454877/how-to-clean-up-database-with-jdbctemplate-after-all-junit-5-tests-are-finished,"['junit', 'jdbctemplate', 'spring-boot-test']",282,False,1,0
Message requeued after AmqpRejectAndDontRequeueException with Qpid,"<p>I am using rabbitMQ for production and in-memory Qpid for integration testing in my Spring boot app. But I encountered a problem when AmqpRejectAndDontRequeueException is thrown - Qpid requeues the message instead of discarding it. With rabbitMQ it is working fine. </p>

<p>I am using gradle with dependencies (used older version but after upgrade problem still persists):</p>

<pre><code>    testCompile(""org.apache.qpid:qpid-broker-core:7.1.5"")
    testCompile(""org.apache.qpid:qpid-broker-plugins-memory-store:7.1.5"")
    testCompile(""org.apache.qpid:qpid-broker-plugins-amqp-0-8-protocol:7.1.5""):
</code></pre>

<p>My qpid config:</p>

<pre><code>{
  ""name"": ""Embedded Broker"",
  ""modelVersion"": ""6.0"", //not working for 7.0 either
  ""authenticationproviders"" : [ {
    ""name"": ""password"",
    ""type"": ""Plain"",
    ""secureOnlyMechanisms"": [],
    ""users"": [{""name"": ""xxx"", ""password"": ""xxx"", ""type"": ""managed""}]
  } ],
  ""ports"" : [  {
    ""name"" : ""AMQP"",
    ""port"" : ""5672"",
    ""protocols"": [ ""AMQP_0_9_1"" ],
    ""authenticationProvider"" : ""password"",
    ""virtualhostaliases"" : [ {
      ""name"" : ""nameAlias"",
      ""type"" : ""nameAlias""
    }, {
      ""name"" : ""defaultAlias"",
      ""type"" : ""defaultAlias""
    }, {
      ""name"" : ""hostnameAlias"",
      ""type"" : ""hostnameAlias""
    } ]
  }],
  ""virtualhostnodes"" : [ {
    ""name"" : ""default"",
    ""type"" : ""Memory"",
    ""defaultVirtualHostNode"" : ""true"",
    ""virtualHostInitialConfiguration"" : ""{\""type\"": \""Memory\""}""
  }]
}
</code></pre>

<p>Issue seems similar to: <a href=""https://stackoverflow.com/questions/57873395/why-does-basicreject-does-not-work-with-apache-qpid"">Why does basicReject does not work with Apache Qpid?</a>
Is this a known problem? </p>
",https://stackoverflow.com/questions/58335445/message-requeued-after-amqprejectanddontrequeueexception-with-qpid,"['amqp', 'spring-amqp', 'qpid']",133,False,1,0
Testing Entity Framework Core Migrations,"<p>How do you use unit/integration testing to ensure that a code-first migration works correctly on a populated previous-version database, including any additional code to map data from one column or table to another?</p>

<p>I found some previous answers that used classes in the <code>System.Data.Entity</code> namespace, but it appears these have become obsolete with Entity Framework Core and manual control of migrations is not possible?</p>

<p>I found a solution for myself which I will post, but I welcome other, better solutions.</p>
",https://stackoverflow.com/questions/58100997/testing-entity-framework-core-migrations,"['c#', 'unit-testing', 'entity-framework-core', 'mstest']",2080,True,4,1
How to retrieve SlingHttpServletRequest from ResourceResolver,"<p>I would like to retrieve the request used to resolve the resources I retrieve from the ResourceResolver.</p>

<p>I am performing integration testing using <a href=""https://sling.apache.org/documentation/bundles/org-apache-sling-junit-bundles.html#the-teleporterrule"" rel=""nofollow noreferrer"">Teleporter Rule</a> And can resolve the resource but can't find its corresponding request.</p>

<pre><code>@Rule
    public final TeleporterRule teleporter = TeleporterRule.forClass(getClass(), ""Launchpad"");

    @Test
    public void testPage() throws LoginException {
        ResourceResolverFactory resourceResolverFactory = teleporter.getService(ResourceResolverFactory.class);
        ResourceResolver resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
        Resource resource = resourceResolver.getResource(""/content/test/en"");
        PageModel page = resource.adaptTo(PageModel.class);
    }
</code></pre>

<p>I would like to be able to retrieve the request like I can with my unit tests using SlingContext.</p>

<pre><code>SlingContextImpl slingContext = new SlingContextImpl();
slingContext.currentResource(""/content/test/en"");
slingContext.request()
</code></pre>

<p>I would like to retrieve the request like I can with my unit tests and properly test my sling models that inject the request.</p>
",https://stackoverflow.com/questions/57510618/how-to-retrieve-slinghttpservletrequest-from-resourceresolver,"['integration-testing', 'aem', 'sling']",103,False,1,1
com.sun.xml.messaging.saaj.SOAPExceptionImpl: Invalid Content-Type:text/plain. Is this an error message instead of a SOAP response?,"<p>Hello I am trying to create a dirty test for my soap integration test. I just got SSL working on my spring boot app and I wanted to see if it will hit my soap end point.</p>

<p>When I run man verify on my integration test I get this error:</p>

<pre><code>com.sun.xml.messaging.saaj.SOAPExceptionImpl: Invalid Content-Type:text/plain. Is this an error message instead of a SOAP response?
</code></pre>

<p>Here is my test code :</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = {EndPointTestConfiguration.class
})


public class SoapIT {
private static ApplicationContext context;
    @BeforeClass
    static public void  setup(){
        SpringApplication springApplication = new SpringApplicationBuilder()           
                .sources(MockServerApp.class)
                .build();
        context = springApplication.run();
    }


    @Autowired
    private String studyDetailDemo;
    @Test
    public void soapTest() throws ClientProtocolException, IOException {
        String result = Request.Post(""https://127.0.0.1:28443/nulogix/ws/billingtool"")
                .connectTimeout(2000)
                .socketTimeout(2000)
                .bodyString(studyDetailDemo, ContentType.TEXT_PLAIN)
                .execute().returnContent().asString();

    }
}
</code></pre>

<p>I am kind of new to integration testing and have no idea what this error means</p>

<p>Thank you for any help</p>
",https://stackoverflow.com/questions/57665696/com-sun-xml-messaging-saaj-soapexceptionimpl-invalid-content-typetext-plain-i,"['java', 'spring-boot', 'soap', 'integration-testing']",185,False,0,1
IntelliJ creating Integration Testing Environment,"<p>I'm creating another source set for integration testing, but every time my gradle rebuilds it turns my main test root folder back to source root folder (blue), when I want it to be test root folder (green). What do I need to configure in my build.gradle so that this is fixed?</p>

<pre><code>sourceSets {
    integration {
        compileClasspath += sourceSets.main.output
        runtimeClasspath += sourceSets.main.output
    }
}

configurations {
    intTestRuntimeOnly.extendsFrom runtimeOnly
    intTestImplementation.extendsFrom testImplementation
}

dependencies {
    intTestImplementation 'junit:junit:4.12'
}
task integrationTest(type: Test) {
    description = 'Runs integration tests.'
    group = 'verification'

    testClassesDirs = sourceSets.integration.output.classesDirs
    classpath = sourceSets.integration.runtimeClasspath
    shouldRunAfter test
}

check.dependsOn integrationTest
</code></pre>

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

<p>Everytime I manually change it to testsources root and rebuild it just turns back to blue. </p>

<p>I followed this documentation <a href=""https://docs.gradle.org/current/userguide/java_testing.html#sec:configuring_java_integration_tests"" rel=""nofollow noreferrer"">https://docs.gradle.org/current/userguide/java_testing.html#sec:configuring_java_integration_tests</a></p>

<p>Thanks</p>
",https://stackoverflow.com/questions/59221824/intellij-creating-integration-testing-environment,"['java', 'gradle', 'intellij-idea']",92,False,0,0
Output logs to Xunit using Serilog Static Logger,"<p>I use serilog in my projects with the static logger approach - it's nice and easy to be able to call Log.X on my class libraries rather than injecting a logger class everywhere.</p>

<p>However when it comes to unit/integration testing, if a test has failed it would be <strong>hugely</strong> beneficial to see the error logs from the class libraries (moreso for integration tests). </p>

<p>Because I am not injecting an ILogger into my classes (due to use of static logger), I can't create a mock test logger that writes output to the test logs. </p>

<p>Has anyone managed to output messages to XUnit using the Serilog global (static) logger?</p>
",https://stackoverflow.com/questions/58913741/output-logs-to-xunit-using-serilog-static-logger,"['c#', 'unit-testing', 'logging', 'xunit', 'serilog']",7556,True,19,2
How to use settings from integration testing project in the Startup class of api project?,"<p>I'm trying to write integration tests for web api, I have two appsettings.json files one for api project and other for integration tests. I want to use the values(azure storage connection strings) from integration testing project in Startup class of web api.</p>

<p>I have tried creating CustomWebApplicatonFactory it didn't work since the Startup class of web api gets settings like shown below.</p>

<pre><code>//Configure services method in Startup class
public virtual void ConfigureServices(IServiceCollection services)
{
      var settings = ConfigurationProvider.GetConfiguration();
      services.TryAddSingleton(settings);
      services.AddHttpClient();
      var azureTableStorageConnectionString = 
      settings[""AzureMainStoreConnectionStringSecretName""];

     //Other Startup related code
}
</code></pre>

<p>I want to change the value of ""azureTableStorageConnectionString"" from my integration test project. Help and suggestions are much appreciated.</p>
",https://stackoverflow.com/questions/58335095/how-to-use-settings-from-integration-testing-project-in-the-startup-class-of-api,"['c#', 'asp.net-core', 'asp.net-web-api', 'integration-testing']",493,True,2,1
Test service method that has @PreAuthorize with JUnit,"<p>In Spring Boot 1.4.1, I want to do unit testing (not integration testing) on a service method that has restricted access with @PreAuthorize.</p>

<p>The problem is the @PreAuthorize doesn't seem to be checked when launching the test solo from Eclipse (haven't try with mvn test yet).</p>

<p>Then, if I miraculously manage to run the test correctly, I will try to work with the StudyService interface, not the impl.</p>

<p>Here is my test class :</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class TestMethodSecurity {

    private static final Long STUDY_ID = 1L;

    @Mock
    private StudyRepository studyRepository;

    @InjectMocks
    private StudyServiceImpl studyService;


    @Before
    public void setup() {
        given(studyRepository.findOne(STUDY_ID)).willReturn(ModelsUtil.createStudy());
    }


    @Test
    public void findByIdWithoutAccessRightTest() {
        Study study = studyService.findById(STUDY_ID);
    }
}
</code></pre>

<p>This is the service :</p>

<pre><code>@Service
public class StudyServiceImpl implements StudyService {


    @Autowired
    private StudyRepository studyRepository;


    @Override
    @PreAuthorize(""hasAnyRole('DOES NOT EVENT CHECK SYNTAX"")
    public Study findById(final Long id) {
        return studyRepository.findOne(id);
    }

}
</code></pre>

<p>The test succeed, which is a fail.</p>
",https://stackoverflow.com/questions/54424892/test-service-method-that-has-preauthorize-with-junit,"['java', 'spring', 'spring-boot', 'junit', 'spring-security']",5240,True,5,3
What is the preferred approach to EF Core migrations in Azure DevOps?,"<p>I'm looking for a workflow to enable local migrations with EF Core (on a developer instance) and then pushing those migrations incrementally through the process:</p>

<ul>
<li>CI/CD Integration for development </li>
<li>Promoting to staging/integration testing</li>
<li>Promoting to UAT &amp; warmup</li>
<li>Deploy to production</li>
</ul>

<p>Assuming I have at least 3 databases above, how can I isolate and track the pending changes without risking corruption in the event I may need to roll back a change at any step of the process?</p>
",https://stackoverflow.com/questions/54930046/what-is-the-preferred-approach-to-ef-core-migrations-in-azure-devops,"['asp.net-core', 'azure-devops', 'ef-core-2.2']",45,False,2,0
Run shell script after keycloak http endpoint is ready,"<p>Simplified scenario:</p>

<p>Dockerfile:</p>

<pre><code>FROM jboss/keycloak
COPY ./initialize.sh /
RUN chmod +x initialize.sh
</code></pre>

<p>initialize.sh:</p>

<pre><code>#!/bin/bash
curl http://localhost:8080/auth
</code></pre>

<p>What I want to achieve is the following:</p>

<ul>
<li>start keycloak container</li>
<li>execute the <code>initialize.sh</code> script after an <code>/auth</code> 
http endpoint inside the container is ready</li>
<li>use keycloak-cli to add test users and roles</li>
</ul>

<p>The motivation behind is to create a keycloak container to be used together with <a href=""https://www.testcontainers.org/"" rel=""nofollow noreferrer"">https://www.testcontainers.org/</a> for integration testing.</p>

<p>The official <code>jboss/keycloak</code> image has a <code>KEYCLOAK_IMPORT</code> environment variable which enables realm import, but it is not possible to import users and roles which are needed for the integration tests.</p>
",https://stackoverflow.com/questions/57059982/run-shell-script-after-keycloak-http-endpoint-is-ready,"['docker', 'dockerfile', 'keycloak']",2290,True,1,2
How to mock NATS microservices?,"<p>I want to test microservices. Microservices communicate via NATS. I see several test levels for it:
Unit testing - one container format;
Integration testing - several container formats;
e2e via GUI.</p>

<p>I can't find a solution for the first test level. How can I isolate  a container format that communicates with others via NATS protocol? I tried doing it based on <a href=""https://www.npmjs.com/package/mountebank"" rel=""nofollow noreferrer"">mountebank</a> via TCP, but that doesn't seem to be right.</p>

<p>How do you test your microservices in NATS? Does it make any sense to do it via TCP?</p>
",https://stackoverflow.com/questions/58964556/how-to-mock-nats-microservices,"['node.js', 'testing', 'automated-tests', 'nats.io']",605,False,4,0
Angular integration testing: how to specify the target on a MouseEvent,"<p>I am trying to invoke a click event in my integration testing by using ""triggerEventHandler"" on one of the HTML elements. I expected that the ""target"" property of the event to be set by ""triggerEventHandler"". That is not happening. When I execute the test, the following error is logged in console: ""<em>Cannot read property 'tagName' of null</em>"" and this happens when I try to get the tagName of the target element.</p>

<p>How should I implement this test?</p>

<p>VIEW</p>

<pre><code>&lt;h1 class=""h1-class"" (click)=""click($event)"" (contextmenu)=""rightClick($event)""&gt;H1&lt;/h1&gt;
&lt;h2 class=""h2-class"" (click)=""click($event)"" (contextmenu)=""rightClick($event)""&gt;H2&lt;/h2&gt;
</code></pre>

<p>COMPONENT</p>

<pre><code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'biq-dbg',
  templateUrl: './biq-dbg.component.html',
  styleUrls: ['./biq-dbg.component.less']
})

export class BiqDbgComponent implements OnInit {

  constructor() {
  }

  ngOnInit() {
  }

  click(event: MouseEvent) {
    console.log(event);
    let targetElement = event.target as HTMLElement;
    if (targetElement.tagName.toLocaleLowerCase() == ""h1"")
      console.log(""H1 was clicked"");
    if (targetElement.tagName.toLocaleLowerCase() == ""h2"")
      console.log(""H2 was clicked"");
  }

  rightClick(event: MouseEvent) {
    console.log(event);
    let targetElement = event.target as HTMLElement;
    if (targetElement.tagName.toLocaleLowerCase() == ""h1"")
      console.log(""H1 was right-clicked"");
    if (targetElement.tagName.toLocaleLowerCase() == ""h2"")
      console.log(""H2 was right-clicked"");
  }
}
</code></pre>

<p>SPEC</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'

import { BiqDbgComponent } from './biq-dbg.component';

fdescribe('BiqDbgComponent', () =&gt; {
  let component: BiqDbgComponent;
  let fixture: ComponentFixture&lt;BiqDbgComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ BiqDbgComponent ]
    })
    .compileComponents();
  }));

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

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

  it('h1 should react to click', () =&gt; {
    let h1 = fixture.debugElement.query(By.css("".h1-class""));
    let mouseEvent: MouseEvent = new MouseEvent(""click"", { clientX: 10, clientY: 20, button: 0});

    h1.triggerEventHandler(""click"", mouseEvent);
    fixture.detectChanges();
  })

  fit('h1 should react to right-click', () =&gt; {
    let h1 = fixture.debugElement.query(By.css("".h1-class""));
    let mouseEvent: MouseEvent = new MouseEvent(""contextmenu"", { clientX: 10, clientY: 20, button: 2});

    h1.triggerEventHandler(""contextmenu"", mouseEvent);
    fixture.detectChanges();
  })
});
</code></pre>
",https://stackoverflow.com/questions/55911516/angular-integration-testing-how-to-specify-the-target-on-a-mouseevent,"['angular', 'angular-test']",791,True,1,1
How to get redux store to update dom of react-testing-library,"<p>I am using react-testing-library to mount a react-redux connected component with my redux-store:</p>

<pre><code>let comp = reduxRender(&lt;ConnectedComponent /&gt;, {store});
</code></pre>

<p>reduxRender is a helper function that basically does this:</p>

<pre><code>return {
    ...render(&lt;Provider store={store}&gt;{ui}&lt;/Provider&gt;),
    store
}
</code></pre>

<p>I then dispatch an action to my store e.g.:</p>

<pre><code>store.dispatch({type:'someAction'});
</code></pre>

<p>So my store updates correctly, however, the dom created by react-testing-library->render  does not update.  Does anyone know how to get it to update?
My goal here is obviously integration testing, I already have unit tests for each individual part of this lot.</p>
",https://stackoverflow.com/questions/57759644/how-to-get-redux-store-to-update-dom-of-react-testing-library,"['javascript', 'redux', 'react-redux', 'jestjs', 'react-testing-library']",1240,True,0,1
Add mock fetcher instead of real class using Carter framework,"<p>Im doing integration testing  on my rest web api.
I have the following setup :</p>

<pre><code>public ItemsControllerTests()
        {
            this.itemFetcher = new Mock&lt;IItemFetcher&gt;();
            this.itemFetcher.Setup(sp =&gt; sp.GetItems(It.IsAny&lt;string&gt;()))
            .Returns(Task.FromResult(
                (200, new Response&lt;ICollection&lt;Item&gt;&gt;()
                {
                    Data = new List&lt;Item&gt;()
                    {
                        new Item()
                        {
                            Id = 42,
                            Artwork = ""http://cdn.fake.com/fake.png"",
                            Category = new Category()
                            {
                                Id = 2,
                                Name = ""musical""
                            },
                            Name = ""Awesome bagpipe""
                        }
                    },
                    Error = null
                })
                ));
            client = new TestServer(new WebHostBuilder()
                    .ConfigureServices(services =&gt;
                    {
                        //Middlewares
                        services.AddSingleton&lt;IItemFetcher, ItemFetcher&gt;();

                        services.AddCarter();
                    })
                    .Configure(app =&gt; { app.UseCarter(); })
                ).CreateClient();
        }

        [Fact]
        public async void GetItemsOK()
        {
            response = client.GetAsync(""/items"").GetAwaiter().GetResult();
            var content = await response.Content.ReadAsStringAsync();

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
    }
</code></pre>

<p>which works perfectly fine. the problem is its actually doing a REAL request as its using the real class. So my doubt is in this line :</p>

<pre><code>services.AddSingleton&lt;IItemFetcher, ItemFetcher&gt;();
</code></pre>

<p>How can I use my mock object <strong>this.itemFetcher = new Mock();</strong> instead of the real one. If I try this :</p>

<pre><code>services.AddSingleton&lt;IItemFetcher, itemFetcher&gt;();
</code></pre>

<p>It fails as I am actually using an instance of a class instead of a class.</p>

<p>How can I overcome this?</p>
",https://stackoverflow.com/questions/58099968/add-mock-fetcher-instead-of-real-class-using-carter-framework,"['c#', 'unit-testing', 'mocking', 'carter']",35,False,0,1
RestTemplate exception no converters found while testing a Spring boot Application,"<p>I am new to testing world of spring boot application.
I want to do an integration testing on my Spring boot application. But i am getting following exception.</p>

<pre><code>org.springframework.web.client.HttpClientErrorException$BadRequest: 400 null
</code></pre>

<p>I am adding an employee and department into the in-memory database with bi-directional relationship. </p>

<pre><code>public void testPostEmployee() throws Exception
            {       
        System.out.println(""Inside Post Employee method"");

        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        EmployeeTestDTO employeeTestDTO = new EmployeeTestDTO();
        DepartmentTest departmentTest = new DepartmentTest(1,""Sales"");
        employeeTestDTO.setName(""ABC"");
        employeeTestDTO.setAge(20);
        employeeTestDTO.setSalary(1200.1);
        employeeTestDTO.setDepartmentTest(departmentTest);

        ObjectMapper objectMapper = new ObjectMapper();

        String data = objectMapper.writeValueAsString(employeeTestDTO);
        System.out.println(data);

        HttpEntity&lt;String&gt; httpEntity = new HttpEntity&lt;String&gt;(data,httpHeaders);

        ResponseEntity&lt;?&gt; postResponse = restTemplate.postForEntity(createURLWithPort(""/employee""), 
                httpEntity,String.class);

        Assert.assertEquals(201, postResponse.getStatusCodeValue());            

}
</code></pre>

<p>This is my new edit. As per previously stated suggestion i tried to implement all of them but neither of them succeded. It gives the bad request 400 null exception. Please suggest me how to solve it </p>
",https://stackoverflow.com/questions/58072836/resttemplate-exception-no-converters-found-while-testing-a-spring-boot-applicati,"['java', 'spring', 'spring-boot', 'junit', 'mockito']",175,True,0,1
Should repositories in Spring Boot applications be tested directly?,"<p>Not sure if this will be considered a ""legitimate question"" or ""purely opinion based"", but is there a ""best practice"" with regards to directly testing a repository in a Spring Boot application? Or, should any integration testing simply target the associated service?</p>

<p>The reasoning for the question is simply the fact that, for the most part, a repository in a Spring Boot application contains no project-generated code. At best, it contains project-defined method signatures which Spring generates implementations for (assuming correct naming conventions).</p>

<p>Thanks...</p>
",https://stackoverflow.com/questions/54889813/should-repositories-in-spring-boot-applications-be-tested-directly,"['spring', 'spring-boot', 'integration-testing', 'spring-repositories']",467,True,3,3
Integration testing between web application and WebAPI,"<p>I am using <code>WebApplicationFactory&lt;TStartup&gt;</code> for integration testing  of a .NET Core 3.0 web application.<br>
It works when it  need to test just one web application.   </p>

<p>But what if  web application need to send request to WebAPI application. I need somehow to instantiate both <code>WebApplicationFactory&lt;Web.Startup&gt;</code> and <code>WebApplicationFactory&lt;Api.Startup&gt;</code>.   </p>

<p>I tried different alternatives with no luck. 
Can anybody with experience of similar task point a right way to me.</p>

<p>P.S. Inside web application there is injected internal <code>HttpClient</code> that used internally in Controllers to send requests to API:</p>

<pre class=""lang-cs prettyprint-override""><code>services.AddHttpClient&lt;IInternalApiClient, InternalApiClient&gt;();
</code></pre>
",https://stackoverflow.com/questions/58486057/integration-testing-between-web-application-and-webapi,"['c#', 'asp.net-core', 'integration-testing', 'asp.net-core-webapi']",304,False,0,1
Android Espresso testing SwipeRefreshLayout OnRefresh not been triggered on swipeDown,"<p>I'm trying to write simple test for pull to refresh as a part of integration testing. I'm using the newest androidX testing components and Robolectric. I'm testing isolated fragment in which one I'm injecting mocked presenter.</p>

<p>XML layout part</p>

<pre><code>&lt;androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id=""@+id/refreshLayout""
        android:layout_width=""match_parent""
        android:layout_height=""match_parent""&gt;

        &lt;androidx.recyclerview.widget.RecyclerView
            android:id=""@+id/recyclerTasks""
            android:layout_width=""match_parent""
            android:layout_height=""match_parent""
            android:orientation=""vertical""
            app:layoutManager=""androidx.recyclerview.widget.LinearLayoutManager""/&gt;
&lt;/androidx.swiperefreshlayout.widget.SwipeRefreshLayout&gt;
</code></pre>

<p>Fragment part</p>

<pre><code>binding.refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                presenter.onRefresh();
            }
        });
</code></pre>

<p>Test:</p>

<pre><code>onView(withId(R.id.refreshLayout)).perform(swipeDown());
verify(presenter).onRefresh();
</code></pre>

<p>but test doesn't pass, message: </p>

<blockquote>
  <p>Wanted but not invoked: presenter.onRefresh();</p>
</blockquote>

<p>The app works perfectly fine and pull to refresh calls presenter.onRefresh(). I did also debugging of the test and setOnRefreshListener been called and it's not a null. If I do testing with custom matcher to check the status of SwipeRefreshLayout test passes.</p>

<pre><code>onView(withId(R.id.refreshLayout)).check(matches(isRefreshing()));
</code></pre>
",https://stackoverflow.com/questions/55517269/android-espresso-testing-swiperefreshlayout-onrefresh-not-been-triggered-on-swip,"['android', 'integration-testing', 'android-espresso', 'robolectric', 'swiperefreshlayout']",1634,True,5,2
How to test nested object with Chai and Mocha?,"<p>I'm using mocha, chai, and chai-http to do integration testing for my Node.js and Express app. I'm trying to test out does my login route has token or not. I tried different asserts to check does token exist inside of data object but none of them work.</p>

<p>Data from Postman looks like this:</p>

<pre><code>{
  ""data"": {
    ""token"": ""eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NiwiaWF0IjoxNTYzODczMzE3LCJleHAiOjE1NjM5NTk3MTd9.bM1RFem2pnlEqjTWGhg-s4Am1PjGNRUS_8x5Dq8J6lI"",
    ""user"": {
      ""id"": 6,
      ""firstName"": ""John"",
      ""lastName"": ""Doe"",
      ""email"": ""test@test.com"",
      ""createdAt"": ""2019-07-23T06:38:11.358Z"",
      ""updatedAt"": ""2019-07-23T06:38:11.358Z""
    }
  },
  ""hasErrors"": false,
  ""errors"": []
}
</code></pre>

<p>This is my actual test where I'm trying to check does res.body has nested token inside of data object. </p>

<pre><code>/* Login Test */
let credentials = {
  'email': 'adnan@test.com',
  'password': 'test'
};

describe(""POST /user-sessions"", function() {
  it(""should login user"", function(done) {
    chai.request('http://localhost:3000')
      .post(""/user-sessions"")
      .send(credentials) 
      .end((err, res) =&gt; {
        res.should.have.status(200);

        res.body.should.have.nested.property('data.token');
        done();
      })
  });
})
</code></pre>

<p>I'm getting  Uncaught AssertionError: expected { Object (data, hasErrors, ...) } to have property 'data.token'</p>
",https://stackoverflow.com/questions/57160926/how-to-test-nested-object-with-chai-and-mocha,"['mocha.js', 'chai', 'chai-http']",4022,True,2,2
Ava separate integration and unit tests,"<p>I'd like to use 'ava' tool for both unit and integration testing.  But I can't figure out what's the best way to separate those tests.  Unit tests should run before the code deployed into test environment, and integration tests need to run after the code has been deployed to the test server.</p>

<p>My challenge is that 'ava' reads it's configuration from 'ava' section of <code>package.json</code>.  Not sure how to tell it to use different sets of test sources depending on which stage of deployment it is.</p>
",https://stackoverflow.com/questions/56642973/ava-separate-integration-and-unit-tests,"['unit-testing', 'npm', 'integration-testing', 'package.json', 'ava']",321,True,2,1
spring Kafka integration test listener not working,"<p>I'm trying integration testing using <code>spring-boot</code> and spring embedded Kafka. I'm able to produce message to spring embedded Kafka server but instead of test listener the listener in service class is trying to consume the records and </p>

<p><strong>KafkaProducerConfigTest</strong> Config class with all beans </p>

<pre><code>@EnableKafka
@TestConfiguration
public class KafkaProducerConfigTest {

@Bean
public EmbeddedKafkaBroker embeddedKafkaBroker() {
    return new EmbeddedKafkaBroker(1,false,2,""test-events"");
}

@Bean
public ProducerFactory&lt;String, Object&gt; producerFactory() {
    Map&lt;String, Object&gt; props = new HashMap&lt;&gt;();
    props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, embeddedKafkaBroker().getBrokersAsString());
    props.put(ProducerConfig.RETRIES_CONFIG, 0);
    props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
    return new DefaultKafkaProducerFactory&lt;&gt;(props);
}

@Bean
public KafkaTemplate&lt;String, Object&gt; kafkaTemplate() {
    KafkaTemplate&lt;String, Object&gt; kafkaTemplate = new KafkaTemplate&lt;&gt;(producerFactory());
    return kafkaTemplate;
   }

@Bean(""consumerFactory"")
 public ConsumerFactory&lt;String, Object&gt; createConsumerFactory() {
     Map&lt;String, Object&gt; props = new HashMap&lt;&gt;();
     props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, embeddedKafkaBroker().getBrokersAsString());
     props.put(ConsumerConfig.GROUP_ID_CONFIG, ""group1"");
     props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
     return new DefaultKafkaConsumerFactory&lt;&gt;(props, new StringDeserializer(), new JsonDeserializer&lt;&gt;(Object.class,false));
 }

@Bean(""kafkaListenerContainerFactory"")
 public ConcurrentKafkaListenerContainerFactory&lt;String, Object&gt; kafkaListenerContainerFactory() {
     ConcurrentKafkaListenerContainerFactory&lt;String, Object&gt; factory = new ConcurrentKafkaListenerContainerFactory&lt;&gt;();
     factory.setConsumerFactory(createConsumerFactory());
     factory.setBatchListener(true);
     factory.setMessageConverter(new BatchMessagingMessageConverter(converter()));
     factory.getContainerProperties().setAckMode(AckMode.BATCH);
     return factory;
 }

@Bean
public StringJsonMessageConverter converter() {
    return new StringJsonMessageConverter();
}

@Bean
public Listener listener() {
    return new Listener();
}

public class Listener {
    public final CountDownLatch latch = new CountDownLatch(1);

    @Getter
    public List&lt;Professor&gt; list;

    @KafkaListener(topics = ""test-events"", containerFactory = ""kafkaListenerContainerFactory"")
    public void listen1(List&lt;Professor&gt; foo) {

        list=foo;
        this.latch.countDown();
      }
   }

 }
</code></pre>

<p><strong>KafkaProducerServiceTest</strong> Service test class, but here listener is not consuming any data and I know this test will fail because this is not correct way to do that</p>

<pre><code>@EnableKafka
@SpringBootTest(classes = { KafkaProducerConfigTest.class })
@RunWith(SpringRunner.class)
public class KafkaProducerServiceTest {

@Autowired
private KafkaConsumerService kafkaConsumerService;

@Autowired
private Listener listener;

@Test
public void testReceive() throws Exception {
    kafkaConsumerService.professor(Arrays.asList(new Professor(""Ajay"", new Department(""social"", 1234))));
    System.out.println(""The professor object is sent to kafka -----------------------------------"");
    listener.latch.await();
    System.out.println(listener.getList());

    }

}
</code></pre>

<p><strong>Error</strong></p>

<pre><code>2019-02-19 15:18:32.620 ERROR 22387 --- [ntainer#1-0-C-1] o.s.k.listener.BatchLoggingErrorHandler  : Error while processing:
ConsumerRecord(topic = test-events, partition = 1, offset = 0, CreateTime = 1550611112583, serialized key size = 9, serialized value size = 64, headers = RecordHeaders(headers = [], isReadOnly = false), key = professor, value = {name=Ajay, department={deptName=social, deptId=1234}})

 java.lang.IllegalStateException: Only String or byte[] supported
at org.springframework.kafka.support.converter.StringJsonMessageConverter.extractAndConvertValue(StringJsonMessageConverter.java:140) ~[spring-kafka-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.kafka.support.converter.MessagingMessageConverter.toMessage(MessagingMessageConverter.java:134) ~[spring-kafka-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.kafka.support.converter.BatchMessagingMessageConverter.convert(BatchMessagingMessageConverter.java:217) ~[spring-kafka-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.kafka.support.converter.BatchMessagingMessageConverter.toMessage(BatchMessagingMessageConverter.java:165) ~[spring-kafka-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.kafka.listener.adapter.BatchMessagingMessageListenerAdapter.toMessagingMessage(BatchMessagingMessageListenerAdapter.java:174) ~[spring-kafka-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.kafka.listener.adapter.BatchMessagingMessageListenerAdapter.onMessage(BatchMessagingMessageListenerAdapter.java:129) ~[spring-kafka-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.kafka.listener.adapter.BatchMessagingMessageListenerAdapter.onMessage(BatchMessagingMessageListenerAdapter.java:59) ~[spring-kafka-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeBatchListener(KafkaMessageListenerContainer.java:984) [spring-kafka-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeBatchListener(KafkaMessageListenerContainer.java:917) [spring-kafka-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeListener(KafkaMessageListenerContainer.java:900) [spring-kafka-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:753) [spring-kafka-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_191]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_191]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_191]
</code></pre>

<p>Updated based on @Gray Russel sir answer but I still have an issue</p>
",https://stackoverflow.com/questions/54773746/spring-kafka-integration-test-listener-not-working,"['java', 'spring-boot', 'spring-kafka', 'spring-kafka-test']",5781,True,1,2
Unable to mock dependency with SpringBoot and Spock Framework,"<p>I'm using SpringBoot 1.5.9, Groovy 2.4.13, Spock-core-1.2-groovy-2.4 and Spock-Spring-1.2-groovy-2.4.
I tried following both documentation and a few tutorials on internet:</p>

<ul>
<li><a href=""http://spockframework.org/spock/docs/1.2/module_spring.html"" rel=""nofollow noreferrer"">http://spockframework.org/spock/docs/1.2/module_spring.html</a></li>
<li><a href=""https://allegro.tech/2018/04/Spring-WebMvcTest-with-Spock.html"" rel=""nofollow noreferrer"">https://allegro.tech/2018/04/Spring-WebMvcTest-with-Spock.html</a></li>
<li><a href=""https://objectpartners.com/2018/06/14/spock-1-2-annotations-for-spring-integration-testing/"" rel=""nofollow noreferrer"">https://objectpartners.com/2018/06/14/spock-1-2-annotations-for-spring-integration-testing/</a></li>
</ul>

<p>Below you can see the versions of my test code.</p>

<p>1st version:</p>

<pre class=""lang-groovy prettyprint-override""><code>import org.spockframework.spring.SpringBean
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import spock.lang.Specification
import spock.lang.Unroll

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status

@SpringBootTest
@AutoConfigureMockMvc
class NotaFiscalControllerIT extends Specification {

  @Unroll
  def ""NotaFiscalController::webhook =&gt; falha -&gt; Token #cenario"" () {

    given:
      notaFiscalService.processarRetornoWebhook(_ as DadoRetornadoDto) &gt;&gt; null

    when:
      def result = this.mvc.perform(
        get('/webhook')
        .header('sec-token', token)
        .contentType(MediaType.APPLICATION_JSON)
      )

    then:
      result.andExpect(status().isUnauthorized())

    where:
      cenario     | token
      'ausente'   | ''
      'inválido'  | 'blablebli'
  }

  /**********************************************************************/

  @Autowired
  MockMvc mvc

  @SpringBean
  NotaFiscalService notaFiscalService = Mock()

  /**********************************************************************/
}
</code></pre>

<p>2nd version:</p>

<pre class=""lang-groovy prettyprint-override""><code>import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import spock.lang.Specification
import spock.lang.Unroll
import spock.mock.DetachedMockFactory

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status

@WebMvcTest(controllers = [NotaFiscalController])
class NotaFiscalControllerIT extends Specification {

  @Unroll
  def ""NotaFiscalController::webhook =&gt; falha -&gt; Token #cenario"" () {

    given:
      notaFiscalService.processarRetornoWebhook(_ as DadoRetornadoDto) &gt;&gt; null

    when:
      def result = this.mvc.perform(
        get('/webhook')
        .header('sec-token', token)
        .contentType(MediaType.APPLICATION_JSON)
      )

    then:
      result.andExpect(status().isUnauthorized())

    where:
      cenario     | token
      'ausente'   | ''
      'inválido'  | 'blablebli'
  }

  /**********************************************************************/

  @Autowired
  MockMvc mvc

  @Autowired
  NotaFiscalService notaFiscalService

  /**********************************************************************/

  @TestConfiguration
  static class MockConfig {
    def detachedMockFactory = new DetachedMockFactory()

    @Bean
    NotaFiscalService notaFiscalService() {
      return detachedMockFactory.Mock(NotaFiscalService)
    }
  }
}
</code></pre>

<p>No matter what I do I always get the same Exception:</p>

<pre class=""lang-none prettyprint-override""><code>2019-02-06 11:24:09.184 ERROR 6266 --- [           main] o.s.boot.SpringApplication               : Application startup failed

java.lang.IllegalArgumentException: Could not create type
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:140) ~[byte-buddy-1.6.14.jar:na]
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346) ~[byte-buddy-1.6.14.jar:na]
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161) ~[byte-buddy-1.6.14.jar:na]
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355) ~[byte-buddy-1.6.14.jar:na]
    at org.spockframework.mock.runtime.ByteBuddyMockFactory.createMock(ByteBuddyMockFactory.java:41) ~[spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.mock.runtime.ProxyBasedMockFactory.create(ProxyBasedMockFactory.java:42) ~[spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.mock.SpockSpringProxyCreator.create(SpockSpringProxyCreator.java:29) ~[spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.mock.SpockDefinition.createMock(SpockDefinition.java:75) ~[spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.mock.SpockMockPostprocessor.createMock(SpockMockPostprocessor.java:140) ~[spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.mock.SpockMockPostprocessor.registerMock(SpockMockPostprocessor.java:108) ~[spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.mock.SpockMockPostprocessor.register(SpockMockPostprocessor.java:92) ~[spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.mock.SpockMockPostprocessor.postProcessBeanFactory(SpockMockPostprocessor.java:85) ~[spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.mock.SpockMockPostprocessor.postProcessBeanFactory(SpockMockPostprocessor.java:78) ~[spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:283) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:171) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:687) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:525) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) [spring-boot-test-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) [spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.spockframework.spring.SpringTestContextManager.prepareTestInstance(SpringTestContextManager.java:56) [spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.SpringInterceptor.interceptInitializerMethod(SpringInterceptor.java:43) [spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.extension.AbstractMethodInterceptor.intercept(AbstractMethodInterceptor.java:24) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:97) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.invoke(BaseSpecRunner.java:475) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.runInitializer(BaseSpecRunner.java:341) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.runInitializer(BaseSpecRunner.java:336) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.initializeAndRunIteration(BaseSpecRunner.java:274) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.ParameterizedSpecRunner.runIterations(ParameterizedSpecRunner.java:139) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.ParameterizedSpecRunner.runParameterizedFeature(ParameterizedSpecRunner.java:41) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.doRunFeature(BaseSpecRunner.java:259) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner$5.invoke(BaseSpecRunner.java:243) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.invokeRaw(BaseSpecRunner.java:484) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.invoke(BaseSpecRunner.java:467) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.runFeature(BaseSpecRunner.java:235) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.runFeatures(BaseSpecRunner.java:185) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.doRunSpec(BaseSpecRunner.java:95) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner$1.invoke(BaseSpecRunner.java:81) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.invokeRaw(BaseSpecRunner.java:484) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.invoke(BaseSpecRunner.java:467) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.runSpec(BaseSpecRunner.java:73) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.run(BaseSpecRunner.java:64) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.Sputnik.run(Sputnik.java:63) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na]
Caused by: java.lang.NoSuchMethodError: net.bytebuddy.dynamic.loading.ClassInjector$UsingLookup.isAvailable()Z
    at org.spockframework.mock.runtime.ByteBuddyMockFactory.determineBestClassLoadingStrategy(ByteBuddyMockFactory.java:103) ~[spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.mock.runtime.ByteBuddyMockFactory.access$300(ByteBuddyMockFactory.java:27) ~[spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.mock.runtime.ByteBuddyMockFactory$1.call(ByteBuddyMockFactory.java:54) ~[spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.mock.runtime.ByteBuddyMockFactory$1.call(ByteBuddyMockFactory.java:43) ~[spock-core-1.2-groovy-2.4.jar:1.2]
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138) ~[byte-buddy-1.6.14.jar:na]
    ... 54 common frames omitted

2019-02-06 11:24:09.187  INFO 6266 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@36f7d7b: startup date [Wed Feb 06 11:24:06 BRST 2019]; root of context hierarchy
2019-02-06 11:24:09.191 ERROR 6266 --- [           main] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@670002] to prepare test instance [br.com.k21.notafiscal.controller.NotaFiscalControllerIT@283ab206]

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.spockframework.spring.SpringTestContextManager.prepareTestInstance(SpringTestContextManager.java:56) [spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.SpringInterceptor.interceptInitializerMethod(SpringInterceptor.java:43) [spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.extension.AbstractMethodInterceptor.intercept(AbstractMethodInterceptor.java:24) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:97) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.invoke(BaseSpecRunner.java:475) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.runInitializer(BaseSpecRunner.java:341) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.runInitializer(BaseSpecRunner.java:336) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.initializeAndRunIteration(BaseSpecRunner.java:274) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.ParameterizedSpecRunner.runIterations(ParameterizedSpecRunner.java:139) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.ParameterizedSpecRunner.runParameterizedFeature(ParameterizedSpecRunner.java:41) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.doRunFeature(BaseSpecRunner.java:259) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner$5.invoke(BaseSpecRunner.java:243) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.invokeRaw(BaseSpecRunner.java:484) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.invoke(BaseSpecRunner.java:467) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.runFeature(BaseSpecRunner.java:235) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.runFeatures(BaseSpecRunner.java:185) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.doRunSpec(BaseSpecRunner.java:95) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner$1.invoke(BaseSpecRunner.java:81) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.invokeRaw(BaseSpecRunner.java:484) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.invoke(BaseSpecRunner.java:467) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.runSpec(BaseSpecRunner.java:73) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.BaseSpecRunner.run(BaseSpecRunner.java:64) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.runtime.Sputnik.run(Sputnik.java:63) [spock-core-1.2-groovy-2.4.jar:1.2]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na]
Caused by: java.lang.IllegalArgumentException: Could not create type
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:140) ~[byte-buddy-1.6.14.jar:na]
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346) ~[byte-buddy-1.6.14.jar:na]
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161) ~[byte-buddy-1.6.14.jar:na]
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355) ~[byte-buddy-1.6.14.jar:na]
    at org.spockframework.mock.runtime.ByteBuddyMockFactory.createMock(ByteBuddyMockFactory.java:41) ~[spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.mock.runtime.ProxyBasedMockFactory.create(ProxyBasedMockFactory.java:42) ~[spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.mock.SpockSpringProxyCreator.create(SpockSpringProxyCreator.java:29) ~[spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.mock.SpockDefinition.createMock(SpockDefinition.java:75) ~[spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.mock.SpockMockPostprocessor.createMock(SpockMockPostprocessor.java:140) ~[spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.mock.SpockMockPostprocessor.registerMock(SpockMockPostprocessor.java:108) ~[spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.mock.SpockMockPostprocessor.register(SpockMockPostprocessor.java:92) ~[spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.mock.SpockMockPostprocessor.postProcessBeanFactory(SpockMockPostprocessor.java:85) ~[spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.spring.mock.SpockMockPostprocessor.postProcessBeanFactory(SpockMockPostprocessor.java:78) ~[spock-spring-1.2-groovy-2.4.jar:1.2]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:283) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:171) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:687) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:525) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) ~[spring-boot-test-1.5.9.RELEASE.jar:1.5.9.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ~[spring-test-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    ... 32 common frames omitted
Caused by: java.lang.NoSuchMethodError: net.bytebuddy.dynamic.loading.ClassInjector$UsingLookup.isAvailable()Z
    at org.spockframework.mock.runtime.ByteBuddyMockFactory.determineBestClassLoadingStrategy(ByteBuddyMockFactory.java:103) ~[spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.mock.runtime.ByteBuddyMockFactory.access$300(ByteBuddyMockFactory.java:27) ~[spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.mock.runtime.ByteBuddyMockFactory$1.call(ByteBuddyMockFactory.java:54) ~[spock-core-1.2-groovy-2.4.jar:1.2]
    at org.spockframework.mock.runtime.ByteBuddyMockFactory$1.call(ByteBuddyMockFactory.java:43) ~[spock-core-1.2-groovy-2.4.jar:1.2]
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138) ~[byte-buddy-1.6.14.jar:na]
    ... 54 common frames omitted


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.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.spockframework.spring.SpringTestContextManager.prepareTestInstance(SpringTestContextManager.java:56)
    at org.spockframework.spring.SpringInterceptor.interceptInitializerMethod(SpringInterceptor.java:43)
    at org.spockframework.runtime.extension.AbstractMethodInterceptor.intercept(AbstractMethodInterceptor.java:24)
    at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:97)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.IllegalArgumentException: Could not create type
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:140)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)
    at org.spockframework.mock.runtime.ByteBuddyMockFactory.createMock(ByteBuddyMockFactory.java:41)
    at org.spockframework.mock.runtime.ProxyBasedMockFactory.create(ProxyBasedMockFactory.java:42)
    at org.spockframework.spring.mock.SpockSpringProxyCreator.create(SpockSpringProxyCreator.java:29)
    at org.spockframework.spring.mock.SpockDefinition.createMock(SpockDefinition.java:75)
    at org.spockframework.spring.mock.SpockMockPostprocessor.createMock(SpockMockPostprocessor.java:140)
    at org.spockframework.spring.mock.SpockMockPostprocessor.registerMock(SpockMockPostprocessor.java:108)
    at org.spockframework.spring.mock.SpockMockPostprocessor.register(SpockMockPostprocessor.java:92)
    at org.spockframework.spring.mock.SpockMockPostprocessor.postProcessBeanFactory(SpockMockPostprocessor.java:85)
    at org.spockframework.spring.mock.SpockMockPostprocessor.postProcessBeanFactory(SpockMockPostprocessor.java:78)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:283)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:171)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:687)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:525)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 13 more
Caused by: java.lang.NoSuchMethodError: net.bytebuddy.dynamic.loading.ClassInjector$UsingLookup.isAvailable()Z
    at org.spockframework.mock.runtime.ByteBuddyMockFactory.determineBestClassLoadingStrategy(ByteBuddyMockFactory.java:103)
    at org.spockframework.mock.runtime.ByteBuddyMockFactory.access$300(ByteBuddyMockFactory.java:27)
    at org.spockframework.mock.runtime.ByteBuddyMockFactory$1.call(ByteBuddyMockFactory.java:54)
    at org.spockframework.mock.runtime.ByteBuddyMockFactory$1.call(ByteBuddyMockFactory.java:43)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)
    ... 35 more


Process finished with exit code 255
</code></pre>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/54554883/unable-to-mock-dependency-with-springboot-and-spock-framework,"['spring-boot', 'spock']",1163,True,0,1
Best way to Inject SeedData into Custom WebApplicationFactory,"<p>I have plagiarized the below code from the mightysoft docs site on integration testing and adapted it slightly to meet my needs:</p>

<pre><code>public class CustomWebApplicationFactory&lt;TStartup&gt;
    : WebApplicationFactory&lt;TStartup&gt; where TStartup : class
{
    private readonly SeedDataClass _seed;

    public CustomWebApplicationFactory(SeedDataClass seed)
    {
        _seed = seed;
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        base.ConfigureWebHost(builder);
        builder.UseEnvironment(""Development"");
        builder.ConfigureServices(services =&gt;
        {
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkInMemoryDatabase()
                .BuildServiceProvider();

            services.AddSingleton(_seed);

            services.AddDbContextPool&lt;GatewayContext&gt;(options =&gt;
            {
                options.UseInMemoryDatabase(""InMemoryDbForTesting"");
                options.UseInternalServiceProvider(serviceProvider);
                options.EnableSensitiveDataLogging();
            });

            var sp = services.BuildServiceProvider();

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

                var seed = scopedServices.GetRequiredService&lt;SeedDataClass&gt;();

                db.Database.EnsureCreated();

                try
                {
                    seed.InitializeDbForTests(db);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, $""An error occurred seeding the database with test messages. Error: {ex.Message}"");
                }
            }
        });
    }
}
</code></pre>

<p>To be used like in a test like:</p>

<pre><code>_client = new CustomWebApplicationFactory&lt;Startup&gt;(new SeedDataClass()).CreateClient();
</code></pre>

<p>And this all works but I am looking to add generics to the custom web app factory class and move this code into a nuget package I am working on for internal testing work.</p>

<p>Something like this:</p>

<pre><code>public class CustomWebApplicationFactory&lt;TStartup, TContext&gt;
    : WebApplicationFactory&lt;TStartup&gt; 
    where TStartup : class 
    where TContext : DbContext
</code></pre>

<p>I am stuck on how to provide/inject the <code>SeedDataClass</code> class instance into my new generic custom web app factory.</p>
",https://stackoverflow.com/questions/54201951/best-way-to-inject-seeddata-into-custom-webapplicationfactory,"['c#', 'asp.net-core', 'entity-framework-core']",1465,True,0,2
ApiTestCase class request function returning &quot;function name must be a string&quot; error,"<p>I'm currently doing integration testing for my small personal project on Slim - testing with PHPunit. I set up my own test class extending the <a href=""https://github.com/lzakrzewski/slim-integration-testing-example/blob/master/tests/ApiTestCase.php"" rel=""nofollow noreferrer"">ApiTestCase</a> class.</p>

<p>I only tried it with simple code and PHPStorm is not indicating any errors. I'm on PHP 7.</p>

<p>

<pre><code>class SQLTest extends ApiTestCase
{
    public function test_if_successful(){
        $this-&gt;request('POST', '/v1/users/login', ['email' =&gt; 'm@yahoo.com', 'password' =&gt; '123']);
        $this-&gt;assertThatResponseHasStatus(200);
    }
}
</code></pre>

<p>When run on PHPunit, it gave me an error saying the function name must be a string on the line where I call the request() function.</p>

<p>Here is the request() function in the ApiTestCase class. </p>

<pre><code>protected function request($method, $url, array $requestParameters = [])
    {
        $request = $this-&gt;prepareRequest($method, $url, $requestParameters);
        $response = new Response();

        $app = $this-&gt;app;
        $this-&gt;response = $app($request, $response);
    }
</code></pre>

<p>The error pointed is at the last line: </p>

<pre><code>$this-&gt;response = $app($request, $response);
</code></pre>
",https://stackoverflow.com/questions/55963198/apitestcase-class-request-function-returning-function-name-must-be-a-string-er,"['php', 'rest', 'unit-testing', 'phpunit', 'slim']",73,False,0,0
How do I instantiate a turnContext using the adapter and request as parameters,"<p>I would like to instantiate a turnContext to be used in integration testing. How would I be able to instantiate one without calling on the processActivity() method of the adapter? </p>

<p>I am looking at the documentation but it shows that I would need the request of the post call as the parameter. I would like my testing to be independant of the post call. I would then assume that I would need to instantiate the request? How would I go about doing so?</p>

<p><a href=""https://i.stack.imgur.com/nvSKo.png"" rel=""nofollow noreferrer"">Image of documentation</a></p>
",https://stackoverflow.com/questions/55227528/how-do-i-instantiate-a-turncontext-using-the-adapter-and-request-as-parameters,['botframework'],435,True,0,1
Running Jest with Apollo Server fails global.fetch undefined,"<p>My team is going through the task of updating our projects. We have updated Jest and Apollo to the latest version. Running into an issue where we are doing integration testing with Apollo/GraphQL and getting errors stated below: </p>

<pre><code>TypeError: Cannot read property 'bind' of undefined

  4 | 
  5 | import { createTestClient } from 'apollo-server-testing';
&gt; 6 | import { ApolloServer } from ""apollo-server-express"";
    | ^
  7 | 
  8 | import schemaString from './../../schema/schema-string.mjs';
  9 | import resolvers from '../../../resolvers/query-resolvers.mjs';

  at Object.&lt;anonymous&gt; (node_modules/apollo-server-env/src/index.browser.js:6:15)
  at Object.&lt;anonymous&gt; (node_modules/apollo-server-core/src/index.ts:1:1)
  at Object.&lt;anonymous&gt; (node_modules/apollo-server-express/src/index.ts:1:1)
</code></pre>

<p>Digging into it, seems Apollo polyfils on the global property is not being set. Unsure how to solve this and couldn't find anything online as of yet. We also updated Babel but I don't feel it has anything to do with that unless it's a compiling issue. Any help is appreciated. </p>
",https://stackoverflow.com/questions/57713253/running-jest-with-apollo-server-fails-global-fetch-undefined,"['graphql', 'jestjs', 'apollo', 'babel-jest']",777,False,2,1
Autofac Container Update and Mock dependencies,"<p>As part of integration testing I would like to wrap a registered class with Autofac so that I can track what happens on that class and redirect the operations to the original implementation. </p>

<p>In the following example, I create a first container which the real app container and then create a spyContainer.</p>

<p>The spyContainer should reuse the registeredInstance of <code>NameRetriever</code> as well as the <code>WorldLogger</code> but the <code>WorldLogger</code> should be injected a <code>HelloLoggerSpy</code> which itself should have been instanciated with the original <code>IHelloLogger</code>.</p>

<pre class=""lang-cs prettyprint-override""><code>public class NameRetriever
{
    public string GetName()
    {
        return ""linvi"";
    }
}

public interface IHelloLogger
{
    void Hello();
}

public class HelloLogger : IHelloLogger
{
    private readonly NameRetriever _nameRetriever;

    public HelloLogger(NameRetriever nameRetriever)
    {
        _nameRetriever = nameRetriever;
    }

    public void Hello()
    {
        Console.WriteLine(""Hello "" + _nameRetriever.GetName());
    }
}

public class WorldLogger
{
    private readonly IHelloLogger _helloLogger;

    public WorldLogger(IHelloLogger helloLogger)
    {
        _helloLogger = helloLogger;
    }

    public void World()
    {
        _helloLogger.Hello();
        Console.WriteLine(""Welcome in this world"");
    }
}

public class HelloLoggerSpy : IHelloLogger
{
    private readonly IHelloLogger _sourceHelloLogger;
    public bool Called { get; private set; }

    public HelloLoggerSpy(IHelloLogger sourceHelloLogger)
    {
        _sourceHelloLogger = sourceHelloLogger;
    }

    public void Hello()
    {
        _sourceHelloLogger.Hello();
        Called = true;
    }
}

static void Main()
{
    var containerBuilder = new ContainerBuilder();
    // This is normal container creation
    containerBuilder.RegisterInstance(new NameRetriever());
    containerBuilder.RegisterType&lt;HelloLogger&gt;().As&lt;IHelloLogger&gt;();
    containerBuilder.RegisterType&lt;WorldLogger&gt;();

    var realContainer = containerBuilder.Build();

    // This is something that would be invoked during tests
    // to override the A behaviour
    containerBuilder.Register&lt;IHelloLogger&gt;(context =&gt;
    {
        var realA = context.Resolve&lt;IHelloLogger&gt;(); // recursive as IA is not yet reusing the previous one
        var aSpy = new HelloLoggerSpy(realA);
        return aSpy;
    });

    var spyContainer = containerBuilder.Build(); // cannot build twice

    var b = spyContainer.Resolve&lt;WorldLogger&gt;();
    b.World(); // should have called  HelloLoggerSpy.Hello()
}
</code></pre>

<p>Anyone knows how to achieve this here and how will this be possible in the future?</p>
",https://stackoverflow.com/questions/59479560/autofac-container-update-and-mock-dependencies,"['c#', 'design-patterns', 'dependency-injection', 'autofac']",203,True,2,1
Need help differentiating between mocks and test drivers,"<p>I'm confused to say the least. I might be getting Mocks wrong, Test Drivers wrong or maybe both. </p>

<p>My understanding of Mocks is that it's a way of imitating units, to avoid depending on specific parts of your system when testing. </p>

<p>My understanding of Test Drivers is that it's specifically used for Bottom-up integration testing, to imitate High Level Modules, which haven't been implemented yet. </p>

<p>To me that makes Test Drivers sound like a type of Mock, but are Mocks specifically a unit testing thing? </p>

<p>What's the difference between the two?</p>
",https://stackoverflow.com/questions/56254037/need-help-differentiating-between-mocks-and-test-drivers,"['unit-testing', 'testing', 'mocking', 'integration-testing']",358,True,1,1
Launch and connect to Dynamodb Local within a container,"<p>We are using Dynamodb Local to do integration testing. It is launched inside a container, and within that container, we need to connect to Dynamodb local. Here is how the DocumentClient is initialized:</p>

<pre><code>const doc = new AWS.DynamoDB.DocumentClient({
  region: 'localhost',
  endpoint: 'http://localhost:5000/'
});
</code></pre>

<p>However, when I try connect try batchwrite, like so <code>doc.batchWrite(buildSetData).promise()</code>, the promise is never fulfilled. For those that are wondering, the batchwrite is in JavaScript, and <code>.promise()</code> just returned a JS promise. </p>

<p>However, when I run my setup locally (outside of docker container), everything works perfectly.</p>

<p>TLDR: Why can't I connect to DynamoDb Local inside my container.</p>
",https://stackoverflow.com/questions/56482422/launch-and-connect-to-dynamodb-local-within-a-container,"['amazon-web-services', 'amazon-dynamodb', 'dynamo-local', 'amazon-dynamodb-local']",641,True,1,1
Unable to find dllimports at run time MSTest c#,"<p>I am using <code>MSTest</code> to carry out some integration testing together with some hardware. I place my <code>dll</code> files in the <code>/bin/debug</code> path (the same path as the test executable). However when I create an object and call a certain function that requires the <code>dll</code> import, I am unable to find the <code>dll</code> file. I am using relative path for my <code>dll</code>, hence I expect that the test program should locate my <code>dll</code>’s in the test executable folder. </p>

<p>Is there a way to examine which directory the test executable looks for when running the tests? </p>
",https://stackoverflow.com/questions/57161698/unable-to-find-dllimports-at-run-time-mstest-c,"['c#', 'visual-studio', 'mstest', 'dllimport']",282,True,1,1
How to handle folder of git submodule which is marked as &quot;untracked&quot; in the host repo?,"<p>I've got a code base in which I want to add another repo as a submodule to do some integration testing. So following a tutorial I ran</p>
<pre><code>git submodule add -b master git@gitlab.com:kramer65/whisky.git
</code></pre>
<p>After that, a <code>git status</code> gives me this:</p>
<pre><code>$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use &quot;git push&quot; to publish your local commits)

Untracked files:
  (use &quot;git add &lt;file&gt;...&quot; to include in what will be committed)

    .gitmodules
    whisky/

nothing added to commit but untracked files present (use &quot;git add&quot; to track)
</code></pre>
<p>As you can see the <code>.gitmodules</code> file is new, but the <code>whisky/</code> folder also appears as untracked. After this I committed the <code>.gitmodules</code> file, but the <code>whisky/</code> folder still appears as untracked.</p>
<p>How should I handle this? Do I need to add the <code>whisky/</code> folder also to the &quot;host repo&quot;? Or do I need to add it to <code>.gitignore</code>? Or is there another way to handle this?</p>
",https://stackoverflow.com/questions/59125313/how-to-handle-folder-of-git-submodule-which-is-marked-as-untracked-in-the-host,"['git', 'version-control', 'integration-testing', 'git-submodules']",108,True,1,1
DRM Playback Issue,"<p>I tried to play DRM file its not playing its showing some error can you pls suggest me the way of integration. Just i want to pass DRM Media URL and WideVine Licence, its showing duration of the movie but content not playing.</p>

<p>Version of ExoPlayer being used
'com.google.android.exoplayer:exoplayer:2.7.3'</p>

<p>Note: There is no device specific.</p>

<p>Player Integration</p>

<pre><code> DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
 TrackSelection.Factory videoTrackSelectionFactory =
  new AdaptiveTrackSelection.Factory(bandwidthMeter);
   trackSelector = new 
 DefaultTrackSelector(videoTrackSelectionFactory);

    int errorStringId = R.string.error_drm_unknown;
        DefaultDrmSessionManager&lt;FrameworkMediaCrypto&gt; drmSessionManager = null;
        try {
            String drmSchemeExtra = DRM_SCHEME;
            UUID drmSchemeUuid = Util.getDrmUuid(drmSchemeExtra);
            if (drmSchemeUuid == null) {
                errorStringId = R.string.error_drm_unsupported_scheme;
            } else {
                String[] keyRequestPropertiesArray = new String[]{};
                drmSessionManager =
                        buildDrmSessionManagerV18(
                                drmSchemeUuid, movie.getDrmLicence(), keyRequestPropertiesArray,false);
            }
        } catch (UnsupportedDrmException e) {
            errorStringId = e.reason == UnsupportedDrmException.REASON_UNSUPPORTED_SCHEME
                    ? R.string.error_drm_unsupported_scheme : R.string.error_drm_unknown;
        }

        if (drmSessionManager == null) {
            showToast(activity.getString(errorStringId));
            //activity.finish();
            return;
        }

        boolean preferExtensionDecoders = false;
        @DefaultRenderersFactory.ExtensionRendererMode int extensionRendererMode =
                ((IdeaApplication) activity.getApplication()).useExtensionRenderers()
                        ? (preferExtensionDecoders ? DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER
                        : DefaultRenderersFactory.EXTENSION_RENDERER_MODE_ON)
                        : DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF;
        DefaultRenderersFactory renderersFactory = new DefaultRenderersFactory(context, drmSessionManager,extensionRendererMode);

        // Create a player instance.
        player =  ExoPlayerFactory.newSimpleInstance(context,trackSelector,new DefaultLoadControl(),drmSessionManager);
</code></pre>

<p>Testing DRM:</p>

<p>""uri"": ""<a href=""https://storage.googleapis.com/wvmedia/cenc/h264/tears/tears.mpd"" rel=""nofollow noreferrer"">https://storage.googleapis.com/wvmedia/cenc/h264/tears/tears.mpd</a>"",
""drm_scheme"": ""widevine"",
""drm_license_url"": ""<a href=""https://proxy.uat.widevine.com/proxy?video_id=0894c7c8719b28a0&amp;provider=widevine_test"" rel=""nofollow noreferrer"">https://proxy.uat.widevine.com/proxy?video_id=0894c7c8719b28a0&amp;provider=widevine_test</a>""</p>

<p>for error logs kindly check below issue which is having bug report</p>

<p><a href=""https://github.com/google/ExoPlayer/issues/5359"" rel=""nofollow noreferrer"">https://github.com/google/ExoPlayer/issues/5359</a></p>
",https://stackoverflow.com/questions/54142090/drm-playback-issue,"['android', 'exoplayer', 'drm']",274,False,1,0
Creating spark cluster with drone.yml not working,"<p>I have docker-compose.yml with below image and configuration</p>

<pre><code>version: '3'
services:
  spark-master:
    image: bde2020/spark-master:2.4.4-hadoop2.7
    container_name: spark-master
    ports:
      - ""8080:8080""
      - ""7077:7077""
    environment:
      - INIT_DAEMON_STEP=setup_spark
  spark-worker-1:
    image: bde2020/spark-worker:2.4.4-hadoop2.7
    container_name: spark-worker-1
    depends_on:
      - spark-master
    ports:
      - ""8081:8081""
    environment:
      - ""SPARK_MASTER=spark://spark-master:7077""
</code></pre>

<p>here the docker-compose up log  --->   <a href=""https://jpst.it/1Xc4K"" rel=""nofollow noreferrer"">https://jpst.it/1Xc4K</a></p>

<p>and here containers up and running and i mean spark worker connected to spark master without any issues , now problem is i created drone.yml and where i added services component with </p>

<pre><code>services:
  jce-cassandra:
    image: cassandra:3.0
    ports:
      - ""9042:9042""

  jce-elastic:
    image: elasticsearch:5.6.16-alpine
    ports:
      - ""9200:9200""
    environment:
      - ""ES_JAVA_OPTS=-Xms512m -Xmx512m""

  janusgraph:
    image: janusgraph/janusgraph:latest
    ports:
      - ""8182:8182""
    environment:
      JANUS_PROPS_TEMPLATE: cassandra-es
      janusgraph.storage.backend: cql
      janusgraph.storage.hostname: jce-cassandra
      janusgraph.index.search.backend: elasticsearch
      janusgraph.index.search.hostname: jce-elastic
    depends_on:
      - jce-elastic
      - jce-cassandra

  spark-master:
    image: bde2020/spark-master:2.4.4-hadoop2.7
    container_name: spark-master
    ports:
      - ""8080:8080""
      - ""7077:7077""
    environment:
      - INIT_DAEMON_STEP=setup_spark

  spark-worker-1:
    image: bde2020/spark-worker:2.4.4-hadoop2.7
    container_name: spark-worker-1
    depends_on:
      - spark-master
    ports:
      - ""8081:8081""
    environment:
      - ""SPARK_MASTER=spark://spark-master:7077""
</code></pre>

<p>but here spark worker is not connected to spark master getting exceptions, <a href=""https://onlinenotepad.us/pRy3mPmkBF"" rel=""nofollow noreferrer"">here</a> is exception log details , can some one please guide me why am facing this issue</p>

<p>Note : I am trying to create these services in drone.yml for my integration testing </p>
",https://stackoverflow.com/questions/59232036/creating-spark-cluster-with-drone-yml-not-working,"['docker', 'apache-spark', 'docker-compose', 'janusgraph', 'drone.io']",195,False,1,1
Arquillian integration test code coverage issue with Jacoco,"<p>I am doing integration testing using arquillian and tomee remote plugin. it is working good. But my code coverage is not working. I am using Jacoco plugin for code coverage. Getting  Exception in my Java class <strong>java.lang.instrument.IllegalClassFormatException: Error while instrumenting com/demo/EmpService</strong></p>

<p>How to do code coverage in remote container using Jacoco ?</p>

<p><strong>Note:</strong> I have passed javaagent ( argLine ) to server catalina opts in integration phase. I am injecting my bean in test class and trying to cover test cases. Test case is passed. But no code coverage and getting exception</p>

<p><strong>EmpService:</strong></p>

<pre><code>import javax.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class EmpService {

    public String getName(String name) {
        System.out.println("" I am here ###################### ""+name);
        String s = ""Fine"";
        if(name.startsWith(""s"")) {
            s = ""Welcome"";
        }
        return s;
    }
}
</code></pre>

<p><strong>EmpSericeIT.java</strong></p>

<pre><code>public class EmpServiceIT extends Arquillian {

    @Inject
    private EmpService empService;

    @Deployment
    public static WebArchive createDeployment() throws IOException {
        WebArchive webArchive = ShrinkWrap.create(WebArchive.class, ""test.war"")
                .addClass(EmpService.class)
                .addAsWebInfResource(EmptyAsset.INSTANCE, ""beans.xml"");
        System.out.println(webArchive.toString(true));
        return webArchive;
    }

    @Test
    public void testService() {

        assertNotNull(empService);
        assertEquals(empService.getName(""K""),""Fine"");
        assertEquals(empService.getName(""s""),""Welcome"");
    }
}
&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns=""http://maven.apache.org/POM/4.0.0""
         xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
         xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;groupId&gt;com.demo&lt;/groupId&gt;
    &lt;artifactId&gt;code-coverage&lt;/artifactId&gt;
    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
    &lt;properties&gt;
        &lt;maven.compiler.source&gt;1.8&lt;/maven.compiler.source&gt;
        &lt;maven.compiler.target&gt;1.8&lt;/maven.compiler.target&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;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt;

        &lt;tomee.version&gt;7.1.0&lt;/tomee.version&gt;
        &lt;tomee.classifier&gt;plus&lt;/tomee.classifier&gt;
        &lt;lombok.version&gt;1.16.8&lt;/lombok.version&gt;
        &lt;arquillian.version&gt;1.4.1.Final&lt;/arquillian.version&gt;
        &lt;testng.version&gt;6.14.3&lt;/testng.version&gt;
        &lt;shrinkwrap.resolvers.version&gt;3.1.3&lt;/shrinkwrap.resolvers.version&gt;
        &lt;plugin.maven.jacoco.version&gt;0.8.2&lt;/plugin.maven.jacoco.version&gt;

        &lt;plugin.maven-surefire.version&gt;2.19.1&lt;/plugin.maven-surefire.version&gt;
        &lt;version.plugin.maven.failsafe&gt;2.19.1&lt;/version.plugin.maven.failsafe&gt;

    &lt;/properties&gt;

    &lt;dependencies&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.tomee&lt;/groupId&gt;
            &lt;artifactId&gt;apache-tomee&lt;/artifactId&gt;
            &lt;classifier&gt;${tomee.classifier}&lt;/classifier&gt;
            &lt;type&gt;zip&lt;/type&gt;
            &lt;scope&gt;provided&lt;/scope&gt;
            &lt;version&gt;${tomee.version}&lt;/version&gt;
            &lt;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
                    &lt;artifactId&gt;slf4j-jdk14&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
        &lt;/dependency&gt;


        &lt;dependency&gt;
            &lt;groupId&gt;org.jboss.arquillian.testng&lt;/groupId&gt;
            &lt;artifactId&gt;arquillian-testng-container&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.jboss.arquillian.config&lt;/groupId&gt;
            &lt;artifactId&gt;arquillian-config-api&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.jboss.arquillian.extension&lt;/groupId&gt;
            &lt;artifactId&gt;arquillian-jacoco&lt;/artifactId&gt;
            &lt;version&gt;1.0.0.Alpha10&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.jacoco&lt;/groupId&gt;
            &lt;artifactId&gt;org.jacoco.core&lt;/artifactId&gt;
            &lt;version&gt;${plugin.maven.jacoco.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.jboss.shrinkwrap.resolver&lt;/groupId&gt;
            &lt;artifactId&gt;shrinkwrap-resolver-depchain&lt;/artifactId&gt;
            &lt;version&gt;${shrinkwrap.resolvers.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
            &lt;type&gt;pom&lt;/type&gt;
        &lt;/dependency&gt;


        &lt;dependency&gt;
            &lt;groupId&gt;org.testng&lt;/groupId&gt;
            &lt;artifactId&gt;testng&lt;/artifactId&gt;
            &lt;version&gt;${testng.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;


        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.tomee&lt;/groupId&gt;
            &lt;artifactId&gt;arquillian-tomee-remote&lt;/artifactId&gt;
            &lt;version&gt;${tomee.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
            &lt;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
                    &lt;groupId&gt;commons-logging&lt;/groupId&gt;
                &lt;/exclusion&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.apache.myfaces.core&lt;/groupId&gt;
                    &lt;artifactId&gt;myfaces-api&lt;/artifactId&gt;
                &lt;/exclusion&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.apache.myfaces.core&lt;/groupId&gt;
                    &lt;artifactId&gt;myfaces-impl&lt;/artifactId&gt;
                &lt;/exclusion&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.apache.tomee&lt;/groupId&gt;
                    &lt;artifactId&gt;tomee-myfaces&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.tomee&lt;/groupId&gt;
            &lt;artifactId&gt;openejb-cxf-rs&lt;/artifactId&gt;
            &lt;version&gt;${tomee.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

    &lt;/dependencies&gt;

    &lt;build&gt;

        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.jacoco&lt;/groupId&gt;
                &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;
                &lt;version&gt;${plugin.maven.jacoco.version}&lt;/version&gt;
                &lt;configuration&gt;
                    &lt;includes&gt;
                    &lt;/includes&gt;
                &lt;/configuration&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;id&gt;default-prepare-agent&lt;/id&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;prepare-agent&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                    &lt;execution&gt;
                        &lt;id&gt;default-prepare-agent-integration&lt;/id&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;prepare-agent-integration&lt;/goal&gt;
                        &lt;/goals&gt;
                        &lt;configuration&gt;
                            &lt;destFile&gt;${project.build.directory}/jacoco-it.exec&lt;/destFile&gt;
                        &lt;/configuration&gt;
                    &lt;/execution&gt;
                    &lt;execution&gt;
                        &lt;id&gt;Create Unit Test Report&lt;/id&gt;
                        &lt;phase&gt;prepare-package&lt;/phase&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;report&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                    &lt;execution&gt;
                        &lt;id&gt;Create Integration Test Report&lt;/id&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;report-integration&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
                &lt;version&gt;${plugin.maven-surefire.version}&lt;/version&gt;
                &lt;configuration&gt;
                    &lt;skip&gt;true&lt;/skip&gt;
                    &lt;skipTests&gt;true&lt;/skipTests&gt;
                    &lt;failIfNoTests&gt;false&lt;/failIfNoTests&gt;
                    &lt;excludes&gt;
                        &lt;exclude&gt;**/*IT.java&lt;/exclude&gt;
                    &lt;/excludes&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;${version.plugin.maven.failsafe}&lt;/version&gt;
                &lt;configuration&gt;
&lt;!--
                    &lt;includes&gt;
                        &lt;include&gt;**/*Test.java&lt;/include&gt;
                    &lt;/includes&gt;
--&gt;
                        &lt;systemPropertyVariables&gt;
                            &lt;tomee.classifier&gt;${tomee.classifier}&lt;/tomee.classifier&gt;
                            &lt;tomee.version&gt;${tomee.version}&lt;/tomee.version&gt;
                            &lt;tomee.httpPort&gt;-1&lt;/tomee.httpPort&gt;
                            &lt;tomee.stopPort&gt;-1&lt;/tomee.stopPort&gt;
                            &lt;tomee.ajpPort&gt;-1&lt;/tomee.ajpPort&gt;
                            &lt;tomee.dir&gt;target/apache-tomee-remote&lt;/tomee.dir&gt;
                            &lt;tomee.appWorkingDir&gt;target/arquillian-test-working-dir&lt;/tomee.appWorkingDir&gt;
                            &lt;tomee.cleanOnStartUp&gt;true&lt;/tomee.cleanOnStartUp&gt;
                            &lt;tomee.catalina_opts&gt;-Xmx550m -XX:MaxPermSize=200m ${argLine}&lt;/tomee.catalina_opts&gt;
                            &lt;!--&lt;tomee.javaVmArguments&gt;-Xmx1024m ${surefireArgLine} -Dsimple=XYZ&lt;/tomee.javaVmArguments&gt;--&gt;
                            &lt;tomee.properties&gt;
                                tomee.jpa.cdi=false
                                LOG_TO_CONSOLE=true
                            &lt;/tomee.properties&gt;
                        &lt;/systemPropertyVariables&gt;
&lt;!--
                        &lt;argLine&gt; &lt;/argLine&gt;
                        &lt;suiteXmlFiles&gt;
                            &lt;suiteXmlFile&gt;${project.basedir}/src/test/resources/testng.xml&lt;/suiteXmlFile&gt;
                        &lt;/suiteXmlFiles&gt;
--&gt;
                &lt;/configuration&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;integration-test&lt;/goal&gt;
                            &lt;goal&gt;verify&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;

    &lt;dependencyManagement&gt;
        &lt;dependencies&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.jboss.arquillian&lt;/groupId&gt;
                &lt;artifactId&gt;arquillian-bom&lt;/artifactId&gt;
                &lt;version&gt;${arquillian.version}&lt;/version&gt;
                &lt;type&gt;pom&lt;/type&gt;
                &lt;scope&gt;import&lt;/scope&gt;
            &lt;/dependency&gt;
        &lt;/dependencies&gt;
    &lt;/dependencyManagement&gt;
</code></pre>

<p><strong>Exception</strong></p>

<pre><code>java.lang.instrument.IllegalClassFormatException: Error while instrumenting com/demo/EmpService.
    at org.jacoco.agent.rt.internal_28bab1d.CoverageTransformer.transform(CoverageTransformer.java:93)
    at sun.instrument.TransformerManager.transform(TransformerManager.java:188)
    at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:428)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2339)
    at org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:829)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1278)
    at org.apache.tomee.catalina.TomEEWebappClassLoader.loadClass(TomEEWebappClassLoader.java:208)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1137)
    at org.apache.openejb.cdi.CdiScanner.load(CdiScanner.java:321)
    at org.apache.openejb.cdi.CdiScanner.handleBda(CdiScanner.java:255)
    at org.apache.openejb.cdi.CdiScanner.init(CdiScanner.java:148)
    at org.apache.openejb.cdi.OpenEJBLifecycle.startApplication(OpenEJBLifecycle.java:179)
    at org.apache.openejb.cdi.ThreadSingletonServiceImpl.initialize(ThreadSingletonServiceImpl.java:189)
    at org.apache.openejb.cdi.CdiBuilder.build(CdiBuilder.java:41)
    at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:963)
    at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:757)
    at org.apache.tomee.catalina.TomcatWebAppBuilder.startInternal(TomcatWebAppBuilder.java:1303)
    at org.apache.tomee.catalina.TomcatWebAppBuilder.configureStart(TomcatWebAppBuilder.java:1125)
    at org.apache.tomee.catalina.GlobalListenerSupport.lifecycleEvent(GlobalListenerSupport.java:133)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:94)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5154)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:754)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.tomee.catalina.TomcatWebAppBuilder.deployWar(TomcatWebAppBuilder.java:652)
    at org.apache.tomee.catalina.TomcatWebAppBuilder.deployWebApps(TomcatWebAppBuilder.java:592)
    at org.apache.tomee.catalina.deployment.TomcatWebappDeployer.deploy(TomcatWebappDeployer.java:47)
    at org.apache.openejb.assembler.DeployerEjb.deploy(DeployerEjb.java:177)
    at org.apache.openejb.assembler.DeployerEjb.deploy(DeployerEjb.java:140)
    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.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
    at org.apache.openejb.security.internal.InternalSecurityInterceptor.invoke(InternalSecurityInterceptor.java:35)
    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.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
    at org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:191)
    at org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:102)
    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.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
    at org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85)
    at org.apache.openejb.core.singleton.SingletonContainer._invoke(SingletonContainer.java:272)
    at org.apache.openejb.core.singleton.SingletonContainer.invoke(SingletonContainer.java:221)
    at org.apache.openejb.server.ejbd.EjbRequestHandler.doEjbObject_BUSINESS_METHOD(EjbRequestHandler.java:371)
    at org.apache.openejb.server.ejbd.EjbRequestHandler.processRequest(EjbRequestHandler.java:182)
    at org.apache.openejb.server.ejbd.EjbDaemon.processEjbRequest(EjbDaemon.java:360)
    at org.apache.openejb.server.ejbd.EjbDaemon.service(EjbDaemon.java:247)
    at org.apache.openejb.server.ejbd.EjbServer.service(EjbServer.java:104)
    at org.apache.openejb.server.httpd.ServerServlet.service(ServerServlet.java:60)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.tomee.catalina.OpenEJBSecurityListener$RequestCapturer.invoke(OpenEJBSecurityListener.java:97)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.IOException: Error while instrumenting com/demo/EmpService.
    at org.jacoco.agent.rt.internal_28bab1d.core.instr.Instrumenter.instrumentError(Instrumenter.java:175)
    at org.jacoco.agent.rt.internal_28bab1d.core.instr.Instrumenter.instrument(Instrumenter.java:125)
    at org.jacoco.agent.rt.internal_28bab1d.CoverageTransformer.transform(CoverageTransformer.java:91)
    ... 83 more
</code></pre>
",https://stackoverflow.com/questions/54412555/arquillian-integration-test-code-coverage-issue-with-jacoco,"['code-coverage', 'jacoco', 'jboss-arquillian', 'apache-tomee', 'jacoco-maven-plugin']",764,True,1,1
Table Driven Tests with Gradle: NoClassDefFoundError TableTestingKt,"<p>I use <a href=""https://github.com/kotlintest/kotlintest/blob/master/doc/reference.md"" rel=""nofollow noreferrer"">kotlintest</a> in a Spring Boot Project for unit and integration testing. I can run my unit tests without any troubles in IntelliJ and all of them are green. When I run my tests in gradle with <code>./gradlew clean test</code> though, all my tests using the <code>table()</code>, <code>headers()</code> and <code>row()</code> functions fail with the following exception:</p>

<pre><code>java.lang.NoClassDefFoundError: io/kotlintest/tables/TableTestingKt
    at com.tractive.hwservice.MessageContentExtensionsSpec$7.invokeSuspend(MessageContentExtensionsSpec.kt:110)
    at com.tractive.hwservice.MessageContentExtensionsSpec$7.invoke(MessageContentExtensionsSpec.kt)
    at io.kotlintest.runner.jvm.TestCaseExecutor$executeTest$supervisorJob$1$invokeSuspend$$inlined$map$lambda$1.invokeSuspend(TestCaseExecutor.kt:130)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)
    at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:233)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
    at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: java.lang.ClassNotFoundException: io.kotlintest.tables.TableTestingKt
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
    ... 8 more
</code></pre>

<p>All other tests are fine. </p>

<p>Here is part of my <code>build.gradle</code>: </p>

<pre><code>repositories {
    mavenCentral()
}

dependencyManagement {
    dependencies {
        dependency 'ch.qos.logback.contrib:logback-classic:1.1.7'
        dependency 'ch.qos.logback.contrib:logback-json-classic:0.1.5'
        dependency 'ch.qos.logback.contrib:logback-jackson:0.1.5'
        dependency 'com.fasterxml.jackson.core:jackson-databind:2.9.3'
        dependency 'com.fasterxml.jackson.module:jackson-module-kotlin:2.9.7'
        dependency 'org.assertj:assertj-core:3.9.1'
    }
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-amqp'
    implementation 'org.springframework.boot:spring-boot-starter-integration'
    implementation 'org.jetbrains.kotlin:kotlin-reflect'
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'

    compile 'org.springframework.boot:spring-boot-starter-data-mongodb'
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'com.fasterxml.jackson.core:jackson-databind'
    compile 'ch.qos.logback.contrib:logback-jackson'
    compile 'ch.qos.logback.contrib:logback-json-classic'
    compile 'com.fasterxml.jackson.module:jackson-module-kotlin'

    testCompile 'org.assertj:assertj-core'
    testCompile 'org.junit.jupiter:junit-jupiter-api'
    testCompile 'org.junit.jupiter:junit-jupiter-params'
    testCompile 'de.flapdoodle.embed:de.flapdoodle.embed.mongo'

    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'

    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.amqp:spring-rabbit-test'
    testImplementation 'io.kotlintest:kotlintest-runner-junit5:3.3.3'
    testImplementation 'io.kotlintest:kotlintest-extensions-spring:3.3.3'
    testImplementation 'io.kotlintest:kotlintest-assertions:3.3.3'

}

jacocoTestReport {
    reports {
        xml.enabled true
    }
}

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

<p>From what I read I shouldn't even need the <code>io.kotlintest:kotlintest-assertions</code> dependency as it should be included in the runner.</p>

<p>It looks like TableTestingKt is not converted to a class, as it should be.</p>
",https://stackoverflow.com/questions/58518135/table-driven-tests-with-gradle-noclassdeffounderror-tabletestingkt,"['testing', 'gradle', 'kotlintest', 'table-driven']",80,True,1,1
SecurityContext.getUserInfo() does not work from localhost,"<p>I fetch the userid using the below code snippet. Its required for Audit Logging</p>

<p>final UserInfo userInfo = SecurityContext.getUserInfo();
final String userId = userInfo.getLogonName();</p>

<p>After the deployment of application in Cloud Foundry, it works as expected.</p>

<p>The problem is when you run the application in localhost. The aforementioned method does not work &amp; results in an exception.</p>

<p>To handle this, I had also done the mocking using the below code snippet,</p>

<pre><code>@Profile(""local"")
@Configuration
public class LocalSecurityConfig {
    private static final Logger LOGGER = CloudLoggerFactory.getSanitizedLogger(LocalSecurityConfig.class);
    public static final String XSAPPNAME = ""test-xsappname!t0"";

    public LocalSecurityConfig() throws IOException {
        final MockUtil mockUtil = new MockUtil();
        mockUtil.mockDefaults();
        mockUtil.mockAuditLog();

        final String publicKey = FileUtils.readFile(""publicKey.txt"");
        final Map&lt;String, String&gt; verificationkey = ImmutableMap.of(""verificationkey"", publicKey);
        final JsonObject xsuaaServiceCredentials = new Gson().toJsonTree(verificationkey).getAsJsonObject();
        when(((ScpCfCloudPlatform) CloudPlatformAccessor.getCloudPlatform())
                .getXsuaaServiceCredentials(org.mockito.ArgumentMatchers.any(DecodedJWT.class)))
                        .thenReturn(xsuaaServiceCredentials);
    }
    ---
}
</code></pre>

<p>The aforementioned code works well for local Integration Testing.</p>

<p><strong>Exception occurs in the below code final userInfo.getLogonName() of the method getUserId()</strong></p>

<pre><code>@AfterQuery(entity = VIEW_CLOUDSERVICES, serviceName = LANDSCAPE_SERVICE)
public QueryResponse afterQueryTechnicalServices(QueryRequest req, QueryResponseAccessor res, ExtensionHelper h) {
    List&lt;EntityData&gt; entData = res.getEntityDataList();
    LOG.info(""##### CloudServices.afterQuery: {} ########"", entData.size());

    QueryResponse response = null;
    String userId = null;
    String identityZone = null;
    try {
        userId = getUserId();
        identityZone = SecurityContext.getUserInfo().getIdentityZone();
    } catch (UserInfoException e1) {
        response = QueryResponse.setError(ErrorResponse.getBuilder().setStatusCode(HttpStatus.UNAUTHORIZED.value())
                .setCause(e1).setMessage(""USERCONTEXT_UNAUTHORIZED"", e1.toString()).response());
        LOG.error(""Failed to Read User Information: Exception Text={}"", e1.getMessage(), e1);

        AuditLogger.logDataRead(new AccessRequester(userId, identityZone, null, null),
                new AuditedDataObject(ENTITY_ENDPOINT, (String) ""LMS""),
                new AuditedDataSubject(""person"", ""user"", userId), null,
                new AccessedAttribute(VIEW_CLOUDSERVICES, Operation.READ, ""Read Cloud Services"", null, entData, true));

        return response;
    }
    AuditLogger.logDataRead(new AccessRequester(userId, identityZone, null, null),
            new AuditedDataObject(ENTITY_ENDPOINT, (String) ""LMS""),
            new AuditedDataSubject(""person"", ""user"", userId), null,
            new AccessedAttribute(VIEW_CLOUDSERVICES, Operation.READ, ""Read Cloud Services"", null, entData, true));

    return QueryResponse.setSuccess().setData(entData).response();
}

private String getUserId() throws UserInfoException {

    final UserInfo userInfo = SecurityContext.getUserInfo();
    System.out.println(userInfo);
    final String userId = userInfo.getLogonName();
    System.out.println(userId);

    MDC.put(""user_name"", userId);
    LOG.debug(""UserConfig - ClientId: {}"", userInfo.getClientId());

    if (userId == null || userId.length() == 0) {
        throw new IllegalStateException(""logon_name attribute was not returned from UserInfo!"");
    }

    System.out.println(""Benu"" + ""returned"");
    return userId;
}
</code></pre>

<p><strong>Error</strong></p>

<pre><code>019-07-12 10:49:15.388 ERROR 21492 --- [nio-8085-exec-2] com.sap.crun.landscape.LandscapeService  : Failed to Read User Information: Exception Text=Invalid user attribute grant_type (END OF LOG ENTRY)
2019-07-12 10:49:15.429 DEBUG 21492 --- [nio-8085-exec-2] c.s.c.s.s.p.v.rt.cds.CDSDataSourceParam  : -------------------------INITIALIZED CONNECTION OBTAINED------------------
2019-07-12 10:49:15.449 DEBUG 21492 --- [nio-8085-exec-2] c.s.c.s.s.p.v.rt.cds.CDSDataSourceParam  : -------------------------INITIALIZED CONNECTION OBTAINED------------------
2019-07-12 10:49:15.449 DEBUG 21492 --- [nio-8085-exec-2] c.s.c.s.s.p.r.c.w.CDSConnectionWrapper   : ----------------CONNECTION CLOSED-------------------------
2019-07-12 10:49:15.456 ERROR 21492 --- [nio-8085-exec-2] c.s.c.s.s.p.v.r.d.provider.DataProvider  : Error in readEntitySet

org.apache.olingo.odata2.api.exception.ODataApplicationException: Unable to execute the operation. Please check the logs for more details.
    at com.sap.cloud.sdk.service.prov.v2.rt.core.extensions.ExtensionDataProvider.handleException(ExtensionDataProvider.java:2497) ~[odata2.core-1.29.0.jar:na]
    at com.sap.cloud.sdk.service.prov.v2.rt.core.extensions.ExtensionDataProvider.checkAndExecuteAfterExit(ExtensionDataProvider.java:1068) ~[odata2.core-1.29.0.jar:na]
    at com.sap.cloud.sdk.service.prov.v2.rt.core.extensions.ExtensionDataProvider.readEntitySetNonDraftFlow(ExtensionDataProvider.java:565) ~[odata2.core-1.29.0.jar:na]
    at com.sap.cloud.sdk.service.prov.v2.rt.core.extensions.ExtensionDataProvider.readEntitySet(ExtensionDataProvider.java:391) ~[odata2.core-1.29.0.jar:na]
    at com.sap.cloud.sdk.service.prov.v2.rt.data.provider.HybridDataProvider.readEntitySet(HybridDataProvider.java:126) ~[odatav2-hybrid-1.29.0.jar:na]
    at com.sap.gateway.core.api.provider.data.GenericODataProcessor.readEntitySet(GenericODataProcessor.java:885) [odata-core-1.29.0.jar:na]
    at org.apache.olingo.odata2.core.Dispatcher.dispatch(Dispatcher.java:77) [odatav2-lib-1.29.0.jar:na]
    at org.apache.olingo.odata2.core.ODataRequestHandler.handle(ODataRequestHandler.java:131) [odatav2-lib-1.29.0.jar:na]
    at org.apache.olingo.odata2.core.servlet.ODataServlet.handleRequest(ODataServlet.java:216) [odatav2-lib-1.29.0.jar:na]
    at org.apache.olingo.odata2.core.servlet.ODataServlet.handle(ODataServlet.java:115) [odatav2-lib-1.29.0.jar:na]
    at org.apache.olingo.odata2.core.servlet.ODataServlet.service(ODataServlet.java:85) [odatav2-lib-1.29.0.jar:na]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.17.jar:9.0.17]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at com.sap.cloud.sdk.cloudplatform.servlet.RequestContextServletFilter.lambda$doFilter$0(RequestContextServletFilter.java:197) [servlet-2.17.0.jar:na]
    at com.sap.cloud.sdk.cloudplatform.servlet.RequestContextCallable.call(RequestContextCallable.java:131) ~[servlet-2.17.0.jar:na]
    at com.sap.cloud.sdk.cloudplatform.servlet.RequestContextServletFilter.doFilter(RequestContextServletFilter.java:209) [servlet-2.17.0.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90) ~[spring-boot-actuator-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:176) ~[spring-security-oauth2-2.0.17.RELEASE.jar:na]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) ~[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117) ~[spring-boot-actuator-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106) ~[spring-boot-actuator-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:679) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_202]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_202]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
    at java.lang.Thread.run(Thread.java:836) ~[na:1.8.0_202]
Caused by: java.lang.NullPointerException: while trying to invoke the method java.lang.CharSequence.length() of a null object loaded from field java.util.regex.Matcher.text of an object loaded from local variable 'this'
    at java.util.regex.Matcher.getTextLength(Matcher.java:1283) ~[na:1.8.0_202]
    at java.util.regex.Matcher.reset(Matcher.java:309) ~[na:1.8.0_202]
    at java.util.regex.Matcher.&lt;init&gt;(Matcher.java:229) ~[na:1.8.0_202]
    at java.util.regex.Pattern.matcher(Pattern.java:1093) ~[na:1.8.0_202]
    at com.sap.xs.env.VcapServices.matcher(VcapServices.java:342) ~[xs-env-1.6.9.jar:na]
    at com.sap.xs.env.VcapServices.findServices(VcapServices.java:293) ~[xs-env-1.6.9.jar:na]
    at com.sap.xs.env.VcapServices.findService(VcapServices.java:191) ~[xs-env-1.6.9.jar:na]
    at com.sap.xs.audit.client.impl.v2.AuditLogMessageFactoryImpl.getCredentials(AuditLogMessageFactoryImpl.java:53) ~[audit-java-client-impl-2.0.6.jar:na]
    at com.sap.xs.audit.client.impl.v2.AuditLogMessageFactoryImpl.&lt;init&gt;(AuditLogMessageFactoryImpl.java:34) ~[audit-java-client-impl-2.0.6.jar:na]
    at com.sap.xs.audit.client.impl.v2.AuditLogMessageFactoryImpl.&lt;init&gt;(AuditLogMessageFactoryImpl.java:30) ~[audit-java-client-impl-2.0.6.jar:na]
    at com.sap.cloud.sdk.cloudplatform.auditlog.ScpCfAuditLog.getAuditLogMessageFactory(ScpCfAuditLog.java:58) ~[auditlog-scp-cf-2.17.0.jar:na]
    at com.sap.cloud.sdk.cloudplatform.auditlog.ScpCfAuditLog.&lt;init&gt;(ScpCfAuditLog.java:75) ~[auditlog-scp-cf-2.17.0.jar:na]
    at com.sap.cloud.sdk.cloudplatform.auditlog.ScpCfAuditLogFacade.getAuditLog(ScpCfAuditLogFacade.java:64) ~[auditlog-scp-cf-2.17.0.jar:na]
    at com.sap.cloud.sdk.cloudplatform.auditlog.AuditLogger.getAuditLog(AuditLogger.java:67) ~[auditlog-2.17.0.jar:na]
    at com.sap.cloud.sdk.cloudplatform.auditlog.AuditLogger.logDataRead(AuditLogger.java:445) ~[auditlog-2.17.0.jar:na]
    at com.sap.crun.landscape.LandscapeService.afterQueryTechnicalServices(LandscapeService.java:109) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_202]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_202]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_202]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_202]
    at com.sap.cloud.sdk.service.prov.v2.rt.core.extensions.ExtensionWrappedDataProvider.process(ExtensionWrappedDataProvider.java:460) ~[odata2.core-1.29.0.jar:na]
    at com.sap.cloud.sdk.service.prov.v2.rt.core.extensions.ExtensionDataProvider.checkAndExecuteAfterExit(ExtensionDataProvider.java:1065) ~[odata2.core-1.29.0.jar:na]
    ... 94 common frames omitted
</code></pre>
",https://stackoverflow.com/questions/56993425/securitycontext-getuserinfo-does-not-work-from-localhost,['sap-cloud-sdk'],499,False,0,1
Don&#39;t run cucumber feature but add it to serenity reports,"<p>I use Serenity framework in my project for selenium integration testing. I use Screenplay pattern.</p>

<p>I have two features in one folder and each feature contains two scenarios. I would like to ignore whole feature, but when I add <code>@Ignore</code> annotation on feature level both features are ignored. When I add <code>@Ignore</code> to each scenario runner ignores some steps, but runs step with RestTemplate get request and fail because of skipped previous step.</p>

<p><strong>How can I force serenity do not run all scenarios in feature but show it in reports?</strong></p>
",https://stackoverflow.com/questions/57054648/dont-run-cucumber-feature-but-add-it-to-serenity-reports,"['java', 'cucumber-serenity']",255,True,0,1
Avoid dependency in Integration Testing,"<p>In integration testing scenario, I have an object creation if the object creation is successful I have Record CRUD operation but if object creation fails then record operation should be skipped. To maintain these integration scenarios I have configured my testng.xml file like this : -  </p>

<pre><code>&lt;!DOCTYPE suite SYSTEM ""http://testng.org/testng-1.0.dtd""&gt;
&lt;suite name=""TestNG"" verbose=""1"" &gt;

    &lt;test name=""Object  Testing"" preserve-order=""true""&gt;
        &lt;classes&gt;
            &lt;class name=""com.settings.test.employee.PostObject"" /&gt;
            &lt;class name=""com.settings.test.employee.GetObject"" /&gt;
            &lt;class name=""com.settings.test.employee.DeleteObject"" /&gt;
        &lt;/classes&gt;
    &lt;/test&gt;

    &lt;test name="" Record Testing"" preserve-order=""true""&gt;
        &lt;classes&gt;
            &lt;class name=""com.settings.test.employee.PostObject"" /&gt;
            &lt;class name=""com.settings.test.employee.PostRecord"" /&gt;
            &lt;class name=""com.settings.test.employee.GetRecord"" /&gt;
            &lt;class name=""com.settings.test.employee.GetRecordByID"" /&gt;
            &lt;class name=""com.settings.test.employee.DeleteObject"" /&gt;
        &lt;/classes&gt;
    &lt;/test&gt;


&lt;/suite&gt;

</code></pre>

<p>In this approach unneccessary i am doing the same operation again and again which increases time of execution and code size.
I need to maintain this dependency at a class level not outside of the class, please suggest me some approach on how I can make it happen?.</p>
",https://stackoverflow.com/questions/57767831/avoid-dependency-in-integration-testing,"['testing', 'automation', 'testng']",39,False,0,1
integration test with SpringBoot with both MockMvc and PowerMock on static methods,"<p>Can someone provide any sample on this scenario combination.  I gave a sample snippet on the lines below, which is failing while trying to mock, intent is to combine both MockMVC with PowerMock</p>

<p>Create a spring Boot Test App for integration testing with</p>

<p>1) MockMvc for initiating a call from controller till end
2) PowerMock to Mock static methods in dependent class</p>

<pre class=""lang-java prettyprint-override""><code>@RunWith(SpringRunner.class)
@PowerMockRunnerDelegate(PowerMockRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@PrepareForTest(ClasswithStaticMethod.class)
public class DevLocationTest {


    @Autowired
    private MockMvc mockMvc;

    @MockBean
    ABCRepository abcRepository;

    @MockBean
    private ClasswithStaticMethod instance;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);        
    }


    @Test
    public void test() throws Exception {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set(""Authorization"","""");

        PowerMockito
                .when(abcRepository
                        .findByDevIdAndPropertyEventNameIn(devId,
                                Arrays.asList(eventName)))
                .thenReturn(devPropMapping);


        PowerMockito.mockStatic(ClasswithStaticMethod.class);
        Mockito.when(ClasswithStaticMethod.getInstance())
         .thenReturn(instance);
</code></pre>

<p>which is failing while trying to mock ""ClasswithStaticMethod"" with error like below, even though i have given @PrepareForTest(ClasswithStaticMethod.class) </p>

<p>The class com.XXX.services.config.ClasswithStaticMethod not prepared for test.
To prepare this class, add class to the '@PrepareForTest' annotation.</p>
",https://stackoverflow.com/questions/57496305/integration-test-with-springboot-with-both-mockmvc-and-powermock-on-static-metho,"['java', 'powermockito', 'spring-boot-test']",668,False,4,0
Launch and call methods on WPF app from unit test project,"<p>I would like to launch a WPF app and call methods on the ViewModel to control the app for the purpose of integration testing. Something like:</p>

<pre><code>    [Test]
    public void Test1()
        var application = new MyApp();
        application.InitializeComponent();
        application.Run();
</code></pre>

<p>(OK, this stops the test execution at this point, presumably passing control to the WPF app. Not sure how to deal with this. Launch in a separate thread or something?)</p>

<p>Then I'd like to be able to get and set values on the ViewModel, something like this:</p>

<pre><code>        application.MyViewModel.SomeProperty = ""A value!"";
</code></pre>

<p>The goal here is to test the WPF app in an integrated sense without resorting to WinAppDriver, White, CodedUI or anything messy like that. Ideas?</p>
",https://stackoverflow.com/questions/56999910/launch-and-call-methods-on-wpf-app-from-unit-test-project,"['c#', 'wpf', 'multithreading', 'integration-testing']",1578,True,3,2
Flutter Integration Test run/debug configuration in Android Studio,"<p>I am trying to run/debug some integration tests on a flutter project. my tests are running fine when I run ""flutter drive --target=test_driver/app.dart"" on my project.
I am trying to create a Debug configuration in my Android Studio as per following steps in the StackOverflow answer-
<a href=""https://stackoverflow.com/questions/53361718/how-to-automate-flutter-integration-testing-command/56286951#56286951"">How to automate Flutter Integration testing command?</a>
however, when I try to run the test with this configuration I get the following error</p>

<p>Any pointers about how this can be resolved?</p>

<p>Removing Break points and Flutter clean did not yield any results</p>

<pre><code>00:00 +0: Flutter Driver demo (setUpAll)
[info ] FlutterDriver: Connecting to Flutter application at http://127.0.0.1:55319/L_Bm--V4Kjg=/
[trace] FlutterDriver: Isolate found with number: 283666305
[trace] FlutterDriver: Isolate is not paused. Assuming application is ready.
00:00 +0 -1: Flutter Driver demo (setUpAll) [E]
  JSON-RPC error -32601 (method not found): Method not found
  package:json_rpc_2/src/client.dart 110:64          Client.sendRequest
  package:json_rpc_2/src/peer.dart 68:15             Peer.sendRequest
  package:vm_service_client/src/scope.dart 64:23     Scope.sendRequestRaw
</code></pre>

<p>Run Configuration is as follows<a href=""https://i.stack.imgur.com/UG4K5.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/UG4K5.png"" alt=""This is a AS_Run_config""></a></p>
",https://stackoverflow.com/questions/56308909/flutter-integration-test-run-debug-configuration-in-android-studio,"['android-studio', 'flutter', 'flutter-test']",3033,False,2,1
Specflow - What is the testing type which is covered as part of feature file/BDD,"<p>This might be a sort of stupid question, but still trying to find my understanding on BDD Specflow .
In my experience across Specflow - seen different companies using Specflow to capture scenarios/test across-</p>

<ul>
<li>Component level Testing </li>
<li>Functional Testing </li>
<li>System Integration Testing</li>
<li>Regression Testing</li>
</ul>

<p>So say for example my feature below for System Integration test coverage-</p>

<pre><code>Given An active account exists
When I  fill up a form &amp; submit a new investment (submitted but not approved)
Then Check the record inserted into a specific table
And new transaction displayed in Holdings report
And new transaction not displayed in cash balance report (as not yet approved)
</code></pre>

<p>In some companies they practice to break it down further-Component</p>

<p>Separate out above scenario to 2 features like below - </p>

<ol>
<li><p>One validating till inserted to database</p>

<pre><code>Given An active account exists
When I  fill up a form &amp; submit a new investment (submitted but not approved)
Then Check the record inserted into a specific table
</code></pre></li>
<li><p>The other Checking the reports</p>

<pre><code>Given A new Investment is recorded
        When we run the reports
        Then new transaction displayed in Holdings report
        And new transaction not displayed in cash balance report (as not yet approved)
</code></pre></li>
</ol>

<p>Which of the above is right way of writing Specflow features? Whats best practice?</p>
",https://stackoverflow.com/questions/57703488/specflow-what-is-the-testing-type-which-is-covered-as-part-of-feature-file-bdd,"['c#', 'automated-tests', 'bdd', 'specflow']",171,True,2,1
Unit testing curried functions,"<p>I am trying to figure out what the correct way of thinking about this is. I am trying to play around with some functional programming paradigm in python. I know it is not a functional language, but the concepts can translate.</p>

<p>Lets say I have a set of functions like:</p>

<pre><code>def add(x: int, y: int) -&gt; int:
  return x + y

add_one = partial(add, y=1)
add_two = partial(add, y=2)
add_three = partial(add, y=3)

fut = lambda x: add_three(add_one(add_two(x)))
</code></pre>

<p>The question is, do I unit test the function under test (<code>fut</code>)? And would I unit test <code>add_one</code>, <code>add_two</code> and <code>add_three</code>?</p>

<p>It is an implementation detail in my mind that <code>add_one</code> is a partial of <code>add</code>, but it feels weird to unit test if I have ""complete"" coverage of <code>add</code>. </p>

<p>Lets extend this for a minute and extend it towards a more realistic system.</p>

<pre><code>class Save(Protocol):
  def __call__(self, x: int): ...

def save_to_disk(x: int, file_name:str) -&gt; None:
  """"""
  Implementation of saving something to a disk
  """"""
  ...

save: Save = partial(save_to_disk, file_name=""random_file"")

def add(x: int, y: int) -&gt; int:
  return x + y

add_one = partial(add, y=1)

fut: Save = lambda x: save(add_one(x))
</code></pre>

<p>I now have a function that handles IO and some work generating the data to save. Do I unit test <code>fut</code> here? Do I assume that the currying is just implementation details and leave it for integration tests?</p>

<p>I feel a little lost on this one because in a OO world, I know how I could unit test some of this chaining with mocks but it seems backwards and against some of the functional paradigm and what I am actively trying to avoid by playing around with it.</p>

<p>My gut feeling right now is that the curried functions are integration testing and as long as everything is tested individually showing the components work than the chain I can leave for integration testing I can prove that the system as a whole works.</p>
",https://stackoverflow.com/questions/57262993/unit-testing-curried-functions,"['python', 'unit-testing', 'functional-programming']",695,False,2,2
RabbitMQ Java API queuePurge() method called on Qpid returns PurgeOK response with zero message count,"<p>I am integration testing a component that uses RabbitMQ client (amqp-client version 5.7.0) with an embedded Apache Qpid server object.</p>

<p>When calling the <code>Channel.queuePurge()</code> method, the queue is purged. I can verify that with the <code>getMessageCount()</code> method. But the <code>queuePurge()</code> method returns a <code>PurgeOk</code> object, which always has 0 message count. The documentation says the <code>PurgeOK</code> returns the message count that was purged.</p>

<pre><code>   //The queue has 1 message.
   int f = getMessageCount();
   //verify message count
   assertEquals(f, 1);
   //purge
   com.rabbitmq.client.AMQP.Queue.PurgeOk purgeOK= channel.queuePurge(queueName);
   //the next test fails.
   //Shouldn't the purgeOK have count 1, to denote that one message was purged?
   assertEquals(purgeOK.getMessageCount(), 1);
</code></pre>

<p>This happens only when testing with embedded Qpid server. The same test case with an actual running instance of Rabbit MQ is giving the expected.</p>

<p>Is this a known issue? Is there a better way to unit test the purge feature?</p>
",https://stackoverflow.com/questions/56264607/rabbitmq-java-api-queuepurge-method-called-on-qpid-returns-purgeok-response-wi,"['java', 'junit', 'rabbitmq', 'qpid']",262,True,1,1
@ExceptionHandler method not getting invoked when exception occurred,"<p>I have a global exception handler as below :- </p>

<pre><code>@ControllerAdvice
@RestController
public class GlobalExceptionHandler {

@ExceptionHandler(value= {HttpMessageNotReadableException.class})
    public final ResponseEntity&lt;ErrorDetails&gt; validationException(HttpMessageNotReadableException ex, WebRequest request) {

        System.out.println(""This was called."");
        if(ex.getCause() instanceof CsvRequiredFieldEmptyException){

            CsvRequiredFieldEmptyException csvExp = (CsvRequiredFieldEmptyException) ex.getCause();
            String exceptionDtls = csvExp.getMessage().concat("" "").concat("" at line number ""+csvExp.getLineNumber()+ "" in the csv filw."");
            ErrorDetails errorDetails = new ErrorDetails(LocalDate.now(),exceptionDtls, request.getDescription(false));
            return new ResponseEntity&lt;&gt;(errorDetails, HttpStatus.BAD_REQUEST);
        }

        return new ResponseEntity&lt;&gt;(null, HttpStatus.BAD_REQUEST);
    }
}
</code></pre>

<p>I am invoking the rest API by using TestRestTemplate for integration testing.</p>

<pre><code>ResponseEntity&lt;?&gt; response = restTemplate.exchange(ITestUtils.createURLWithPort(postUrlCsv,
                host,port ), HttpMethod.POST,listingDocEnt, String.class);

</code></pre>

<pre><code>@Test
    public void uploadListingCsvTest_Returns400BadReq_WhenCodeMissing() throws HttpMessageNotReadableException {

        // Step 1 : Create the Http entity object which contains the request body and headers.
        HttpEntity&lt;ListingList&gt; listingDocEnt = new HttpEntity&lt;ListingList&gt;(createTestDataForNewVehicleListingCodeMissing(),
                getHttpHeaderCsv());

        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));

        List&lt;HttpMessageConverter&lt;?&gt;&gt; csvMessgeonverter = new ArrayList&lt;&gt;();
        csvMessgeonverter.add(new CsvHttpMessageConverter&lt;&gt;());
        csvMessgeonverter.add(converter);
        TestRestTemplate restTemplate = new TestRestTemplate();
        restTemplate.getRestTemplate().setMessageConverters(csvMessgeonverter);

        ResponseEntity&lt;?&gt; response = restTemplate.exchange(ITestUtils.createURLWithPort(postUrlCsv,
                host,port ), HttpMethod.POST,listingDocEnt, String.class);

        // Check if the response is not null and the http status code is - 201 Created.
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST,response.getStatusCode());

    }
</code></pre>

<p>My rest API has custom HttpMessageConverter which is as below which converts the input request csv to java object in the rest controller. This custom message converter has a method readInternal which throws an exception HttpMessageNotReadableException , but still the exception handler method 'validationException' is not getting invoked. The Junit simply breaks and fails. </p>

<pre><code>public class CsvHttpMessageConverter&lt;T, L extends ListParam&lt;T&gt;&gt;
          extends AbstractHttpMessageConverter&lt;L&gt; {

    public CsvHttpMessageConverter () {
        super(new MediaType(""text"", ""csv""));
    }

    @Override
    protected boolean supports (Class&lt;?&gt; clazz) {
        return ListParam.class.isAssignableFrom(clazz);
    }

    @Override
    protected L readInternal (Class&lt;? extends L&gt; clazz,HttpInputMessage inputMessage)
              throws IOException, HttpMessageNotReadableException {

        HeaderColumnNameMappingStrategy&lt;T&gt; strategy = new HeaderColumnNameMappingStrategy&lt;&gt;();
        Class&lt;T&gt; t = toBeanType(clazz.getGenericSuperclass());
        strategy.setType(t);

        CSVReader csv = new CSVReader(new InputStreamReader(inputMessage.getBody()));
        CsvToBean&lt;T&gt; csvToBean = new CsvToBean&lt;&gt;();

        List&lt;T&gt; beanList = null;

        try {
            beanList = csvToBean.parse(strategy, csv);

        } catch(Exception exception){
            throw new HttpMessageNotReadableException(""Exception while parsing the CSV file."",exception.getCause());
        }

        try {
            L l = clazz.newInstance();
            l.setList(beanList);
            return l;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings(""unchecked"")
    @Override
    protected void writeInternal (L l, HttpOutputMessage outputMessage)
              throws IOException, HttpMessageNotWritableException {

        HeaderColumnNameMappingStrategy&lt;T&gt; strategy = new HeaderColumnNameMappingStrategy&lt;&gt;();
        strategy.setType(toBeanType(l.getClass().getGenericSuperclass()));

        OutputStreamWriter outputStream = new OutputStreamWriter(outputMessage.getBody());
        StatefulBeanToCsv&lt;T&gt; beanToCsv =
                  new StatefulBeanToCsvBuilder(outputStream)
                            .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                            .withMappingStrategy(strategy)
                            .build();

            try {
                beanToCsv.write(l.getList());
            } catch (CsvDataTypeMismatchException e) {
                throw new HttpMessageNotWritableException(""Exception while parsing the CSV file."",e);
            } catch (CsvRequiredFieldEmptyException e) {
                throw new HttpMessageNotWritableException(""Exception while parsing the CSV file."",e);
            }
            outputStream.close();

    }

    @SuppressWarnings(""unchecked"")
    private Class&lt;T&gt; toBeanType (Type type) {
        return (Class&lt;T&gt;) ((ParameterizedType) type).getActualTypeArguments()[0];
    }
</code></pre>

<p>Is there a way that when invoking a spring rest API using TestRestTemplate we can invoke the exception handler method when there is an exception?</p>
",https://stackoverflow.com/questions/56327596/exceptionhandler-method-not-getting-invoked-when-exception-occurred,"['java', 'rest', 'spring-boot', 'spring-test']",2085,True,1,1
Is there any alternative to dynamic_cast in c++?,"<p>I would like to know this in case RTTI is disabled in some compiler environment.</p>

<p>Use case: </p>

<p>I used this in my code and it worked on my machine but during integration testing the code failed to run properly, rather crashed.</p>

<p>I supposed it would have returned null in case RTTI is not there which was handled in my code but the behavior was unexpected. </p>

<p>What should I have checked to terminate it elegantly?</p>

<p>Also, when I used a wrapper of dynamic_cast (defined in our inhouse framework), it worked fine. What kind of  implementation would that wrapper have to fulfill this requirement?</p>
",https://stackoverflow.com/questions/58547025/is-there-any-alternative-to-dynamic-cast-in-c,"['c++', 'inheritance', 'downcast']",101,False,1,1
Problem terminating my app with an exit code,"<p>After my app runs and completes its work, I want it to terminate and return an exit code back to the operating system. This can be done using:</p>

<pre><code>System.exit(exitCode)
</code></pre>

<p>The only problem with this is that Android will then attempt to restart the app again after it terminates it. I want to avoid this. The reason I want to terminate the app with an exit code is to allow for continuous integration testing which will allow external apps to determine whether the app succeeded or failed.</p>

<p>How can I terminate the app with an exit code but prevent it from restarting?</p>
",https://stackoverflow.com/questions/59421618/problem-terminating-my-app-with-an-exit-code,['android'],66,True,0,1
Shutdown Hook Corda integration testing,"<p>I have the following <a href=""https://github.com/altfatterz/learning-corda/blob/master/workflows/iou-workflow/src/main/kotlin/com/example/flows/IOUFlow.kt"" rel=""nofollow noreferrer"">Corda service</a>. It starts up a Jetty Server</p>

<pre><code>@CordaService
class IOUService(private val serviceHub: AppServiceHub): SingletonSerializeAsToken() {

    init {
        val port = serviceHub.myInfo.addresses.first().port - 1002
        log.println(""IOUService init was called..."")
        log.println(""Port: $port"")

        val jettyServer = JettyServer()
        jettyServer.start(port)
    }
}
</code></pre>

<p>My problem is how to release the stared Jetty port when running integration tests. Here are two example test (basically the same test twice to illustrate the problem):</p>

<pre><code>    @Test
    fun `node test`() = withDriver {
        val (partyAHandle, partyBHandle) = startNodes(bankA, bankB)
        assertEquals(bankB.name, partyAHandle.resolveName(bankB.name))
        assertEquals(bankA.name, partyBHandle.resolveName(bankA.name))
    }

    @Test
    fun `node test2`() = withDriver {
        val (partyAHandle, partyBHandle) = startNodes(bankA, bankB)
        assertEquals(bankB.name, partyAHandle.resolveName(bankB.name))
        assertEquals(bankA.name, partyBHandle.resolveName(bankA.name))
    }
</code></pre>

<p>The first test will start up 3 nodes: one notary, BankA and BankB nodes with the following details:</p>

<pre><code>Notary:
Advertised P2P messaging addresses      : localhost:10000
RPC connection address                  : localhost:10001
RPC admin connection address            : localhost:10002
Jetty Port: 8998

BankA:
Advertised P2P messaging addresses      : localhost:10004
RPC connection address                  : localhost:10005
RPC admin connection address            : localhost:10006
Jetty Port: 9002

BankB:
Advertised P2P messaging addresses      : localhost:10008
RPC connection address                  : localhost:10009
RPC admin connection address            : localhost:10010
Jetty Port: 9006
</code></pre>

<p>Unfortunately the second test will fails since the Jetty ports are still bound:</p>

<pre><code>[ERROR] 14:22:04,825 [driver-pool-thread-0] internal.Node.installCordaServices - Corda service com.example.flows.IOUService failed to instantiate. Reason was: Address already in use [errorCode=1pryyp4, moreInformationAt=https://errors.corda.net/OS/4.1/1pryyp4]
 java.io.IOException: Failed to bind to 0.0.0.0/0.0.0.0:9006
</code></pre>

<p>How to register a shutdown hook during integration testing in order to shut down the Jetty servers?</p>

<p>The example code can be found here:</p>

<p><a href=""https://github.com/altfatterz/learning-corda"" rel=""nofollow noreferrer"">https://github.com/altfatterz/learning-corda</a></p>
",https://stackoverflow.com/questions/59214090/shutdown-hook-corda-integration-testing,['corda'],73,False,0,1
Entity Framework returns empty data for a local database that shows data in SQL Server Object Explorer,"<p>I am writing Integration tests for a WPF application and I'm using a local database that is placed inside the solution for integration testing and this database has data inside it.</p>

<p>When I read data from this database after connecting it to SQL Server, it returns valid data, but once I go back to the application, add its connection string and try to get data, the code returns an empty set. I'm on a tight deadline and I don't know why this is happening.</p>

<p>Any help will be greatly appreciated.</p>

<p>Simple code is: </p>

<pre><code>var xsystem = context.Species.ToList();
</code></pre>

<p>My connection string is:</p>

<pre><code>&lt;add name=""MaxDatabase"" 
     connectionString=""Data Source=(LocalDb)\ProjectsV13;Initial Catalog=Catalog=MaxLocalEmbeded;Integrated Security=SSPI"" 
     providerName=""System.Data.SqlClient"" /&gt;
</code></pre>
",https://stackoverflow.com/questions/58212258/entity-framework-returns-empty-data-for-a-local-database-that-shows-data-in-sql,"['c#', 'sql-server', 'wpf', 'localdb']",376,True,0,1
Laravel Virgin: Disable/mock database connection when testing model mutators that utilize relationships,"<p>I have the following models:</p>

<ul>
<li><code>Grid.php</code></li>
</ul>

<pre><code>namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Model\Rover;

class Grid extends Model
{
    /**
     * Table Name
     */
    protected $table='grid';

    public function rovers()
    {
        return $this-&gt;hasMany(Rover::class);
    }
}
</code></pre>

<ul>
<li><code>Rover.php</code></li>
</ul>

<pre><code>namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Model\Grid;

class Rover extends Model
{

    /**
     * Table Name
     */
    protected $table='rover';

    public function grid()
    {
        return $this-&gt;belongsTo(Grid::class);
    }

    public function setGridPosXValue($value)
    {
        $Grid = $this-&gt;grid()-&gt;first();
        $width = $Grid-&gt;width;
        if($value &lt; 0 || $value &gt; $width){
            throw new \InvalidArgumentException(""X is out of grid bounds"");
        }

        $this-&gt;attributes['x']=$value;
    }

    public function setGridPosYValue($value)
    {
        $Grid = $this-&gt;grid()-&gt;first();
        $height = $Grid-&gt;height;

        if($value &lt; 0 || $value &gt; $height){
            throw new \InvalidArgumentException(""Y is out of grid bounds"");
        }

        $this-&gt;attributes['y']=$value;
    }
}

</code></pre>

<p>And I want to test the Rover's mutator with theese tests:</p>

<pre><code>namespace Tests\Unit;

use Tests\TestCase;
use App\Model\Rover;
use App\Model\Grid;
use Mockery;

define(""TEST_ROVEL_SUCCESS_VAL"",3);
define(""TEST_ROVEL_NEGATIVE_VAL"",-1);


class RoverModelTest extends TestCase
{
    public function testSetGridPosXValueThrowsExceptionWhenNegative(){
        $this-&gt;markTestSkipped('To be implemented');
    }

    public function testSetGridPosXValueThrowsExceptionWhenOverWidth(){
        $rover = new Rover();
        $grid = new Grid();
        $grid-&gt;width=5;
        $grid-&gt;height=5;
        $rover-&gt;grid=$grid;

        $this-&gt;expectException(\InvalidArgumentException::class);
        $rover-&gt;setGridPosXValue(TEST_ROVEL_NEGATIVE_VAL);

    }

    public function testSetGridPosXValueThorwsExceptionOnNormal(){
        $rover = new Rover();
        $grid = new Grid();

        $grid-&gt;width=5;
        $grid-&gt;height=5;

        $rover-&gt;grid=$grid;
        try {
            $rover-&gt;setGridPosXValue(TEST_ROVEL_SUCCESS_VAL);
            $this-&gt;assertEquals($rover-&gt;x,TEST_ROVEL_SUCCESS_VAL);
        } catch(\Exception $e) {
            $this-&gt;fail(""No exception should be thrown when setting a correct value."");
        }
    }
}
</code></pre>

<p>So when I run the tests I get the following error:</p>

<pre><code>PHPUnit 7.5.13 by Sebastian Bergmann and contributors.

SFF                                                                 3 / 3 (100%)

Time: 125 ms, Memory: 18.00 MB

There were 2 failures:

1) Tests\Unit\RoverModelTest::testSetGridPosXValueThrowsExceptionWhenOverWidth
Failed asserting that exception of type ""Illuminate\Database\QueryException"" matches expected exception ""InvalidArgumentException"". Message was: ""SQLSTATE[08006] [7] FATAL:  password authentication failed for user ""laravel"" (SQL: select * from ""grid"" where ""grid"".""id"" is null limit 1)"" at
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:46
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/PostgresConnector.php:33
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/ConnectionFactory.php:182
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:918
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:943
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:399
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:325
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:657
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:624
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:333
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2124
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2112
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2598
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2113
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:521
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:505
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Concerns/BuildsQueries.php:77
/var/www/html/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:23
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php:386
/var/www/html/app/Model/Rover.php:23
/var/www/html/tests/Unit/RoverModelTest.php:28
.

2) Tests\Unit\RoverModelTest::testSetGridPosXValueThorwsExceptionOnNormal
No exception should be thrown when setting a correct value.

/var/www/html/tests/Unit/RoverModelTest.php:44

FAILURES!
Tests: 3, Assertions: 2, Failures: 2, Skipped: 1.

</code></pre>

<p>Meaning that the tests hit a misconfigured database connection.</p>

<p>So how I can set a ""fake"" database connection in order not to use any database at all when testing? The reason why is because I want to do a unit testing instead of an integration testing.</p>

<p>In my case I want the code not to hit the db connection and test the logic that the mutator has without writing into the database at all.</p>
",https://stackoverflow.com/questions/56734032/laravel-virgin-disable-mock-database-connection-when-testing-model-mutators-tha,"['php', 'laravel', 'unit-testing', 'phpunit']",650,True,0,1
Azure AD Auth on LocalDB,"<p>I presume that LocalDB does not support Azure AD auth, as I receive the following error message:</p>

<pre><code>CREATE USER [myuser] FROM EXTERNAL PROVIDER;
</code></pre>

<blockquote>
  <p>Incorrect syntax near 'PROVIDER'.</p>
</blockquote>

<p>(I'm attempting to create a Local DB for integration testing from the same DacPac).</p>

<p>However I cannot find any documentation that suggests explicitly that LocalDB (nor SQL Express) does not support Azure AD Auth.</p>

<p>Experience has found that just because it's not documented doesn't mean it's not possible.</p>

<p>In Azure SQL Server, you activate AD auth by assigning an Azure AD user to be an administrator, which can be done via AzureRM powershell module. Is there an equivalent none azurerm  way of achieving the same thing?</p>
",https://stackoverflow.com/questions/54215902/azure-ad-auth-on-localdb,"['azure-active-directory', 'azure-sql-database', 'localdb']",301,True,2,1
Produce SocketTimeoutException in Junit Tests in Netty,"<p><strong>Problem</strong> </p>

<p>I need to test a scenario where my Netty Server will throw SocketTimeoutExceptions causing the client to retry on those failures and eventually fail.I want to achieve this with integration testing in Junit Java</p>

<p><strong>Things I tried</strong></p>

<p>I tried exploiting SO_TIMEOUT = 0 for both option and child option and at the same time keeping SO_KEEPALIVE = false and SO_BACKLOG = 0 . Also I reduced CONNECT_TIMEOUT_MILLIS to 0. But nothing has worked. Client is still able to connect to the server.**</p>

<p><strong>Sample code below</strong> </p>

<pre><code> ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(NativeTransportUtil.newEventLoopGroup(),       NativeTransportUtil.newEventLoopGroup())
.channel(NativeTransportUtil.serverSocketChannelClass())
                    .option(ChannelOption.SO_BACKLOG, 0)
                    .childOption(ChannelOption.SO_KEEPALIVE, false)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 0)
                    .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 0)
                    .option(ChannelOption.SO_BACKLOG, 0)
                    .childOption(ChannelOption.SO_BACKLOG, 0)
                    .option(ChannelOption.SO_TIMEOUT, 0)
                    .childOption(ChannelOption.SO_TIMEOUT, 0)
                    .childHandler(new NewConnectionInitializer());

            bootstrap.bind(port).syncUninterruptibly();

            client.sendSync(request);
</code></pre>

<p><strong>Results</strong> </p>

<p>Actual Result : The above code results in a successful connection from the client to the server. </p>

<p>ExpectedResult : I want the server to throw out SocketTimeoutException.</p>
",https://stackoverflow.com/questions/56032022/produce-sockettimeoutexception-in-junit-tests-in-netty,"['netty', 'socket-timeout-exception']",290,False,2,0
Why does basicReject does not work with Apache Qpid?,"<p>I'm using <code>qpid-broker</code> for integration testing my <code>spring-boot-start-amqp</code> application which uses <code>basicGet</code> (autoAck=false), <code>basicAck</code> and <code>basicReject</code> for handling the messages. <code>basicReject</code> (with requeue=false) works fine with my external <code>rabbitmq</code> instance but doesn't work with the <code>qpid-broker</code>.</p>

<p>I have tested my code with an external RabbitMQ instance where everything works fine but with the embedded Apache Qpid server the test fails because <code>basicReject</code> is not working properly.</p>

<p>Getting the message and rejecting it:</p>

<pre><code>rabbitTemplate.execute {
    val response = it.basicGet(config.queueName, false)
    it.basicReject(response.envelope.deliveryTag, false)
}
</code></pre>

<p>Check if the message is still in the queue:</p>

<pre><code>rabbitTemplate.execute {
    val response = it.basicGet(config.queueName, false)
    Assertions.assertThat(response).isNull()
}
</code></pre>

<p>My Qpid config:</p>

<pre><code>{
  ""name"": ""EmbeddedBroker"",
  ""modelVersion"": ""7.0"",
  ""authenticationproviders"": [
    {
      ""name"": ""password"",
      ""type"": ""Plain"",
      ""secureOnlyMechanisms"": [],
      ""users"": [
        {
          ""name"": ""guest"",
          ""password"": ""guest"",
          ""type"": ""managed""
        }
      ]
    }
  ],
  ""ports"": [
    {
      ""name"": ""AMQP"",
      ""port"": ""${qpid.amqp_port}"",
      ""protocols"": [ ""AMQP_0_9_1"" ],
      ""authenticationProvider"": ""password"",
      ""virtualhostaliases"": [
        {
          ""name"": ""defaultAlias"",
          ""type"": ""defaultAlias""
        }
      ]
    }
  ],
  ""virtualhostnodes"": [
    {
      ""name"": ""default"",
      ""defaultVirtualHostNode"": ""true"",
      ""type"": ""Memory"",
      ""virtualHostInitialConfiguration"": ""{\""type\"": \""Memory\"" }""
    }
  ]
}
</code></pre>

<p>Why does <code>basicReject</code> work fine with my RabbitMQ instance but doesn't work properly with the Apache Qpid embedded broker?</p>

<p>Edit: My solution was to move away from qpid and use a <a href=""https://www.testcontainers.org/modules/rabbitmq/"" rel=""nofollow noreferrer"">RabbitMQ Testcontainer</a>. </p>
",https://stackoverflow.com/questions/57873395/why-does-basicreject-does-not-work-with-apache-qpid,"['spring', 'kotlin', 'rabbitmq', 'amqp', 'qpid']",113,False,1,0
Integration test in Spring Boot using in-memory database,"<p>I am doing integration testing using in-memory database(H2) so that I can populate the repository with known values, initialize the service implementation with the repo. Here is my test class</p>

<pre><code>@RunWith(SpringRunner.class)
@TestPropertySource(""classpath:application-test.properties"")
@SpringBootTest
public class ManufacturerServiceH2ImplTest {

    @Autowired
    private ManufacturerRepository manufacturerRepository;

    @Autowired
    ManufacturerServiceImpl manufacturerServiceImpl;


    @Test
    public void testManufacturerCreate() throws Exception {

        //Create Manufacturer
        Manufacturer manufacturer = new Manufacturer();
        manufacturer.setManufacturerId(""SSS"");
        manufacturer.setManufacturerName(""WWW"");

        //Save Manufacturer in Inmemory 
        Manufacturer manufacturerInMemory = manufacturerRepository.save(manufacturer);

        //Service Implementation
        StResponse createManufacturer = manufacturerServiceImpl.createManufacturer(manufacturer);

        //Compare the result

    }

}
</code></pre>

<p>The service implementation should use the data saved in the in-memory database and perform few business validation. The issue which I am facing here is that the service implementation is actually considering the manufacturerRepository instance which is pointing to the actual db(postgres in this case) rather than pointing to the in memory database. Any help of how to inject the manufacturerRepository instance into manufacturerServiceImpl service implementation that points out to inmemory database</p>
",https://stackoverflow.com/questions/57098086/integration-test-in-spring-boot-using-in-memory-database,"['java', 'spring', 'spring-boot', 'jpa', 'junit']",11429,True,1,2
"express test router app.use(&quot;v1/books&quot;, bookRouter)","<p>I am not sure about how to test my booksRouter.
Instead of repeating in the router ""/v1/books"" in front of each route, I'm using the convenient following syntax </p>

<pre class=""lang-js prettyprint-override""><code>app.use(""v1/books"", booksRouter);
</code></pre>

<p>But since there is no prefix anymore in my router, I am not sure about how to test the full route path.</p>

<p>Here is an extract from my app.ts</p>

<pre class=""lang-js prettyprint-override""><code>import express from ""express"";
import booksRouter from ""./books.router"";

const app = express();
app.use(""v1/books"", booksRouter);

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

<p>And here is an extract from my router test file</p>

<pre class=""lang-js prettyprint-override""><code>import request from ""supertest"";
import app from ""../app"";
import bookRouter from ""../books.router"";
import BookController from ""../controllers/book.controller"";

describe(""GET /:id"", () =&gt; {
  it(""should return book from an existing id"", async () =&gt; {
    const newBook = await BookController.createBook({
      price: 100,
      title: ""Great book"",
    });
    //HERE IS THE ROUTE : /myBookId
    //But in fact it's /v1/books/myBookId
    const response = await request(app).get(`/${newBook._id}`);
    expect(response.status).toBe(200);
    expect(newBook._id.equals(response.body._id)).toBe(true);
    expect(response.body.price).toEqual(newBook.price);
    expect(response.body.title).toEqual(newBook.title);
  });
});
</code></pre>

<p>One of my solution is to add the prefix in each test but I don't want to have a strong coupling here.</p>

<p>What do you think ? I have the feeling that it's a mix between unit and integration testing</p>
",https://stackoverflow.com/questions/57414670/express-test-router-app-usev1-books-bookrouter,"['node.js', 'unit-testing', 'express', 'integration-testing']",34,False,1,0
Integration Testing Spring boot application JSON Assert,"<p>I have spring boot application was trying to write Integration testing but when i ht the in memory DB i get one value from that but when do ASSERT TO MATCH THE PARAMETER VALUES i AM  NOT ABLE TO COMPARE THE SIZE AND VALUES </p>

<p>these how the response when i hit the api in Postman </p>

<pre><code>{
    ""continuationToken"": ""09/07/19 05:21 PM"",
    ""permit"": [
        {
            ""expiry"": null,
            ""activation"": ""2019-07-01T06:00:00.000+0000"",
            ""permitId"": ""C8S43N5"",
            ""plateNumber"": ""ERT1234"",
            ""plateState"": ""AB""
        },
        {
            ""expiry"": null,
            ""activation"": ""2018-12-17T22:04:13.947+0000"",
            ""permitId"": ""CGW3TNF"",
            ""plateNumber"": ""FDF"",
            ""plateState"": ""AB""
        }
  ]
}
</code></pre>

<pre><code>        Assert.assertThat(response.getStatusCode(), Matchers.equalTo(HttpStatus.OK));
        String jsonBody = response.getBody();
        Assert.assertThat(jsonBody, JsonPathMatchers.hasJsonPath(""$[0].expiry"", Matchers.equalTo(""2080-06-26T06:00:00.000+0000"")));
        Assert.assertThat(jsonBody, JsonPathMatchers.hasJsonPath(""$[0].activation"", Matchers.equalTo(""2019-06-26T22:33:14.849+0000"")));
        Assert.assertThat(jsonBody, JsonPathMatchers.hasJsonPath(""$[0].permitId"", Matchers.equalTo(""CS383UA"")));
        Assert.assertThat(jsonBody, JsonPathMatchers.hasJsonPath(""$[0].plateNumber"", Matchers.equalTo(""VGZ05"")));
        Assert.assertThat(jsonBody, JsonPathMatchers.hasJsonPath(""$[0].plateState"", Matchers.equalTo(""AB"")));
</code></pre>

<blockquote>
  <p>java.lang.AssertionError:  Expected: is json with json path
  ""$[0]['expiry']"" evaluated to ""2080-06-26T06:00:00.000+0000""
       but: json path ""$[0]['expiry']"" was not found in &lt;{continuationToken=09/07/19 05:31 PM,
  permit=[{""expiry"":""2080-06-26T06:00:00.000+0000"",""activation"":""2019-06-26T22:33:14.849+0000"",""permitId"":""CS383UA"",""plateNumber"":""VGZ05"",""plateState"":""AB""}]}></p>
</blockquote>
",https://stackoverflow.com/questions/56958031/integration-testing-spring-boot-application-json-assert,['java'],799,True,1,1
Dask distributed.utils_test.client doesn&#39;t inherit parent process environment variables?,"<p>I am using pytest to test my dask workflows. I have a specific workflow, <code>ingest_l0_files</code> that uses a <code>Client</code> to map out tasks to workers. During testing, I need to artificially set a directory path that is set in an environment variable called <code>CURRENT_RUN_LOG_PATH</code>. Importantly, this setup works flawlessly during integration testing and real runs; I set the environment variable in my driver script and all my workers have access to it (because they are spawned from thy master process presumably). However, in my pytest, the (artificially set) environment variable is unavailable to the workers. Why? Perhaps I can tell my <code>utils_test.client</code> to re-initialize its environment and then pass it to its workers?</p>

<pre><code>from distributed.utils_test import client
def test_ingest_l0_files(client, clean_database_fixture, tmpdir):
    """"""Test the workflow function `ingest_l0_files`""""""
    os.putenv('CURRENT_RUN_LOG_PATH', f'{tmpdir}')
    get_config('CURRENT_RUN_LOG_PATH')
    client = client()
    unique_obs = workflow.ingest_l0_files([L0_ALL_FILE, L0_LPT_FILE], client)
    assert len(unique_obs) == 20
    os.unsetenv('CURRENT_RUN_LOG_PATH')
</code></pre>
",https://stackoverflow.com/questions/58651522/dask-distributed-utils-test-client-doesnt-inherit-parent-process-environment-va,"['pytest', 'dask', 'dask-distributed']",201,False,1,1
System.OperationCanceledException : dotnet Core 2.1,"<p>I am trying to setup a xunit project for my integration testing, it calls our local test server instead of the local host .</p>

<p>Whenever I run my project locally it is working fine .</p>

<p>But when I tried to integrate with circleCI I am getting below exception</p>

<pre><code>Starting test execution, please wait...
</code></pre>

<p>Hello
[xUnit.net 00:01:41.45]     IntegrationTesting.Test1.LTest1 [FAIL]
Failed   IntegrationTesting.Test1.LTest1
Error Message:
 System.OperationCanceledException : The operation was canceled.
Stack Trace:
   at System.Net.Http.HttpClient.HandleFinishSendAsyncError(Exception e, CancellationTokenSource cts)
   at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
   at IntegrationTesting.Test1.LTest1() in /root/project/Testing/Test1.cs:line 29
--- End of stack trace from previous location where exception was thrown ---</p>

<p>Here is the sample code </p>

<pre><code> [Fact]
 public async Task LTest1()
{


     _client = new HttpClient();

    _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(""Bearer"",""asdsada"");

    Console.WriteLine(""Hello"");

    var response = await _client.GetAsync(""https://testServer/api/work"");

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

    Console.WriteLine(testdata);

}
</code></pre>
",https://stackoverflow.com/questions/58072387/system-operationcanceledexception-dotnet-core-2-1,"['.net-core', 'circleci']",308,False,1,0
How to do integration testing in Flutter?,"<p>I want to do integration testing in Flutter. The tutorial I follow gives the following procedure:</p>

<ol>
<li>Add the flutter_driver package to pubspec:</li>
</ol>

<pre><code>dev_dependencies:
flutter_driver:
sdk: flutter
</code></pre>

<ol start=""2"">
<li>Enable the Flutter driver extension and add a call to
the enableFlutterDriverExtension() function in main.dart.</li>
<li>Run the integration test by using the flutter drive command:
flutter drive --target=my_app/test_driver/my_test.dart</li>
</ol>

<p>My problem is with understanding step 2. It's not clear to me where in Android Studio do you enable the driver extension and where exactly in main.dart do you call the function enableFlutterDriveExtension().</p>

<p>I also have problems with the third step. After running the said command, it says in my terminal that </p>

<pre><code>Error: The Flutter directory is not a clone of the GitHub project.
       The flutter tool requires Git in order to operate properly;
       to set up Flutter, run the following command:
       git clone -b stable https://github.com/flutter/flutter.git
</code></pre>
",https://stackoverflow.com/questions/56104378/how-to-do-integration-testing-in-flutter,"['flutter', 'flutter-dependencies']",2952,True,1,2
Integration testing issue on inserting in data base,"<p>I am very new to testing and I'm playing right now with integration testing.</p>

<p>I'm writing this piece of code to insert a new entry in the database and test the before and after arrays. But for some reason, it seems to return false and I'm not sure if I'm doing everything right:</p>

<p>Here is the JUnit Class:</p>

<pre><code>public class TestJunit {

private Question question;
private QuestionDAO questionDaoMock;

protected void setUp(){
    question = new Question();
    questionDaoMock = mock(QuestionDAO.class);  
    question.setQuestiondao(questionDaoMock);
}

@Test
public void testAdd() {
    questionDaoMock.openCurrentSessionwithTransaction();
    List&lt;Question&gt; currentQuestions = new ArrayList&lt;Question&gt;();
    currentQuestions = questionDaoMock.findAll();

    question.setChapterId(64);
    question.setText(""Rezultatul calculului 54*2-76:2 este..."");

    questionDaoMock.persist(question);
    currentQuestions.add(question);

    List&lt;Question&gt; newQuestions = new ArrayList&lt;Question&gt;();
    newQuestions = questionDaoMock.findAll();

    questionDaoMock.closeCurrentSessionwithTransaction();

    assertEquals(currentQuestions.size(), newQuestions.size());
}
}
</code></pre>

<p>This is my TestRunner:</p>

<pre><code>public class TestRunner {
   public static void main(String[] args) {
  Result result = JUnitCore.runClasses(TestJunit.class);

  for (Failure failure : result.getFailures()) {
     System.out.println(failure.toString());
  }

  System.out.println(result.wasSuccessful());
   }
}   
</code></pre>

<p>I tried already the code in the testAdd() function separately in the main function just to check if insertion works and it does. I compared the arrays size and it works as well when I'm running from main method. What am I doing wrong?</p>
",https://stackoverflow.com/questions/56793911/integration-testing-issue-on-inserting-in-data-base,"['java', 'hibernate', 'mockito', 'integration-testing']",374,True,0,3
Running two containers in a single pod via kubectl run does not terminate the pod with two containers,"<p>Trying to run a two docker containers in one kubernetes pod. The problem we face is that we have 2 images/containers in a Kubernetes pod whereas we used to have 1 image for this pod previously where it was working perfectly and shutting down the pod gracefully. Now the problem is that with 2 images or containers within the same pod both images are not shutting down at the same time gracefully.</p>

<p>We are doing integration testing of our container against the database which is MongoDB, our container terminates but MongoDB fails to terminate here and continues running</p>

<pre><code>while getopts n:c:l:i:d:t: option
do
case ""${option}""
in
n) Company_NAMESPACE=$OPTARG;;
c) Company_CONFIG=$OPTARG;;
l) Company_LICENSE=$OPTARG;;
i) Company_IMAGE=$OPTARG;;
d) Company_CONTAINER_NAME=$OPTARG;;
t) Company_TOKEN=$OPTARG;;
esac
done

kubectl run $Company_CONTAINER_NAME -n $Company_NAMESPACE --restart=Never --overrides='
{
  ""apiVersion"": ""v1"",
  ""spec"": {
    ""imagePullSecrets"": [
      {
        ""name"": ""Company-regsecret""
      }
    ],
    ""initContainers"": [
      {
        ""name"": ""copy-configs"",
        ""image"": ""busybox"",
        ""command"": [""sh"", ""-c"", ""cp /tmp/Company-config-volume/server/* /tmp/ng-rt/config/server/ 2&gt;/dev/null || true; cp /tmp/Company-license-volume/licenses/* /tmp/ng-rt/config/licenses 2&gt;/dev/null || true""],
        ""volumeMounts"": [
          {
            ""name"": ""Company-config-volume"",
            ""mountPath"": ""mount_path""
          },
          {
            ""name"": ""'$Company_CONFIG'"",
            ""mountPath"": ""mount_path""
          },
          {
            ""name"": ""Company-license-volume"",
            ""mountPath"": ""mount_path""
          },
          {
            ""name"": ""'$Company_LICENSE'"",
            ""mountPath"": ""mount_path""
          }
        ]
      }
    ],
    ""containers"": [
    {
         ""name"": ""mongodb-test"",
          ""image"": ""mongo:3.6.8"",
          ""command"": [
              ""numactl"",
              ""--interleave=all"",
              ""mongod"",
              ""--wiredTigerCacheSizeGB"",
            ""0.1"",
            ""--replSet"",
            ""MainRepSet"",
            ""--bind_ip_all""
        ],
        ""ports"": [{
            ""containerPort"": 27017
        }],
        ""readinessProbe"": {
            ""exec"": {
                ""command"": [""mongo"", ""--eval"", ""rs.initiate()""]
            }
        },
        ""terminationGracePeriodSeconds"": 10
    },
      {
        ""env"": [
          {
            ""name"": ""AWS_ACCESS_KEY_ID"",
            ""valueFrom"": {
              ""secretKeyRef"": {
                ""key"": ""AWS_ACCESS_KEY_ID"",
                ""name"": ""aws-secrets""
              }
            }
          },
          {
            ""name"": ""AWS_SECRET_ACCESS_KEY"",
            ""valueFrom"": {
              ""secretKeyRef"": {
                ""key"": ""AWS_SECRET_ACCESS_KEY"",
                ""name"": ""aws-secrets""
              }
            }
          },
          {
            ""name"": ""AWS_REGION"",
            ""valueFrom"": {
              ""secretKeyRef"": {
                ""key"": ""AWS_REGION"",
                ""name"": ""aws-secrets""
              }
            }
          },
          {
            ""name"": ""BUILD_ID"",
            ""valueFrom"": {
              ""configMapKeyRef"": {
                ""key"": ""BUILD_ID"",
                ""name"": ""config""
              }
            }
          }
        ],
        ""command"": [
          ""sh"",
          ""-c"",
          ""mkdir -p mount_path 2\u003e/dev/null &amp;&amp; npm test --skipConnectivityTestRethinkDB""
        ],
        ""name"": ""'$Company_CONTAINER_NAME'"",
        ""image"": ""'$Company_IMAGE'"",
        ""volumeMounts"": [
          {
            ""mountPath"": ""mount_path"",
            ""name"": ""'$Company_CONFIG'""
          },
          {
            ""mountPath"": ""mount_path"",
            ""name"": ""'$Company_LICENSE'""
          }
        ]
      }
    ],
    ""volumes"": [
      {
        ""name"": ""Company-config-volume"",
        ""configMap"": {
          ""name"": ""'$Company_CONFIG'""
        }
      },
      {
        ""name"": ""'$Company_CONFIG'"",
        ""emptyDir"": {}
      },
      {
        ""name"": ""Company-license-volume"",
        ""configMap"": {
          ""name"": ""'$Company_LICENSE'""
        }
      },
      {
        ""name"": ""'$Company_LICENSE'"",
        ""emptyDir"": {}
      }
    ]
  }
}
' --image=$Company_IMAGE -ti --rm --token=$Company_TOKEN
</code></pre>

<pre><code>{
  ""kind"": ""Pod"",
  ""apiVersion"": ""v1"",
  ""metadata"": {
    ""name"": ""test-dev-58663"",
    ""namespace"": ""d-int-company-dev-v2"",
    ""labels"": {
      ""run"": ""test-dev-58663""
    },
    ""annotations"": {
      ""kubernetes.io/psp"": ""nfs-provisioner""
    }
  },
  ""spec"": {
    ""volumes"": [
      {
        ""name"": ""company-config-volume"",
        ""configMap"": {
          ""name"": ""test-core"",
          ""defaultMode"": 420
        }
      },
      {
        ""name"": ""test-core"",
        ""emptyDir"": {}
      },
      {
        ""name"": ""company-license-volume"",
        ""configMap"": {
          ""name"": ""company-license"",
          ""defaultMode"": 420
        }
      },
      {
        ""name"": ""company-license"",
        ""emptyDir"": {}
      },
      {
        ""name"": ""default-token-wqp5x"",
        ""secret"": {
          ""secretName"": ""default-token-wqp5x"",
          ""defaultMode"": 420
        }
      }
    ],
    ""initContainers"": [
      {
        ""name"": ""copy-configs"",
        ""image"": ""busybox"",
        ""command"": [
          ""sh"",
          ""-c"",
          ""cp mount_path* mount_path 2&gt;/dev/null || true; cp mount_path* mount_path 2&gt;mount_path|| true""
        ],
        ""resources"": {},
        ""volumeMounts"": [
          {
            ""name"": ""company-config-volume"",
            ""mountPath"": ""mount_path""
          },
          {
            ""name"": ""test-core"",
            ""mountPath"": ""mount_path""
          },
          {
            ""name"": ""company-license-volume"",
            ""mountPath"": ""mount_path""
          },
          {
            ""name"": ""company-license"",
            ""mountPath"": ""mount_path""
          },
          {
            ""name"": ""default-token-wqp5x"",
            ""readOnly"": true,
            ""mountPath"": ""/var/run/secrets/kubernetes.io/serviceaccount""
          }
        ],
        ""terminationMessagePath"": ""/dev/termination-log"",
        ""terminationMessagePolicy"": ""File"",
        ""imagePullPolicy"": ""Always""
      }
    ],
    ""containers"": [
      {
        ""name"": ""mongodb-test"",
        ""image"": ""mongo:3.6.8"",
        ""ports"": [
          {
            ""containerPort"": 27017,
            ""protocol"": ""TCP""
          }
        ],
        ""resources"": {},
        ""volumeMounts"": [
          {
            ""name"": ""default-token-wqp5x"",
            ""readOnly"": true,
            ""mountPath"": ""/var/run/secrets/kubernetes.io/serviceaccount""
          }
        ],
        ""readinessProbe"": {
          ""exec"": {
            ""command"": [
              ""mongo"",
              ""--eval"",
              ""rs.initiate()""
            ]
          },
          ""timeoutSeconds"": 1,
          ""periodSeconds"": 10,
          ""successThreshold"": 1,
          ""failureThreshold"": 3
        },
        ""terminationMessagePath"": ""/dev/termination-log"",
        ""terminationMessagePolicy"": ""File"",
        ""imagePullPolicy"": ""IfNotPresent""
      },
      {
        ""name"": ""test-dev-58663"",
        ""image"": ""image_path"",
        ""command"": [
          ""sh"",
          ""-c"",
          ""mkdir -p mount_path 2&gt;/dev/null &amp;&amp; npm test --skipConnectivityTestRethinkDB""
        ],
        ""env"": [
          {
            ""name"": ""AWS_ACCESS_KEY_ID"",
            ""valueFrom"": {
              ""secretKeyRef"": {
                ""name"": ""aws-secrets"",
                ""key"": ""AWS_ACCESS_KEY_ID""
              }
            }
          },
          {
            ""name"": ""AWS_SECRET_ACCESS_KEY"",
            ""valueFrom"": {
              ""secretKeyRef"": {
                ""name"": ""aws-secrets"",
                ""key"": ""AWS_SECRET_ACCESS_KEY""
              }
            }
          },
          {
            ""name"": ""AWS_REGION"",
            ""valueFrom"": {
              ""secretKeyRef"": {
                ""name"": ""aws-secrets"",
                ""key"": ""AWS_REGION""
              }
            }
          },
          {
            ""name"": ""BUILD_ID"",
            ""valueFrom"": {
              ""configMapKeyRef"": {
                ""name"": ""tbsp-config"",
                ""key"": ""BUILD_ID""
              }
            }
          }
        ],
        ""resources"": {},
        ""volumeMounts"": [
          {
            ""name"": ""test-core"",
            ""mountPath"": ""mount_path""
          },
          {
            ""name"": ""company-license"",
            ""mountPath"": ""mount_path""
          },
          {
            ""name"": ""default-token-wqp5x"",
            ""readOnly"": true,
            ""mountPath"": ""/var/run/secrets/kubernetes.io/serviceaccount""
          }
        ],
        ""terminationMessagePath"": ""/dev/termination-log"",
        ""terminationMessagePolicy"": ""File"",
        ""imagePullPolicy"": ""IfNotPresent""
      }
    ],
    ""restartPolicy"": ""Never"",
    ""terminationGracePeriodSeconds"": 10,
    ""dnsPolicy"": ""ClusterFirst"",
    ""serviceAccountName"": ""default"",
    ""serviceAccount"": ""default"",
    ""nodeName"": ""pc212"",
    ""securityContext"": {},
    ""imagePullSecrets"": [
      {
        ""name"": ""company-regsecret""
      }
    ],
    ""schedulerName"": ""default-scheduler"",
    ""tolerations"": [
      {
        ""key"": ""node.kubernetes.io/not-ready"",
        ""operator"": ""Exists"",
        ""effect"": ""NoExecute"",
        ""tolerationSeconds"": 300
      },
      {
        ""key"": ""node.kubernetes.io/unreachable"",
        ""operator"": ""Exists"",
        ""effect"": ""NoExecute"",
        ""tolerationSeconds"": 300
      }
    ]
  },
  ""status"": {
    ""phase"": ""Pending"",
    ""conditions"": [
      {
        ""type"": ""Initialized"",
        ""status"": ""True"",
        ""lastProbeTime"": null,
        ""lastTransitionTime"": ""2019-05-10T12:50:39Z""
      },
      {
        ""type"": ""Ready"",
        ""status"": ""False"",
        ""lastProbeTime"": null,
        ""lastTransitionTime"": ""2019-05-10T12:49:54Z"",
        ""reason"": ""ContainersNotReady"",
        ""message"": ""containers with unready status: [mongodb-test test-dev-58663]""
      },
      {
        ""type"": ""PodScheduled"",
        ""status"": ""True"",
        ""lastProbeTime"": null,
        ""lastTransitionTime"": ""2019-05-10T12:49:54Z""
      }
    ],
    ""hostIP"": ""10.10.2.12"",
    ""podIP"": ""172.16.4.22"",
    ""startTime"": ""2019-05-10T12:49:54Z"",
    ""initContainerStatuses"": [
      {
        ""name"": ""copy-configs"",
        ""state"": {
          ""terminated"": {
            ""exitCode"": 0,
            ""reason"": ""Completed"",
            ""startedAt"": ""2019-05-10T12:50:39Z"",
            ""finishedAt"": ""2019-05-10T12:50:39Z"",
            ""containerID"": ""docker://1bcd12f5848e32e82f7dfde8e245223345e87f70061b789cbbabc0f798436b59""
          }
        },
        ""lastState"": {},
        ""ready"": true,
        ""restartCount"": 0,
        ""image"": ""busybox:latest"",
        ""imageID"": ""docker-pullable://busybox@sha256:0b184b74edc63924be0d7f67d16f5afbcdbe61caa1aca9312ed3b5c57792f6c1"",
        ""containerID"": ""docker://1bcd12f5848e32e82f7dfde8e245223345e87f70061b789cbbabc0f798436b59""
      }
    ],
    ""containerStatuses"": [
      {
        ""name"": ""mongodb-test"",
        ""state"": {
          ""waiting"": {
            ""reason"": ""PodInitializing""
          }
        },
        ""lastState"": {},
        ""ready"": false,
        ""restartCount"": 0,
        ""image"": ""mongo:3.6.8"",
        ""imageID"": """"
      },
      {
        ""name"": ""test-dev-58663"",
        ""state"": {
          ""waiting"": {
            ""reason"": ""PodInitializing""
          }
        },
        ""lastState"": {},
        ""ready"": false,
        ""restartCount"": 0,
        ""image"": ""image_path"",
        ""imageID"": """"
      }
    ],
    ""qosClass"": ""BestEffort""
  }
}


</code></pre>

<p>Both the containers and the hosting pod should terminate gracefully.</p>
",https://stackoverflow.com/questions/56077516/running-two-containers-in-a-single-pod-via-kubectl-run-does-not-terminate-the-po,"['mongodb', 'kubernetes']",213,False,0,1
File Endpoint for Citrus Framework,"<p>I'm currently looking at using Citrus for our Integration Testing, however our Integration Software uses amongst others, file messages - where files are written to an inbound folder, picked up and processed which results in a new file message being written to an outbound folder or data being written to SQL.</p>

<p>I was wondering if Citrus can write a file with a certain payload to an inbound folder and then monitor for a file to appear in certain outbound folder and/or in a SQL table.</p>

<p>Example Test Case:</p>

<pre><code>file()
  .folder(todoInboundFolder)
  .write()
  .payload(new ClassPathResource(""templates/todo.xml""));

file()
  .folder(todoOutboundFolder)
  .read()
  .validate(""/t:todo/t:correlationId"", ""${todocorrelationId}"")
  .validate(""/t:todo/t:title"", ""${todoName}"");

query(todoDataSource)
  .statement(""select count(*) as cnt from todo_entries where correlationid = '${todocorrelationId}'"")
  .validate(""cnt"", ""1"");
</code></pre>

<p>Additionaly - is there a way to specific the timeout to wait for the file/SQL entries to appear?</p>
",https://stackoverflow.com/questions/57910464/file-endpoint-for-citrus-framework,['citrus-framework'],314,True,0,1
Does SpringBoot test with TestRestTemplate always require @SpringBootTest annotation,"<p>I am testing a controller using the @WebMvcTest annotation and MockMvc, it is working fine:</p>

<pre><code>@WebMvcTest(MyController.class)
class MyControllerSpec extends Specification {

@Autowired
MockMvc mockMvc;

def ""test""() {
   def mockRequest = ""something""

   when: ""we make call""
   def response = mockMvc.perform(post(""/getuser"")
            .contentType(MediaType.APPLICATION_JSON)
            .content(mockRequest))
            .andReturn().response

   then: ""we get response""
   response.status == OK.value()
   }
}
</code></pre>

<p>I read some articles online that we can use TestRestTemplate for integration testing.  My question is that if I use TestRestTemplate, do I have to use it with @SpringBootTest annotation for SpringBoot test? The reason I am asking this is that we have many controllers in our springBoot application, and also the service/dao layer code.  It seems that I have to create a TestConfigure.class for all the beans (even the beans for other controllers that I am not testing) for testing purpose, otherwise, I will get error like:</p>

<pre><code>Unable to start EmbeddedWebApplicationContext 
due to missing EmbeddedServletContainerFactory bean
</code></pre>

<p>My test code using TestRestTemplate: </p>

<pre><code>@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, 
                classes = [TestConfigure.class])
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
class  MyControllerSpec extends Specification {

@LocalServerPort
private int port;

@Autowired
TestRestTemplate restTemplate

private String createURLWithPort(String uri) {
    return ""http://localhost:"" + port + uri;
}

def ""Integration Success Senario""() {

    given: """"
    when: ""we try to get a user using a rest call""

    def request = new User(name, address)

    String jsonResponse = 
       restTemplate.postForObject(createURLWithPort(""/getuser""), 
                                  request, String.class)

    .....
   }
 }
</code></pre>
",https://stackoverflow.com/questions/54729875/does-springboot-test-with-testresttemplate-always-require-springboottest-annota,"['spring-boot', 'groovy', 'spock', 'spring-boot-test']",551,False,0,1
Conditional compilation of a source file that must be included only in debug builds,"<p>I have been reading best practices for conditional compilation, but I haven't found an example for the situation I have.</p>

<p>I have a C project whose target platform is a specific device (different from a PC). I have a source file that only contains functions for integration testing and things like that. I want this file to be compiled and linked only in <code>DEBUG</code> builds, not in the <code>RELEASE</code> ones.</p>

<p><strong>My question is which of the following options is a better practice:</strong></p>

<p>A<code>*.c</code> file like the following:</p>

<pre><code>Tests.c
---------
#ifndef NDEBUG
// All testing functions
...
#endif
</code></pre>

<p>And include that file in both <code>DEBUG</code> and <code>RELEASE</code> builds.</p>

<p><strong>Or</strong></p>

<p>Checking whether or not <code>NDEBUG</code> is defined from within the  project's <code>Makefile / CMakeLists.txt</code> and including the mentioned source file consequently.</p>
",https://stackoverflow.com/questions/56423142/conditional-compilation-of-a-source-file-that-must-be-included-only-in-debug-bui,"['c', 'makefile', 'macros', 'embedded', 'conditional-compilation']",410,True,0,3
Test with DataJpaTest given no bean of type ServletContext,"<p>I am trying to test using DataJpaTest. I get the following error </p>

<blockquote>
  <p>Description:</p>
  
  <p>Parameter 6 of constructor in
  springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper
  required a bean of type 'javax.servlet.ServletContext' that could not
  be found.</p>
  
  <p>Action:</p>
  
  <p>Consider defining a bean of type 'javax.servlet.ServletContext' in
  your configuration.</p>
</blockquote>

<p>I have tried defining a EmbeddedServletContainerFactory in the test configuration. 
When i use @SpringBootTest it works, but I don't think it is good to use integration testing for everything. </p>

<p>I even tried to fool it by using a mockbean of Servlet Context, but still it doesn't work. Is there a way around this?</p>

<p>Also, why is this error happening, I'm new to testing so, I do not have full knowledge about it. </p>

<p>The following is my test</p>

<pre><code>@RunWith(SpringRunner.class)
@DataJpaTest
public class GprsDeviceRepositoryTest{
    @Autowired
    GprsDeviceRepository gprsDeviceRepository;

    @Autowired
    TestEntityManager entityManager;

    @Test
    public void test(){
    ..}
}
</code></pre>
",https://stackoverflow.com/questions/55015539/test-with-datajpatest-given-no-bean-of-type-servletcontext,"['spring-boot', 'junit', 'spring-data-jpa', 'junit4', 'spring-boot-test']",1445,False,3,0
How can I run Integration Test to Kafka with Testcontainer using Junit 5,"<p>I'm trying to write an integration test for my Kafka consumer.<br>
I'm using <code>JUnit 5</code>, so I can׳t initialize it using <code>@Rule</code>, and the examples I saw with <code>@Container</code> initialization it is not working as well.</p>

<p><strong>I tried to change my Junit version</strong> to <code>Junit 4</code> but it damages my other tests (so I need to stay with <code>Junit 5</code>).</p>

<p><strong>I tried to use this example at Junit 4:</strong> <a href=""https://www.testcontainers.org/modules/kafka/"" rel=""nofollow noreferrer"">https://www.testcontainers.org/modules/kafka/</a></p>

<p>And those on <code>Junit 5</code>: <a href=""https://www.hascode.com/2019/01/using-throwaway-containers-for-integration-testing-with-java-junit-5-and-testcontainers/"" rel=""nofollow noreferrer"">https://www.hascode.com/2019/01/using-throwaway-containers-for-integration-testing-with-java-junit-5-and-testcontainers/</a></p>

<p>But it doesn't recognize my annotations (<code>@Testcontainers</code>, <code>@Container</code>).</p>

<p><strong>Gradle imports:</strong></p>

<pre><code>testImplementation 'org.junit.jupiter:junit-jupiter-api:5.4.0'
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.4.0'
implementation group: 'org.apache.kafka', name: 'kafka-clients', version: '1.1.1'
testIntegrationImplementation ""org.testcontainers:kafka:1.11.4""
</code></pre>

<p>I'm uploading this code as an annotation:</p>

<pre class=""lang-java prettyprint-override""><code>@Testcontainers
public class KafkaTestContainer implements BeforeAllCallback, AfterAllCallback {

    @Container
    public KafkaContainer kafkaContainer = new KafkaContainer();
    private static final Logger logger = LoggerFactory.getLogger(KafkaTestContainer.class);

    @Inject
    private KafkaTestContainer() {
        try {

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    private String getKafkaBootstrapServers(Request request) throws IOException {
        return this.kafkaContainer.getBootstrapServers();
    }


    public void stopKafkaTestContainer() {
        // Stop the container.
        kafkaContainer.stop();

    }

    @Override
    public void afterAll(ExtensionContext context) throws Exception {
    }

    @Override
    public void beforeAll(ExtensionContext context) throws Exception {
        boolean isKafkaRunning = this.kafkaContainer.isRunning();
        if(isKafkaRunning) {
            logger.info(""start Kafka docker!!"");
        }
    }
</code></pre>

<p>isKafkaRunning value is always false.</p>

<ol>
<li>Any help with Kafka test container initialization is appreciated?</li>
<li>What am I missing??</li>
</ol>
",https://stackoverflow.com/questions/57509190/how-can-i-run-integration-test-to-kafka-with-testcontainer-using-junit-5,"['java', 'apache-kafka', 'integration-testing', 'junit5', 'testcontainers']",5958,True,3,3
Asp.Net Core Integration Testing with CustomWebApplicationFactory - How does it work?,"<p>I am trying to get a better understanding of integration testing. By default, a lot of example utilize <code>IClassFixture&lt;T&gt;</code> for integration testing (e.g. being <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#basic-tests-with-the-default-webapplicationfactory"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#basic-tests-with-the-default-webapplicationfactory</a>).</p>

<p>That works great for testing things like - is the page loading, is the form being displayed, am I getting the correct http status code etc. But when testing an API, you'll want some seed data to exist. In order to get seed data into your testing, typical go-to is EF in-memory database. This is achieved via a custom web application factory where you can create a scope, request the appropriate service (i.e. dbcontext), and seed it (e.g. being <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#customize-webapplicationfactory"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#customize-webapplicationfactory</a>).</p>

<p>I have an integration test project that is working and fully functional. But the nuances of how it works is still confusing to me. </p>

<hr>

<h2>Am I correct in assuming that when you create a <strong>CustomWebApplicationFactory</strong>, essentially you are creating a custom ""Program.cs"" (i.e. the typical entry point into the application) where you are free to add in additional testing services/filters as needed?</h2>

<hr>

<p>Below is my custom web application factory that I am using for my integration testing. My API has basic authentication for most endpoints so I added a global filter to bypass that. But what I am doing below is essentially the same in my <strong>Program.cs</strong> in my actual API (the only difference being I don't add the fake user and global anonymous filter). So I am lead to believe that my above point stands true. Is this a correct assumption?</p>

<p>Another point I wanted to verify is that in an actual unit test, I can replace a service with a mock. Is this possible in an integration test where I can swap out the DI instance for a requested service to be a test service instead? </p>

<hr>

<h2>E.g. my app has a <code>IUploadFileToAzure</code> service. Instead of using UploadFileToAzure as the DI instance, can I replace that implementation with a <code>TestUploadFileToAzure</code> service in my integration test?</h2>

<hr>

<p>Registering a service multiple times takes the last registration of the service so I was wondering if that can be used as a workaround for my above point. Is this even recommended? I understand it defeats the purpose of testing a service but wanted to verify if that was possible. I tried testing this locally and it did not work.</p>

<pre><code>public class CustomWebApplicationFactory&lt;TStartup&gt; : WebApplicationFactory&lt;Startup&gt;
    {
        protected override IWebHostBuilder CreateWebHostBuilder()
        {
            return WebHost
                .CreateDefaultBuilder&lt;Startup&gt;(new string[0])
                .ConfigureServices(services =&gt;
                {
                    services.AddSingleton&lt;IStartupFilter, AddCustomMiddlewareStartupFilter&gt;();
                });
        }


        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder
            .UseEnvironment(""Development"")
            .ConfigureServices(services =&gt;
            {
                services.AddMvc(opt =&gt;
                {
                    //add a global anonymous filter
                    opt.Filters.Add(new AllowAnonymousFilter());

                    //add a filter for adding a fake claimsprincipal so that the user service
                    //correctly identifies the user
                    opt.Filters.Add(new FakeClaimsPrincipalFilter(true, false));
                });

                services.AddEntityFrameworkInMemoryDatabase();

                // Create a new service provider.
                var provider = services
                    .AddEntityFrameworkInMemoryDatabase()
                    .BuildServiceProvider();

                // Add a database context using an in-memory 
                // database for testing.
                services.AddDbContext&lt;AppDbContext&gt;(options =&gt;
                {
                    options.UseInMemoryDatabase(""TestDb"");
                    options.UseInternalServiceProvider(provider);
                });

                // 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 apiDb = scopedServices.GetRequiredService&lt;AppDbContext&gt;();   

                    // Ensure the database is created.
                    apiDb.Database.EnsureCreated();
                }
            });
        }
    }
</code></pre>
",https://stackoverflow.com/questions/57485969/asp-net-core-integration-testing-with-customwebapplicationfactory-how-does-it,"['c#', 'asp.net-core']",4802,True,2,1
Mocking current_app in Flask unit pytest,"<p>I want to unit test following function:</p>

<pre><code>from flask import current_app

def fuu():
    current_app.logger.info('hello world')
    any = current_app.config['any']
</code></pre>

<p>Without any special context handling I receive following error message:</p>

<pre><code>E           This typically means that you attempted to use functionality that needed
E           to interface with the current application object in some way. To solve
E           this, set up an application context with app.app_context().  See the
E           documentation for more information.
</code></pre>

<p>After reading about Flask context, I came up with a <em>working</em> solution:</p>

<pre><code>@classmethod
def setUpClass(cls):
    app = app_factory.create_app()
    ctx = app.app_context()
    ctx.push()
    cls.app = app
</code></pre>

<p>But the point is that I do not want to deal with any flask contexts in <strong>UNIT tests</strong>. I want to have a plain unit test, in which all collaborators can be mocked, so that the <em>system under test</em> just deals with mocked instance, in this case for <code>current_app</code> as well. 
Having flask context is pretty fine for integration testing, but not for unit testing.</p>

<p>I am searching for something similar like this:</p>

<pre><code> @patch('flask.current_app')
</code></pre>

<p>Is there any way to achieve this?</p>

<p><strong>EDIT #1</strong></p>

<p>@Gabriel C</p>

<p>service.py</p>

<pre><code>from flask import current_app

def fuu():
    current_app.logger.info('hello world')
</code></pre>

<p>service_test.py</p>

<pre><code>import unittest
from unittest.mock import patch

class TestService(unittest.TestCase):

@patch('flask.current_app')
def test_generate_image_happy_path(self, mock):
    from service import fuu
    fuu()
    assert 1 == 1
</code></pre>

<p>This fails for the same exact reason:</p>

<pre><code>E           RuntimeError: Working outside of application context.
</code></pre>
",https://stackoverflow.com/questions/57947935/mocking-current-app-in-flask-unit-pytest,"['unit-testing', 'flask', 'mocking', 'pytest']",5641,True,7,2
How to mock a function in jest or prevent default?,"<p>I am trying to use react-testing-lib to do some integration testing</p>

<p>I want to mock a function like inside my react class called <code>handleSubmit</code></p>

<pre><code>handleSubmit(){
 // does some stuff
 // calls an action creator

}
</code></pre>

<p>I basically want to stub this method, so that it either returns <code>null</code>/<code>undefined</code> or anything. But I don't want it to actually call the action creator</p>

<p>The reason being I wanted to assert some UI is present and calling the action creator is giving me the error: </p>

<blockquote>
  <p>Actions must be plain objects. Use custom middleware for async actions.</p>
</blockquote>

<p>I have tried to <code>jest.mock(thismethod)</code> and jest.spyOn()` too but neither seem to work. I just want it to do something like</p>

<pre><code>myFunc() {

}
</code></pre>

<p>as if it were an empty function and does nothing. How can I stub this?</p>
",https://stackoverflow.com/questions/56036715/how-to-mock-a-function-in-jest-or-prevent-default,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'react-testing-library']",3876,True,2,2
Is it still &quot;unit testing&quot; if you&#39;re using React Testing Library / Enzyme&#39;s mount function?,"<p>We're currently unit testing our React application with Enzyme's shallow render function. Every component is tested in isolation so I understand why this is called ""unit testing"". </p>

<p>We're moving towards rendering the component and it's children. You can do this with Enzyme's mount function or with React Testing Library as it never shallow renders. This also means we have to mock Redux if it's a connected component. </p>

<p>What is the name for this type of testing? I've heard it called ""integration testing"", but when I say this at work people think that I mean something else. Is it still a type of ""unit testing"" despite the fact that multiple components are tested together? </p>
",https://stackoverflow.com/questions/57091857/is-it-still-unit-testing-if-youre-using-react-testing-library-enzymes-moun,"['reactjs', 'testing']",1416,True,2,2
Null is passed to autowired service even after mocking - SpringBootTest,"<p>I wanted to do integration testing of my API.</p>

<pre><code>@RestController
@RequestMapping(""/api/v1"")
public class TestController {

    @Autowired
    TestService testService;

    @RequestMapping(""/welcome"")
    public String welcomeMessage(@RequestParam(""name"") String name) {
        return testService.welcomeMessage(name);
    }
}
</code></pre>

<p>Below are the service interface and its implementation:</p>

<pre><code>public interface TestService {
    public String welcomeMessage(String name);
}

public class TestServiceImpl implements TestService{
    @Autowired
    TestRepository repo;

    @Override
    public String welcomeMessage(String name) {
        repo.save(new StringEntity(name));
        return ""Hello ""+name;
    }
}
</code></pre>

<p>Below is the Test Case:</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MockitoTestingApplicationTests {

    @Autowired
    MockMvc mvc;

    @MockBean
    TestService testService;

    @MockBean
    TestController testController;

    @Test
    public void contextLoads() throws Exception {
        Mockito.when(testController.welcomeMessage(ArgumentMatchers.anyString())).thenCallRealMethod();
        Mockito.when(testService.welcomeMessage(ArgumentMatchers.anyString())).thenCallRealMethod();

        mvc.perform(get(""/api/v1/welcome"").param(""name"", ""dude"")).andExpect(status().isOk());
    }

}
</code></pre>

<p>I have a few questions.</p>

<ol>
<li><p>when I'm executing the above code it is throwing an error saying cannot call real method on abstract methods. And When I'm mocking the <code>TestServiceImpl</code>, It is throwing <code>NullPointerException</code> in the Controller because the <code>TestService</code> is null. How should I fix that?</p></li>
<li><p>How should I mock the repository layer when we are using MongoDB. when I try to Mock <code>MongoTemplate</code>, It is throwing an error saying <code>MongoConvertor must not be null</code></p></li>
<li><p>Is this the right way to write test cases. can we have code coverage without using <code>thenCallRealMethod()</code>?</p></li>
</ol>

<p>Please suggest me how to proceed. Thanks in advance.</p>
",https://stackoverflow.com/questions/56509083/null-is-passed-to-autowired-service-even-after-mocking-springboottest,"['spring-boot', 'junit', 'mocking', 'mockito', 'spring-boot-test']",2511,True,1,1
How to write Integration Tests for MEAN application,"<p>Currently, I'm creating a project that incorporates the MEAN stack, Docker, and Travis CI. I'm using Travis CI to automate builds for unit testing, integration testing, etc. I'm using Docker to help create a test environment. I've already successfully created unit tests thanks to resources via Medium. However, I haven't found many resources on writing integration tests for a MEAN application. I want to create tests to see if I get expected values in the Angular application when it connects to the REST API endpoints from Express, and the Express application is connected to a MongoDB server. Does anyone have any resources or advice on how to write these tests, and to execute them in a Dockerized test environment?</p>
",https://stackoverflow.com/questions/54030604/how-to-write-integration-tests-for-mean-application,"['mongodb', 'docker', 'express', 'continuous-integration', 'mean']",36,True,1,1
Integration tests for plotly.js,"<p>Need to test the line chart, scatter chart, spider chart etc created using plotly.js using any automation framework/tools. Following are few of the targeted verifications:</p>

<p>-Get data points (markers) count</p>

<p>-Get each data point (marker) value</p>

<p>-Get data points css</p>

<p>-Get legends css</p>

<p>-Handling out of the box action header items</p>

<p>-Zoom in/out</p>

<p>Have tried with java-selenium but can’t find data points (markers) in DOM to get the required styling and values.</p>

<p>Can anyone please help in this aspect to how to perform integration testing for these charts here?
Link for demo chart - <a href=""https://plot.ly/javascript/line-and-scatter/"" rel=""nofollow noreferrer"">https://plot.ly/javascript/line-and-scatter/</a></p>

<p>The same has been integrated as it is in our scenario.</p>
",https://stackoverflow.com/questions/54437766/integration-tests-for-plotly-js,"['javascript', 'java', 'selenium', 'integration-testing', 'plotly']",339,False,1,0
NUnit Unit Testing which involves dbcontext,"<p>I have the code below, which is now testable. The problem is when it reaches the Entity Framework (EF) related code, it kinda hangs there (infinite loop). I think my interim solution is to comment out my EF related code. </p>

<p>I understand that to test EF, I might need thing like MOQ or integration testing which I plan to come out with later on. Meanwhile, how do I 'split' out all this EF code, so that I can perform NUnit testing for other testable code? Here is one of the methods I have:</p>

<pre><code>public void PlaceDeposit(BankAccount account, decimal _transaction_amt)
{   

    if (_transaction_amt &lt;= 0)               
        _msgPrinter.PrintMessage(""Amount needs to be more than zero. Try again."", false);
    else if (_transaction_amt % 10 != 0)
        _msgPrinter.PrintMessage($""Key in the deposit amount only with multiply of 10. Try again."", false);
    else if (!PreviewBankNotesCount(_transaction_amt))
        _msgPrinter.PrintMessage($""You have cancelled your action."", false);
    else
    {
        var transaction = new Transaction()
        {
            AccountID = account.Id,
            BankAccountNoTo = account.AccountNumber,
            TransactionType = TransactionType.Deposit,
            TransactionAmount = _transaction_amt,
            TransactionDate = DateTime.Now
        };
        repoTransaction.InsertTransaction(transaction);
        // Add transaction record - End

        account.Balance = account.Balance + _transaction_amt;

        ctx.SaveChanges();

        _msgPrinter.PrintMessage($""You have successfully deposited {Utility.FormatAmount(_transaction_amt)}"", true);
    }
}
</code></pre>

<p>I have this test method in NUnit, which works fine:</p>

<pre><code>[TestCase(""Amount needs to be more than zero. Try again."",0)]
[TestCase(""Amount needs to be more than zero. Try again."",-1)]
[TestCase(""Key in the deposit amount only with multiply of 10. Try again."", 1)]
[TestCase(""Key in the deposit amount only with multiply of 10. Try again."", 5)]
public void ShowErrorMessage_OnPlaceDeposit(string expectedMessage, decimal transactionAmount)
{
    // Arrange - Start
    var mock = new MockMessagePrinter();

    MeybankATM atmCustomer = new MeybankATM(new RepoBankAccount(), new RepoTransaction(), mock);

    BankAccount bankAccount = new BankAccount()
    {
        FullName = ""John"",
        AccountNumber = 333111,
        CardNumber = 123,
        PinCode = 111111,
        Balance = 2000.00m,
        isLocked = false
    };
    // Arrange - End

    // Act
    atmCustomer.PlaceDeposit(bankAccount, transactionAmount);

    // Assert                       
    Assert.AreEqual(expectedMessage, mock.Message);
}
</code></pre>

<p>Now, all I have I left is to test the balance update part:</p>

<pre><code>account.Balance = account.Balance + _transaction_amt;
</code></pre>
",https://stackoverflow.com/questions/55104971/nunit-unit-testing-which-involves-dbcontext,"['c#', 'nunit']",400,False,0,0
publishing XML messages from Zerocode to Kafka topic,"<p>I am trying integration testing for streaming platform ( Kafka / spark ) using <a href=""https://authorjapps.github.io/zerocode/"" rel=""nofollow noreferrer"">zerocode</a> </p>

<p>zero code (publish XML Message )-->  serialize with Apache AVRO --> Kafka topic --> spark job (processing) --> Kafka topic --> deserialize with AVRO -->zero code consumer Test ( assert for message content )</p>

<p>when i am trying to put message on Kafka topic with zero code , zero code test case introduce special char at start of XML message , which cause error while parsing XML message in spark . </p>

<p>when I work with string serializer and ""hello world"" it work .</p>

<p>I need to make it work with Apache Avro and XML message  .</p>

<pre><code>{
  ""scenario Name"": ""Produce a message to Kafka topic - vanilla"",
  ""steps"": [
    {
      ""name"": ""produce_step"",
      ""URL"": ""Kafka-topic: my-topic "",
      ""operation"": ""produce"",
      ""request"": {
        ""record Type"" : ""J SON"",
        ""records"": [
          {
            ""key"":""123456789"",
            ""value"": ""Schema Test""
          }
        ]
      },
      ""assertions"": {
        ""record Metadata"" : ""$NOT.NULL"",
        ""status"" : ""OK""
      }
    }
  ]
}
</code></pre>

<p>when zero code test case put message on Kafka topic , it should not introduce any special char at start of message . </p>
",https://stackoverflow.com/questions/57985087/publishing-xml-messages-from-zerocode-to-kafka-topic,"['xml', 'apache-spark', 'apache-kafka', 'streaming', 'avro']",698,True,0,2
Testing with Embeded stub/dummy application in SpringBoot,"<p>I'm trying to write a integration test for my SpringBoot microservice that interacts with another service inside the product ecosystem.
Since this kind of testing is consider function/integration testing (depending on what nomenclature you use) it is usually done on some development environment.
However, I wanted to test a basic interaction between my service and a STUB/dummy app which are connected with RPC (so not exactly a typical TestRestTemplate test).
I know that there is a way to embed a service while booting up the Spring Context but have never done it by myself.
Does anyone have any experience with the upper or maybe a few helpful links where I can explore.</p>
",https://stackoverflow.com/questions/58195710/testing-with-embeded-stub-dummy-application-in-springboot,"['java', 'spring-boot', 'spring-boot-test']",117,True,0,1
Spring Integration testing doesn&#39;t use security configuration,"<p>I am new to integration testing and doing everything everything as in tutorials. 
My security config:</p>

<pre><code>@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers(""/ticket/create"")
                .access(""hasAnyAuthority('MANAGER','EMPLOYEE')"")
                .and().authorizeRequests().antMatchers(""/api/**"",""/ticket/*"")
                .access(""isAuthenticated()"")
                .and().formLogin().loginPage(""/login"").failureUrl(""/login?error"")
                .and().formLogin().defaultSuccessUrl(""/ticket/all"", true)
                .usernameParameter(""email"")
                .passwordParameter(""password"")
                .and().csrf().disable();
    }
</code></pre>

<p>All of my app requires login.</p>

<p>Now i'm trying to run a simple test to view main page of my app which: /ticket/all</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebAppInit.class, WebMvcConfig.class, WebSecurityConfig.class, HibernateConfig.class, SecurityWebApplicationInitializer.class})
@WebAppConfiguration
public class TicketLoginControllerTest extends TestCase {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    @Before
    public void setup() throws Exception {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testTicketOverviewAll() throws Exception {
        mockMvc.perform(get(""/ticket/all""))
                .andExpect(status().isOk());

    }
}
</code></pre>

<p>Test pass, even though i'm not authenticated.</p>

<p>Now my url: /ticket/create is forbidden for role ENGINEER</p>

<p>but when i try </p>

<pre><code>@Test
public void testTicketOverviewAll() throws Exception {
    mockMvc.perform(get(""/ticket/create""))
            .andExpect(status().isOk());

}
</code></pre>

<p>it still ok, when it should be 401 forbidden even if logged in.</p>

<p>I'm probably doing something wrong with test configuration but i don't know what exactly. Any help apreciated. 
If i just run my server and try all of the above, it will work as i expect it to work.</p>
",https://stackoverflow.com/questions/58166827/spring-integration-testing-doesnt-use-security-configuration,"['spring-mvc', 'junit', 'spring-security', 'integration-testing']",88,True,0,1
How to write Integration Test for rabbit template with confirm and return callback,"<p>I have publisher that publish the message to exchange and associated rabbit template is configured to have confirm and return call back. I just would like to know How do I write integration test for this class using mock or any other frame work.</p>

<p>I have publisher that publish the message to exchange and associated rabbit template is configured to have confirm and return call back. I just would like to know How do I write integration test for this class using mock or any other frame work.</p>

<h2>Code :</h2>

<pre class=""lang-java prettyprint-override""><code>
    @Configuration
    public class TopicConfiguration {

        private static final Logger LOGGER = LoggerFactory.getLogger(TopicConfiguration.class);

        @Autowired
        RabbitMqConfig rabbitMqConfig;

        @Autowired 
        EPPQ2Publisher eppQ2Publisher;


         /**
         * Caching connection factory 
         * @return CachingConnectionFactory
         */
        @Bean
        public CachingConnectionFactory cachingConnectionFactory() {
            CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(rabbitMqConfig.getPublisherHosts(),
                    rabbitMqConfig.getPublisherPort());
            cachingConnectionFactory.setUsername(rabbitMqConfig.getPublisherUsername());
            cachingConnectionFactory.setPassword(rabbitMqConfig.getPublisherPassword());
            cachingConnectionFactory.setVirtualHost(""hydra.services"");
            cachingConnectionFactory.createConnection();
            cachingConnectionFactory.setPublisherReturns(true);
            cachingConnectionFactory.setPublisherConfirms(true);
            cachingConnectionFactory.setConnectionNameStrategy(f -&gt; ""publisherConnection"");
            return cachingConnectionFactory;
        }

        /**
         * Bean RabbitTemplate
         * @return RabbitTemplate
         */
        @Bean
        public RabbitTemplate template(
                @Qualifier(""cachingConnectionFactory"") CachingConnectionFactory cachingConnectionFactory) {
            final RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
            rabbitTemplate.setMessageConverter(producerJackson2MessageConverter());
            RetryTemplate retryTemplate = new RetryTemplate();
            ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
            backOffPolicy.setInitialInterval(500);
            backOffPolicy.setMultiplier(10.0);
            backOffPolicy.setMaxInterval(10000);
            retryTemplate.setBackOffPolicy(backOffPolicy);
            rabbitTemplate.setRetryTemplate(retryTemplate);
            rabbitTemplate.setExchange(rabbitMqConfig.getPublisherTopic());
            rabbitTemplate.setUsePublisherConnection(true);
            rabbitTemplate.setMandatory(true);

            rabbitTemplate.setConfirmCallback((correlation, ack, reason) -&gt; {
                if (correlation != null) {
                    LOGGER.info(""Received "" + (ack ? "" ack "" : "" nack "") + ""for correlation: "" + correlation);
                    if (ack) {
                        // this is confirmation received..
                        // here is code to ack Q1. correlation.getId() and ack it !!
                        eppQ2Publisher.ackMessage(new Long(correlation.getId().toString()));
                    } else {
                        // no confirmation received and no need to do any thing for
                        // retry..
                    }
                }

            });
            rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -&gt; {
                LOGGER.error(""Returned: "" + message + ""\nreplyCode: "" + replyCode + ""\nreplyText: "" + replyText
                        + ""\nexchange/rk: "" + exchange + ""/"" + routingKey);
            });
            return rabbitTemplate;
        }

        /**
         * Bean Jackson2JsonMessageConverter
         * @return Jackson2JsonMessageConverter
         */
        @Bean
        public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
            return new Jackson2JsonMessageConverter();
        }

    }

    ````java
    @Component
    public class EPPQ2PublisherImpl implements EPPQ2Publisher{
        @Autowired
        RabbitMqConfig rabbitMqConfig;

        @Autowired
        private RabbitTemplate rabbitTemplate;

        private Channel channel;

        /**
         * Method sendMessage for sending individual scrubbed and encrypted message to publisher queue (Q2).
         * @param msg - message domain object 
         * @param deliveryTag - is message delivery tag.        
         */
        @Override
        public void sendMessage(Message msg,Long deliveryTag) {
            rabbitTemplate.convertAndSend(rabbitMqConfig.getRoutingKey(), msg,new CorrelationData(deliveryTag.toString()));
        }

        /**
         * sendMessages for sending list of scrubbed and encrypted messages to publisher queue (Q2)
         * @param msgList - is list of scrubbed and encrypted messages
         * @param channel - is ampq client channel 
         * @param deliveryTagList - is list of incoming message delivery tags. 
         */
        @Override
        public void sendMessages(List&lt;Message&gt; msgList, Channel channel, List&lt;Long&gt;deliveryTagList) {
            if(this.channel == null) {
                this.channel = channel;
            }
            for (int i = 0 ; i &lt; msgList.size(); i ++) {
                sendMessage(msgList.get(i),deliveryTagList.get(i));
            }
        }

        /**
         * Method ackMessage for sending acknowledgement to subscriber queue (Q1).
         * @param  deliveryTag - is deliveryTag for each individual message.
         */
        @Override
        public void ackMessage(Long deliveryTag)  { 
            try {
                channel.basicAck(deliveryTag, false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
</code></pre>

<p>could some one guide me with reference or example is available that would be great.
Some junit and integration testing for rabbit template with confirm and returns would be a great help.</p>
",https://stackoverflow.com/questions/55508116/how-to-write-integration-test-for-rabbit-template-with-confirm-and-return-callba,"['spring-boot', 'spring-amqp']",2333,False,2,1
How to test for exceptions in test_driver?,"<h3>Widget tests</h3>

<p>I know that I can <code>expect</code> exceptions in <strong>widget tests</strong>:</p>

<ul>
<li><p><a href=""https://stackoverflow.com/q/54262024/6509751"">Flutter: Testing for exceptions in widget tests</a></p></li>
<li><p><a href=""https://stackoverflow.com/q/54241396/6509751"">Flutter: Test that a specific exception is thrown</a></p></li>
</ul>

<p>However, I want to test for an <code>Error</code> or an <code>Exception</code> when running my app using <a href=""https://api.flutter.dev/flutter/flutter_driver/flutter_driver-library.html"" rel=""nofollow noreferrer""><code>flutter_driver</code></a>.</p>

<h2>Integration tests</h2>

<p>Currently, I simply look at the logs when running <code>test_driver</code> and check if the logged exceptions are what I expect. However, that is not ideal and I want to integrate the exceptions into the rest of the integration testing.</p>

<h3>flutterDriverLog</h3>

<p>I found <a href=""https://api.flutter.dev/flutter/flutter_driver/flutterDriverLog.html"" rel=""nofollow noreferrer""><code>flutterDriverLog</code> in the <code>flutter_driver</code> library</a>, however, the exceptions do not appear there. It only sends records for the <code>FlutterDriver</code> status, e.g.:</p>

<pre><code>[info ] FlutterDriver: Connecting to Flutter application at ..
[trace] FlutterDriver: Isolate found with number: ..
...
</code></pre>

<h3>What I am looking for</h3>

<p>I would love to have some code like this:</p>

<pre class=""lang-dart prettyprint-override""><code>group('Some tests', () {
  test('Button that throws an exception', () async {
    await flutterDriver.tap(find.byType(IconButton));

    // The following property and function do not exist.
    expect(thatExceptionIsThrown, thatMatches('PlatformException(some_error'));
  });
});
</code></pre>

<p>How do I do that when running <code>FlutterDriver</code>?</p>
",https://stackoverflow.com/questions/58258685/how-to-test-for-exceptions-in-test-driver,"['flutter', 'dart', 'flutter-test']",623,False,2,0
".net core 3.0, issue with IClassFixture, &quot;unresolved constructor arguments: ITestOutputHelper output&quot;","<p>I made a repo for the issue I have with Integration testing upgrading to .net core 3.0 :
<a href=""https://github.com/ranouf/TestingWithDotNetCore3_0"" rel=""nofollow noreferrer"">https://github.com/ranouf/TestingWithDotNetCore3_0</a></p>

<p>When I launch the test, I have this issue:
Message: </p>

<blockquote>
  <p>System.AggregateException : One or more errors occurred. (Class fixture type 'MyIntegrationTests.TestServerFixture' had one or more
  unresolved constructor arguments: ITestOutputHelper output) (The
  following constructor parameters did not have matching fixture data:
  TestServerFixture testServerFixture)
      ---- Class fixture type 'MyIntegrationTests.TestServerFixture' had one or more unresolved constructor arguments: ITestOutputHelper output
      ---- The following constructor parameters did not have matching fixture data: TestServerFixture testServerFixture   Stack Trace: 
      ----- Inner Stack Trace #1 (Xunit.Sdk.TestClassException) -----
      ----- Inner Stack Trace #2 (Xunit.Sdk.TestClassException) -----</p>
</blockquote>

<p>Here is the constructor:</p>

<pre><code>public class WeatherForecastController_Tests : IClassFixture&lt;TestServerFixture&gt;
{
    public WeatherForecastController_Tests(TestServerFixture testServerFixture, ITestOutputHelper output)
    {
        Client = testServerFixture.Client;
        Output = output;
    }
</code></pre>

<p>TestStartup:</p>

<pre><code>public class TestStartup : Startup
{
    public TestStartup(IConfiguration configuration)
        : base(configuration)
    {

    }

    public override void SetUpDataBase(IServiceCollection services)
    {
        // here is where I use the InMemoryDatabase 
    }
}
</code></pre>

<p>TestServerFixture:</p>

<pre><code>public class TestServerFixture : WebApplicationFactory&lt;TestStartup&gt;
{
    private IHost _host;
    public HttpClient Client { get; }
    public ITestOutputHelper Output { get; }

    public TestServerFixture(ITestOutputHelper output)
    {
        Output = output;
        Client = Server.CreateClient();
    }

    // never called but this is where i was previously building up the server
    //
    protected override TestServer CreateServer(IWebHostBuilder builder)
    {
        return base.CreateServer(builder);
    }

    protected override IHost CreateHost(IHostBuilder builder)
    {
        _host = builder.Build();

        using (var scope = _host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            InitializeDataBase(services, Output);
        }

        _host.Start();
        return _host;
    }

    protected override IHostBuilder CreateHostBuilder() =&gt;
        Host.CreateDefaultBuilder()
            .ConfigureLogging((hostingContext, builder) =&gt;
            {
                builder.Services.AddSingleton&lt;ILoggerProvider&gt;(new XunitLoggerProvider(Output));
            })
            .ConfigureWebHostDefaults(webBuilder =&gt;
            {
                webBuilder.UseTestServer();
            });

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseStartup&lt;TestStartup&gt;();
    }

    private void InitializeDataBase(IServiceProvider services, ITestOutputHelper output)
    {
        try
        {
            output.WriteLine(""Starting the database initialization."");
            //here is where is feed the Test DB
            output.WriteLine(""The database initialization has been done."");
        }
        catch (Exception ex)
        {
            output.WriteLine(""An error occurred while initialization the database."");
            Console.WriteLine(ex.Message);
        }
    }
}
</code></pre>

<p>So clearly, the Iod for TestServerFixture testServerFixture and ITestOutputHelper output doesnt work. How to make it work?</p>
",https://stackoverflow.com/questions/59166798/net-core-3-0-issue-with-iclassfixture-unresolved-constructor-arguments-ites,"['c#', 'xunit', '.net-core-3.0']",6276,True,2,2
Roslyn seems to ignore some metadata references,"<p>During the preparation stage of some integration testing, I have to dynamically generate some assemblies with references to other assemblies and flush them to disk. The obvious choice for this task is Roslyn I guess.
Roslyn compilation completes successfully and emitted assemblies saved to disk. When I check the result using ILSPy, I see that some assembly references are not included.</p>

<p>Dummy class generation code: </p>

<pre><code>public static string GenerateEmptyPublicClass([NotNull] string @namespace, [NotNull] string className)
        {
            if (@namespace == null) throw new ArgumentNullException(nameof(@namespace));
            if (className == null) throw new ArgumentNullException(nameof(className));

            var classDeclaration = SyntaxFactory.ClassDeclaration(className).AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));
            var namespaceDeclaration = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(@namespace)).NormalizeWhitespace();
            namespaceDeclaration = namespaceDeclaration.AddMembers(classDeclaration);
            return namespaceDeclaration.NormalizeWhitespace().ToFullString();
        }
</code></pre>

<p>Assembly preparation code: </p>

<pre><code>blic static void GenerateAssembly([NotNull] this string sourceCode, [NotNull] string assemblyFilePath,
            [NotNull] params string[] referencedAssemblyPaths)
        {
            if (sourceCode == null) throw new ArgumentNullException(nameof(sourceCode));
            if (assemblyFilePath == null) throw new ArgumentNullException(nameof(assemblyFilePath));

            var assemblyFileName = Path.GetFileName(assemblyFilePath);
            var outputDirectory = Path.GetDirectoryName(assemblyFilePath);
            Directory.CreateDirectory(outputDirectory);

            var syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);
            var referencedAssemblyMetadata =
                referencedAssemblyPaths.Select(x =&gt; MetadataReference.CreateFromFile(x).WithProperties(new MetadataReferenceProperties()));
            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var compilation = CSharpCompilation.Create(assemblyFileName, new[] {syntaxTree}, referencedAssemblyMetadata, compilationOptions);

            using (var fs = File.Create(assemblyFilePath))
            {
                var emitResult = compilation.Emit(fs);
                if (!emitResult.Success)
                {
                    var failures = emitResult.Diagnostics.Where(x =&gt; x.IsWarningAsError || x.Severity == DiagnosticSeverity.Error);
                    var errorReport = failures.Select(x =&gt; $""{x.Id}: {x.GetMessage()}, {x.Location}"");
                    throw new InvalidOperationException($""Failed to compile source code {sourceCode}. Report: {errorReport}"");
                }

                fs.Flush();
            }
        }
</code></pre>

<p>For simplicity, I want to generate two assemblies:</p>

<ul>
<li>B with the only dependency to netstandard.dll</li>
<li>A with references both to netstandard.dll and B</li>
</ul>

<p>Here goes the code: </p>

<pre><code>  var emptyClassSourceCode = RoslynAssemblyGenerator.GenerateEmptyPublicClass(""DummyNamespace"", ""DummyClass"");
            var standardAssemblyLocation = Path.Combine(Path.GetDirectoryName(Common.ExecutingAssemblyFullPath), ""Resources"", ""netstandard.dll"");

            // A references B
            var aPath = Path.Combine(AssemblyGenerationPath, ""A.dll"");
            var bPath = Path.Combine(AssemblyGenerationPath, ""B.dll"");
            emptyClassSourceCode.GenerateAssembly(bPath, standardAssemblyLocation);
            emptyClassSourceCode.GenerateAssembly(aPath, bPath, standardAssemblyLocation);
</code></pre>

<p>B is generated as expected, but A does not refer to B:</p>

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

<p>Can't figure out what have I missed, why B is not referenced by A.</p>
",https://stackoverflow.com/questions/58144901/roslyn-seems-to-ignore-some-metadata-references,"['c#', 'code-generation', 'roslyn']",284,True,1,1
Python NLS http encoding,"<p>I am trying to do some integration testing on our web pages using National Language Support (NLS).  For example, I try posting a page with form containing the value ""Fréd"" for the first_name.</p>

<p>To do this I set up Python 3.7.3 with </p>

<pre><code>import request
</code></pre>

<p>And then do requests.post with the data {'first_name': ""Fr\u00E9d""}</p>

<p>At some point the UTF-8 str is translated to bytes, but those are not translated to the accent e code.  I dug through the code and it boils down to this test case:</p>

<pre><code>&gt;&gt;&gt; ""Fr\u00E9d""
'Fréd'
&gt;&gt;&gt; ""Fr\u00E9d"".encode(""utf-8"")
b'Fr\xc3\xa9d'
</code></pre>

<p>The w3schools list \xc3 as LATIN CAPITAL LETTER A WITH TILDE and \xa9 as COPYRIGHT SIGN.</p>

<p>Assuming this is not a problem with Python encoding, how should I be coding these NLS characters in Python.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/56134835/python-nls-http-encoding,"['python', 'utf-8', 'python-requests', 'python-unicode']",99,False,1,1
Error starting Spring Boot microservice with KPL/KCL enabled,"<p>I am starting my Spring Boot microservice locally with Localstack running. When I start it with <code>spring.cloud.stream.kinesis.binder.kpl-kcl-enabled=false</code>, it starts just fine. Setting this value to <code>true</code> causes the following stack trace.:</p>

<pre><code>Unable to load credentials from com.amazonaws.auth.profile.ProfileCredentialsProvider@58faba32: Unable to load credentials into profile [default]: AWS Access Key ID is not specified.
c.a.s.kinesis.producer.KinesisProducer   : Error in child process
java.lang.RuntimeException: Error running child process
at com.amazonaws.services.kinesis.producer.Daemon.fatalError(Daemon.java:533)
at com.amazonaws.services.kinesis.producer.Daemon.fatalError(Daemon.java:513)
at com.amazonaws.services.kinesis.producer.Daemon.access$200(Daemon.java:63)
at com.amazonaws.services.kinesis.producer.Daemon$1.run(Daemon.java:135)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.amazonaws.SdkClientException: Unable to load AWS credentials from any provider in the chain: [com.amazonaws.auth.EC2ContainerCredentialsProviderWrapper@71435b85: Unable to load credentials from service endpoint, com.amazonaws.auth.profile.ProfileCredentialsProvider@58faba32: Unable to load credentials into profile [default]: AWS Access Key ID is not specified.]
at com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:136)
at com.amazonaws.services.kinesis.producer.Daemon.makeSetCredentialsMessage(Daemon.java:565)
at com.amazonaws.services.kinesis.producer.Daemon.startChildProcess(Daemon.java:436)
at com.amazonaws.services.kinesis.producer.Daemon.access$100(Daemon.java:63)
at com.amazonaws.services.kinesis.producer.Daemon$1.run(Daemon.java:133)
</code></pre>

<p>In the <a href=""https://spring.io/blog/2019/11/27/spring-integration-aws-2-3-ga-and-spring-cloud-stream-kinesis-binder-2-0-ga-available"" rel=""nofollow noreferrer"">release announcement for the 2.0.0 version of the Kinesis Cloud Stream Kinesis Binder</a>, it states that ""the main theme of both these releases is about an integration testing using a Local Stack framework which helped us to spot several bugs and race conditions in both libraries.""</p>

<p>I have <code>AWS_ACCESS_KEY_ID</code> and <code>AWS_SECRET_ACCESS_KEY</code> set as environment variables alongside other environment variables that my Docker stack uses, so I'm confused why I'm receiving this error. </p>

<p>Are there any additional configurations I need to specify so that I can enable KPL/KCL and run and test it locally using LocalStack?</p>
",https://stackoverflow.com/questions/59507293/error-starting-spring-boot-microservice-with-kpl-kcl-enabled,['spring-cloud-stream'],959,False,0,1
How to properly write unit tests for router modules in NodeJS,"<p>I'm new to nodeJS and testing and I'd like to know how I can test my application routes properly. I've read some articles that uses <strong>supertest</strong> and <strong>chai-http</strong> to call the POST method but I believe this way would be more of an integration testing instead of unit testing my app.</p>

<p>I've read about Sinon but I'm having a hard time applying it on my code like I don't know what to stub, how I can manipulate the data from the request body so I can cover different branches of my conditional statements. I'm monitoring my code coverage with <strong>nyc</strong> so I'm also aiming to increase my unit test coverage.</p>

<p>I would appreciate it a lot if someone can guide me on this. Thanks in advance! </p>

<p><strong>server.js</strong></p>

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

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
    extended: true
}));

app.listen(8080, function () {
    logger.info('App is now running on port 8080');
});

app.use('/', require('./routes/generateURL.js'));

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

<p><strong>generateURL.js</strong></p>

<pre><code>const express = require('express');
const router = express.Router();

router.post('/generate-url', (req, res) =&gt; {
    let result = {
        status: false
    };
    const acctId = req.body.accountId;
    const baseURL = 'http://somecompany.com/billing/';
    const dateToday = new Date();

    try {
        if (accountId) {
            result.status = true;
            result.bill = baseURL + acctId + '/' + dateToday;
        } else {
            throw 'Missing accountId';
        }
    } catch(err){
        console.log(err);
    }

    return res.send(result);
});

module.exports = router;
</code></pre>
",https://stackoverflow.com/questions/54804948/how-to-properly-write-unit-tests-for-router-modules-in-nodejs,"['node.js', 'unit-testing', 'express', 'mocha.js', 'sinon-chai']",107,False,2,0
How can you make file paths &#39;OS agnostic&#39; in nodejs?,"<p>I'm working on some code right now that is screwing up in our integration testing because we run a test job on a EC2 instance of a Windows machine. After fixing the filenames-are-too-long issue, a lot of the paths still aren't resolved properly because many of them are hard-coded for UNIX.</p>

<p>I was looking into nodejs' Path module but I'm not sure what all needs to be changed to make the path names work on both operating systems (other than the backslashes of course). Do I need to prefix these path names for Windows?</p>

<p>Here's some of the code this is failing on:</p>

<pre><code>function getDirectories(srcpath) {
//srcPath looks like graph-validator/tests/data/graph-examples/
  return fs.readdirSync(srcpath).filter(function(file) {
    return (
      file !== '.git' &amp;&amp; fs.statSync(path.join(srcpath, file)).isDirectory()
    )
  })
}

const dataDirectory = 'graph-validator/tests/data/'

// Generate valid input for included minimal tests
function createDatasetFileList(path) {

  const testDatasetPath = `${dataDirectory}${path}`
 //path is often 'graph-examples/ds001/' 
  if (!isNode) {

    return createFileList(testDatasetPath)
  } else {
    return testDatasetPath
    // testDatasetPath = graph-validator/tests/data/graph-examples/ds001/

  }
}
</code></pre>

<p>I tried <code>path.join()</code> and this seems to partially solve this, at least the slashes.  How can I make these path names fully agnostic across OS'? </p>
",https://stackoverflow.com/questions/59379150/how-can-you-make-file-paths-os-agnostic-in-nodejs,"['javascript', 'node.js', 'path', 'filesystems', 'filenames']",467,False,2,1
How to have bean of repository interface of spring data jpa during run of test cases,"<p>We have written below 2 classes </p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
public class AbcFilterTest {

    @Autowired
    private AbcUtils abcUtils;

    @Autowired
    private AbcRepository abcRepository;

    @Test
    public void testFilter() {

        MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
        MockHttpServletResponse httpServletResponse = new MockHttpServletResponse();
        MockFilterChain mockChain = new MockFilterChain();

    }
}

    @Configuration
    @ComponentScan(basePackageClasses = {AbcUtils.class, AbcRepository.class,})
    public class TestConfig {
    }
</code></pre>

<p>For running a test class, i need instance of both AbcUtilsclass and AbcRepository interface(extending CurdRepository) which are autowired in the class i am testing.1st one has @Component while 2nd has @Repositry on top of it.As you can see,in my test class I have autowired both util and repository class with component scan as above code.In real time spring framework creates implementaion class for the repository interface but On running test case,I am getting below error </p>

<blockquote>
  <p>Caused by: org.springframework.beans.BeanInstantiationException:
  Failed to instantiate [com.a.b.c.persistence.AbcRepository]: Specified
  class is an interface.</p>
</blockquote>

<p>Kindly suggest how to make this test class work. Please note that we are not using Spring Boot and Mockito.We are doing integration testing.
We are using Spring rest and Spring Data JPA with hibernate.</p>
",https://stackoverflow.com/questions/57499754/how-to-have-bean-of-repository-interface-of-spring-data-jpa-during-run-of-test-c,"['spring', 'junit', 'spring-data-jpa', 'spring-test']",733,False,1,1
How to test if an exception was raised and handled in code path?,"<p>I am writing an <strong>integration</strong> <strong>test</strong> (not a mocked unit test) to check behavior for the usecase where user doesn't have sufficient permissions to access aws resource say an S3 bucket. </p>

<p>Here is how the code looks like:</p>

<pre><code>MyService svcClient = new MyService(permissions);
</code></pre>

<p>Line above consumes all exceptions(eg. Access Denied to S3 - S3Exception, returns a null object. </p>

<p>While I can certainly test behavior with the following </p>

<pre><code>Assertions.assertThrows( NullPointerException.class, () -&gt; svcClient.methodCall());
</code></pre>

<p>I am not able to express that there was an spectific exception like S3Exception that was raised with the message Access Denied. </p>

<h1>Question:</h1>

<ol>
<li><p>How do I test whether certain exception was <strong>raised and
handled/consumed</strong> in code path ? </p></li>
<li><p>If there is no way, is it generally out of scope during integration
testing to test such behavior and does it fall into behavorial
testing?</p></li>
</ol>

<p>Any guidance here is appreciated. Thanks.</p>
",https://stackoverflow.com/questions/59183415/how-to-test-if-an-exception-was-raised-and-handled-in-code-path,"['java', 'junit', 'junit5']",169,False,1,0
Integration testings on swift?,"<p>I have an app that I'm testing right now, 
a big part of my app is using an enclosed library that does REST calls to a server to update and take out data and then is doing stuff with that data.</p>

<p>most of these ""calls"" are happening inside my interactor. and in order to check it, I need to call them.</p>

<p>calling this functions doesn't return me the reply i usually get from them, and i looked for an integration testing tutorial or something for xcode or swift, and couldn't find one.  </p>

<p>am I approaching this wrong ? or what am I doing wrong?</p>

<p>here is an example of one of my interactor functions:</p>

<pre><code> func SDKAuthenticatedSussfuly(_ errorHandle: @escaping (String) -&gt; Void, _ completion: @escaping (AWSDKConsumer) -&gt; Void) {

        AWSDKAuthenticationService.authenticateConsumer(withUsername: sdkUsername, password: sdkPassword, consumerAuthKey: nil) {[weak self] (result, error) in


            if (result != nil) {

                guard let consumer = result as? AWSDKConsumer else {
                    NSLog(""Unexpected authentication result"")
                    return
                }

                isUserLoggedIn = true
                completion(consumer)

            } else {
               errorHandle(WhiteLabeler.localizedStringForKey(key: ""loginScreen_error_wrongUsername"", comment: ""-"", defaultValue: ""Wrong Username or Password""))
            }

        }

    }
</code></pre>

<p>and an example of a unitest i'm writing (that fails due to the rest call doesn't go inside the callback):</p>

<pre><code>func testLoginScreen() {
        let homeInteractor: HomeInteractor = HomeInteractor ()

        homeInteractor.initSDK()

        sleep(4)

        homeInteractor.loginUser(userNameText: ""a@a.com"", passwordText: ""Password1"")

        XCTAssertEqual(isInitlized, true)

    }
</code></pre>
",https://stackoverflow.com/questions/54866788/integration-testings-on-swift,"['swift', 'xcode']",221,False,0,0
Autoscaling group lifecycle hook not called when ASG deleted by CloudFromation,"<p>I have an autoscaling group created by CloudFormation.  When a scale out or scale in event occurs, I have configured an SNS topic to trigger a lambda function.  Everything works as expected, except when I delete my CloudFormation stack.</p>

<p>When I delete my CloudFormation stack (I use short-lived stacks for integration testing), the autoscaling group is deleted and the instances enter the Terminating:Wait stage as expected.  But, the <code>autoscaling:EC2_INSTANCE_TERMINATING</code> lifecycle hook is never called (neither the Lambda monitoring nor the CloudWatch logs show any evidence of the lifecycle hook getting called).  The autoscaling group appears to wait for the heartbeat timeout to expire, then deletes the instances and the autoscaling group.</p>

<p>Is there a way I can have the <code>autoscaling:EC2_INSTANCE_TERMINATING</code> lifecycle hook called when the EC2 instances are terminated because the ASG is deleted?</p>
",https://stackoverflow.com/questions/59277653/autoscaling-group-lifecycle-hook-not-called-when-asg-deleted-by-cloudfromation,"['amazon-web-services', 'amazon-ec2', 'aws-lambda', 'aws-cloudformation', 'autoscaling']",518,True,0,1
"Integration Testing Nodejs/Express/Mongoose with Jest/Supertest One Mongoose Model Saves, One Mongoose Model Doesn&#39;t","<p>I use Postman and the ReactJS UI to call this registration execution and it works as I expect. Ironically, the Jest and Supertest integration tests do not produce expected results. When integration testing, the Profile is created and the User is not.</p>

<p>The architecture is pretty simple. MongoDB in a Docker container, and Node using nodemon in VSCode. </p>

<p>I have to be doing something wrong, I just can't spot what it is.</p>

<pre><code>
// The Integration Test __test__/users/../user.test.js

const app = require('../../app');
const uuidv4 = require('uuid/v4');
const User = require('../../src/models/User');
const Profile = require('../../src/models/Profile');
const bcrypt = require('bcryptjs');
const mongoose = require('mongoose');
const request = require(""supertest"");

const {
    MONGO_URI,
    TEST_DB_NAME
} = process.env;
let DB_URI = MONGO_URI + TEST_DB_NAME;
let NAME = TEST_DB_NAME;

mongoose.connect(DB_URI, {
    useNewUrlParser: true,
    useCreateIndex: true,
    dbName: NAME
});

describe('User Integration Test', () =&gt; {
    // make sure app is imported without issues
    it('Has App Defined', () =&gt; {
        expect(app).toBeDefined();
    });

    let server;

    beforeAll(async () =&gt; {
        // Clear Test Data
        await User.deleteMany({});
        await Profile.deleteMany({});
        server = await app.listen(3001);
    });

    afterAll(async (done) =&gt; {
        // Clear Test Data
        await User.deleteMany({});
        await Profile.deleteMany({});
        // Close server
        await server.close(done);
    });

    describe('User route tests', () =&gt; {

        it('Can Register a User', async () =&gt; {
            const body = {
                ""username"": ""User21"",
                ""email"": ""user21@user.com"",
                ""password"": ""123456"",
                ""avatar"": ""image.jpg""
            }
            await request(server)
                .post('/api/v1/users')
                .send(body)
                .set('Accept', 'application/json')
                .set('Content-Type', 'application/json')
                .expect(200)
        });

});

// THE EXPRESS ROUTE in api/v1/users.js

const express = require('express');
const auth = require('../../middleware/auth');
const router = express.Router();
const { UserService } = require('../../services');
const {
    check,
    validationResult
} = require('express-validator/check');

// @route   POST api/users
// @desc    Register User
// @access  Public
// @return  status message
router.post('/', [
    check('email', 'Please provide a valid email address').isEmail(),
    check('password', 'Please enter a password with 6 or more characters').isLength({ min: 6 }),
    check('username', 'Username is Required.').not().isEmpty()
], async (req, res, next) =&gt; {
    try {
        //--Validate
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({
                errors: errors.array()
            });
        }

        const message = await UserService.register(req.body);
        return res.status(200).json(message)

    } catch (err) {
        next(err);
    }
});

// THE register METHOD found in ../../services/UserService.js

const register = async (data) =&gt; {
    try {

        // Destructure the data
        const {
            username,
            email,
            password,
            avatar
        } = data;

        // remove spaces from username and lcase it
        let user_name = username.replace(/\s/g, '').toLowerCase();
        // Check if the username or email already exists
        await doesUserExist(user_name, email);
        // Create a new user 
        const token = uuidv4();
        user = new User({
            email: email.toLowerCase(),
            username: user_name,
            avatar: avatar,
            verifyEmailToken: token
        });

        // encrypt the password
        const salt = await bcrypt.genSalt(10);
        user.password = await bcrypt.hash(password, salt);
        // Save the user
        // (Works Unless Running Jest Integration Tests)
        await user.save(); 

        // Create and save an empty Profile for the new user
        profile = new Profile();
        profile.user = user;
        // (Always Works)
        await profile.save();

        // Send verification email
        await send(user, 'Verify Your Email', token, 'verify-email.html');

        return { message: 'User was registered successfully.' };


    } catch (err) {
        throw err;
    }
}

// Does user exist method found in ./UserService.js
const doesUserExist = async (username, email) =&gt; {

    // Check if user exists by email
    let message = await checkEmail(email);
    if (!message.email_available) {
        throw new Error('Email already exists');
    }
    // Check if user exists by username
    message = await checkUserName(username.toLowerCase())
    if (!message.username_available) {
        throw new Error('Username already exists');
    }
    return false;
}

</code></pre>

<p>When I call this code via the UI, Postman, or curl both the User and Profile are created, as expected.</p>

<p>When I run the Integration Test, npm run test:integration or npm test,
Only the Profile is created.</p>

<p>my package.json scripts:
""test"": ""jest"",
""test:integration"": ""jest --testPathPattern integration.test"",</p>

<p>Finally, no errors are reported anywhere. User simply isn't created.</p>
",https://stackoverflow.com/questions/56755677/integration-testing-nodejs-express-mongoose-with-jest-supertest-one-mongoose-mod,"['mongodb', 'express', 'jestjs', 'mongoose-schema', 'supertest']",2047,False,0,2
Spring Test Module vs Mockito,"<p>I am learning about integration testing a spring app that communicates with a rest API. I found out from this <a href=""https://www.baeldung.com/spring-mock-rest-template"" rel=""nofollow noreferrer"">article</a> that spring test supports two ways to do, what I assume the same thing.</p>
<ol>
<li>Create a mockserver using <code>MockRestServiceServer</code></li>
<li>Create a mock object using <code>Mockito</code></li>
</ol>
<p>I understand that the former intercepts http request; then returns the objects, while the latter returns the object directly without bothering with any http requests at all.
Since in the end, at least in most cases, we just verify the object retrieved and compare it to the expected result.</p>
<p>So, my Questions; if try to compare:</p>
<ol>
<li><p>What are possible trade-offs; if I choose either one of them?</p>
</li>
<li><p>Are there any advantages of choosing one than the other?</p>
</li>
<li><p>For which cases would I prefer one compared to the other (possible
use cases of each)?</p>
</li>
</ol>
",https://stackoverflow.com/questions/57107805/spring-test-module-vs-mockito,"['java', 'spring', 'mockito', 'integration-testing', 'junit5']",276,True,4,1
"FlutterDriver problem, not able to find Widget by Key","<p>I am having a problem in terms of finding the widget by key in SerializableFinder, what can I do to solve this?</p>

<p>I have tried on making the key with constants and I made sure to check that the key is the same as the one in finder by providing constants. Besides, I was referring to this link : <a href=""https://stackoverflow.com/questions/55460993/flutter-driver-test-bottomnavigationbaritem"">Flutter Driver: Test BottomNavigationBarItem</a></p>

<p>Here is the code:
Integration test file (example part, not a full code): </p>

<pre><code>// todo: bottom navigation pressed
    test('bottom navigation bar test item', () async{

      // todo: intended = pressed favorite dessert, but we want to test
      await flutterDriver.waitFor(bottomNavigationBar);

      // todo: bottom navigation bar item text research
      await flutterDriver.tap(dessert); // intended : tap at bottom navigation view item

      print('This is Dessert section');

      // todo: expect title is keyword

      await flutterDriver.tap(seafood);

      print('This is Seafood section');

      await flutterDriver.tap(favoriteDessert);

      print('This is Favorite Dessert section');

      await flutterDriver.tap(favoriteSeafood);

      print('This is Favorite Seafood section');


    });
</code></pre>

<p>Finder file (for bottom navigation bar thing):</p>

<pre><code>SerializableFinder bottomNavigationBar = find.byValueKey(BOTTOM_NAVIGATION_BAR);

SerializableFinder dessert = find.byValueKey(DESSERT);
SerializableFinder seafood = find.byValueKey(SEAFOOD);
SerializableFinder favoriteDessert = find.byValueKey(FAVORITE_DESSERT);
SerializableFinder favoriteSeafood = find.byValueKey(FAVORITE_SEAFOOD);
</code></pre>

<p>Widget file (2 parts):
Part 1: bottom navigation bar items</p>

<pre><code>List&lt;BottomNavigationBarItem&gt; bottomNavigationBarItems = [
    BottomNavigationBarItem(
        icon: Icon(Icons.cake, key: Key(DESSERT)), title: Text(""Dessert"")),
    BottomNavigationBarItem(
        icon: Icon(Icons.restaurant, key : Key(SEAFOOD)), title: Text(""Seafood"")),
    BottomNavigationBarItem(
        icon: Icon(Icons.cake, key: Key(FAVORITE_DESSERT)), title: Text(""Favorite Dessert"")),
    BottomNavigationBarItem(
        icon: Icon(Icons.restaurant, key: Key(FAVORITE_SEAFOOD)), title: Text(""Favorite Seafood""))
  ];
</code></pre>

<p>Part 2: bottom navigation bar</p>

<pre><code> bottomNavigationBar: BottomNavigationBar(
        key: Key(BOTTOM_NAVIGATION_BAR),
        items: bottomNavigationBarItems,
        currentIndex: currentIndex,
        onTap: (index) {
          changeSelectedBottomNavigationBarItem(index);
        },
        selectedItemColor: appConfig.appColor,
        unselectedItemColor: Colors.grey,
      ),
</code></pre>

<p>If you want to provide full code just request it, I will be more than happy to provide them.</p>

<p>Expected results : When doing integration testing, the app will automatically navigate selected item</p>

<p>Actual result : </p>

<p>Sneak peek:</p>

<pre><code>00:02 +0: Meals Catalogue App bottom navigation bar test item
[warning] FlutterDriver: waitFor message is taking a long time to complete...
00:32 +0 -1: Meals Catalogue App bottom navigation bar test item [E]
  TimeoutException after 0:00:30.000000: Test timed out after 30 seconds.
</code></pre>

<pre><code>00:32 +0 -1: Meals Catalogue App (tearDownAll)
00:32 +0 -1: Meals Catalogue App bottom navigation bar test item [E]
  DriverError: Failed to fulfill WaitFor due to remote error
  Original error: Bad state: The client closed with pending request ""ext.flutter.driver"".
</code></pre>

<p>Since the stack trace is a bit too long in the link, I will provide my pastebin into here: <a href=""https://pastebin.com/p4ktKXLA"" rel=""noreferrer"">https://pastebin.com/p4ktKXLA</a></p>
",https://stackoverflow.com/questions/56492561/flutterdriver-problem-not-able-to-find-widget-by-key,"['flutter', 'integration-testing']",4518,True,12,1
Mocking a dependent class using Mockito in JAVA,"<p>I am quite new to Mockito. I apologise if my question sounds sill. I have a standalone JAVA application for which I have to write Unit test cases using JUnit and Mockito. The important thing is that I cannot change the code as it has been written by someone else and Integration testing has been completed. I have tried to search for similar questions, but couldnt find anything. Solutions suggested in somewhat similar questions, didnt work :(</p>

<p>I have attached the flow control diagram.I want to mock the dependent classes. For example when I am Unit testing 'Class 1 --> Method 1', I want to mock the output of 'Method 2 in Class 2' WITHOUT CALLING it. I have tried to use Mockito.when and Mockito.doReturn. Both call the dependent methods. </p>

<p>Can someone please suggest me some ideas to achieve this ?</p>

<p><a href=""https://i.stack.imgur.com/A201b.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/A201b.jpg"" alt=""Flow of Control""></a></p>

<pre class=""lang-java prettyprint-override""><code>//Pseudocode of Class 1
public class Class1 {
    public boolean method1() {
        Class2 c2 = new Class2();
        boolean b1 = c2.method2();
    }
}

//Pseudocode of Class 2
public class Class2 {
    public boolean method2() {
        Class3 c3 = new Class3();
        boolean b2 = c3.method3();
    }
}

... Likewise same for Class 3, 4 and 5
</code></pre>
",https://stackoverflow.com/questions/59190782/mocking-a-dependent-class-using-mockito-in-java,"['java', 'mockito', 'powermock', 'stub']",3656,True,3,2
Is it a good practice to unit test controller classes in Spring MVC,"<p>I used to unit test my controller classes just like any other normal Java class. I mean without using Spring's MockMvc. But then I realized that this way I won't be able to be sure that I've set up the MVC configuration correctly. So if I have controller like this:</p>

<pre><code>@Restcontroller
@RequestMapping(""/cars"")
public class CarController{
    private CarService carService;
    public CarController (CarService service){this.carService = service};
    @GetMapping
    public List&lt;Car&gt; getCar(@RequestParam(""filter"") String filter){
       if(filter!=null &amp;&amp; !filter.trim().equal("""")){
          //omitted for brevity
       }
    }
}
</code></pre>

<p>and if I unit test its <code>getCar</code> method directly, even if the test passes, that won't mean my controller is alright. So instead of unit testing, I started actually doing integration testing. Something like this:</p>

<pre><code>mockMvc.perform(get(""/v1/cars?filter = Honda""))....  bla bla bla
</code></pre>

<p>Recently a question arose if we should first unit test and the integration test rest controllers. At first glance, it seems to me that integration test does, in the end, check the correct behavior of the controller. But on the other hand, how good is that to rely on integration test only.</p>
",https://stackoverflow.com/questions/55649851/is-it-a-good-practice-to-unit-test-controller-classes-in-spring-mvc,"['spring', 'unit-testing', 'controller', 'integration-testing']",958,True,2,1
Zookeeper + Solr in TestContainers,"<p>I'm using org.testcontainers to perform integration testing with Solr.  </p>

<p>[Using SolrJ in my unit tests]  </p>

<p>When I start Solr in cloud mode, using an embedded ZooKeeper instance, I'm able to connect to the solr instance from my unit test, but unable to connect to ZooKeeper from my SolrClient.<br>
I think this is because embedded ZooKeeper is bound to IP 127.0.0.1 and inaccessible.  </p>

<p>If I start two separate containers [using a shared network], ZooKeeper and Solr, I can connect Solr to ZooKeeper, and I can connect to Zookeeper from my unit tests, BUT when Zookeeper returns the active SOLR node, it return the internal server IP which is not accessible from my unit test [in my SolrJ client].  </p>

<p>I'm not sure where to go with this.<br>
Maybe there is a network mode that will do address translation?  </p>

<p>Thoughts?  </p>
",https://stackoverflow.com/questions/58001396/zookeeper-solr-in-testcontainers,"['solr', 'apache-zookeeper', 'solrj', 'testcontainers']",1267,True,1,2
Spring integration mail imap inbound adapter throws exception after integration flow change,"<p>I have configured the following imap-inbound-adapter to receive  mails from an inbox.</p>

<pre><code>@Bean
public IntegrationFlow incomingMailFlow(MailProperties properties,
                                        MimeMessageToMailMessageTransformer mimeMessageToMailMessageTransformer,
                                        SubscribableChannel errorChannel,
                                        SubscribableChannel notificationChannel
) {
    return IntegrationFlows
            .from(Mail.imapIdleAdapter(properties.getImapUrl())
                    .javaMailProperties(p -&gt; p
                            .put(""mail.imap.starttls.enable"", ""true"")
                            .put(""mail.imap.ssl.trust"", ""*""))
                    .errorChannel(errorChannel)
                    .shouldDeleteMessages(properties.getDeleteMessages())
            )
            .transform(mimeMessageToMailMessageTransformer)
            .channel(notificationChannel)
            .get();
}
</code></pre>

<p>To enable integration testing i changed the the configuration (for testing i want to replace the imapIdleAdapter with test configuration):</p>

<pre><code>@Bean
public SubscribableChannel incomingMailChannel() {
    return MessageChannels
            .publishSubscribe(""incomingMailChannel"")
            .get();
}

@Bean
public IntegrationFlow imapAdapter(MailProperties properties, SubscribableChannel errorChannel,
                                   SubscribableChannel incomingMailChannel) {
    return from(Mail.imapIdleAdapter(properties.getImapUrl())
            .javaMailProperties(p -&gt; p
                    .put(""mail.imap.starttls.enable"", ""true"")
                    .put(""mail.imap.ssl.trust"", ""*""))
            .errorChannel(errorChannel)
            .channel(incomingMailChannel)
            .get();
}

@Bean
public IntegrationFlow incomingMailFlow(SubscribableChannel incomingMailChannel,
                                        MimeMessageToMailMessageTransformer mimeMessageToMailMessageTransformer,
                                        SubscribableChannel notificationChannel
) {
    return IntegrationFlows
            .from(incomingMailChannel)
            .transform(mimeMessageToMailMessageTransformer)
            .channel(notificationChannel)
            .get();
}
</code></pre>

<p>UPDATE: I could run the JavaMail debug, but i had to remove some content in order to post the logfile output (max. 30_000 characters)</p>

<pre><code>javax.mail                               : Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
javax.mail                               : successfully loaded resource: /META-INF/javamail.default.address.map
o.s.b.f.s.DefaultListableBeanFactory     : Returning cached instance of singleton bean 'taskScheduler'
javax.mail                               : getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle]
com.sun.mail.imap                        : mail.imap.fetchsize: 16384
com.sun.mail.imap                        : mail.imap.ignorebodystructuresize: false
o.s.b.w.s.f.OrderedRequestContextFilter  : Filter 'requestContextFilter' configured successfully
com.sun.mail.imap                        : mail.imap.statuscachetimeout: 1000
.b.w.s.f.OrderedHttpPutFormContentFilter : Initializing filter 'httpPutFormContentFilter'
.b.w.s.f.OrderedHttpPutFormContentFilter : Filter 'httpPutFormContentFilter' configured successfully
.s.b.w.s.f.OrderedHiddenHttpMethodFilter : Initializing filter 'hiddenHttpMethodFilter'
.s.b.w.s.f.OrderedHiddenHttpMethodFilter : Filter 'hiddenHttpMethodFilter' configured successfully
com.sun.mail.imap                        : mail.imap.appendbuffersize: -1
s.b.w.s.f.OrderedCharacterEncodingFilter : Initializing filter 'characterEncodingFilter'
s.b.w.s.f.OrderedCharacterEncodingFilter : Filter 'characterEncodingFilter' configured successfully
com.sun.mail.imap                        : mail.imap.minidletime: 10
com.sun.mail.imap                        : enable STARTTLS
com.sun.mail.imap                        : peek
com.sun.mail.imap                        : closeFoldersOnStoreFailure
o.s.integration.mail.ImapMailReceiver    : connecting to store [imap://user:*****@mailserver:143/INBOX]
com.sun.mail.imap                        : trying to connect to host ""mailserver"", port 143, isSSL false
io.undertow                              : starting undertow server io.undertow.Undertow@7c3ebc6b
io.undertow                              : Configuring listener with protocol HTTP for interface 0.0.0.0 and port 8080
com.sun.mail.imap                        : AUTH: PLAIN
com.sun.mail.imap                        : protocolConnect login, host=mailserver, user=user, password=&lt;non-null&gt;
o.s.b.w.e.u.UndertowServletWebServer     : Undertow started on port(s) 8080 (http) with context path ''
d.e.m.applicationApplication            : Started applicationApplication in 20.603 seconds (JVM running for 21.067)
com.sun.mail.imap.connectionpool         : getStoreProtocol() borrowing a connection
com.sun.mail.imap.connectionpool         : getStoreProtocol() - connection available -- size: 1
com.sun.mail.imap.connectionpool         : getStoreProtocol() -- storeConnectionInUse
com.sun.mail.imap.connectionpool         : releaseFolderStoreProtocol()
o.s.integration.mail.ImapMailReceiver    : opening folder [imap://user:*****@mailserver:143/INBOX]
com.sun.mail.imap                        : connection available -- size: 1
com.sun.mail.imap.messagecache           : create cache of size 0
o.s.integration.mail.ImapMailReceiver    : This email server does not support RECENT flag, but it does support USER flags which will be used to prevent duplicates during email fetch. This receiver instance uses flag: spring-integration-mail-adapter
com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Pool stats (total=10, active=0, idle=10, waiting=0)
com.sun.mail.imap.messagecache           : add 1 messages
com.sun.mail.imap.messagecache           : create message number 1
com.sun.mail.imap                        : IMAPProtocol noop
com.sun.mail.imap.connectionpool         : getStoreProtocol() - no connections in the pool, creating a new one
com.sun.mail.imap                        : AUTH: PLAIN
com.sun.mail.imap.connectionpool         : getStoreProtocol() -- storeConnectionInUse
com.sun.mail.imap                        : IMAPProtocol noop
com.sun.mail.imap.connectionpool         : releaseStoreProtocol()
o.s.integration.mail.ImapMailReceiver    : attempting to receive mail from folder [INBOX]
o.s.integration.mail.ImapMailReceiver    : This email server does not support RECENT flag, but it does support USER flags which will be used to prevent duplicates during email fetch. This receiver instance uses flag: spring-integration-mail-adapter
p.s.integration.mail.ImapMailReceiver    : found 1 new messages
o.s.integration.mail.ImapMailReceiver    : Received 1 messages
o.s.integration.mail.ImapMailReceiver    : USER flags are supported by this mail server. Flagging message with 'spring-integration-mail-adapter' user flag
javax.activation                         : MailcapCommandMap: load HOME
javax.activation                         : new MailcapFile: file /home/mailAppUser/.mailcap
javax.activation                         : MailcapCommandMap: load SYS
javax.activation                         : new MailcapFile: file /usr/lib/jvm/java-8-oracle/jre/lib/mailcap
javax.activation                         : MailcapCommandMap: load JAR
javax.activation                         : MailcapCommandMap: getResources
javax.activation                         : MailcapCommandMap: URL jar:file:/var/application/application_customer_1.0.0.jar!/BOOT-INF/lib/javax.mail-1.5.5.jar!/META-INF/mailcap
javax.activation                         : new MailcapFile: InputStream
javax.activation                         : parse: text/plain;;      x-java-content-handler=com.sun.mail.handlers.text_plain
javax.activation                         :   Type: text/plain
javax.activation                         :     Command: content-handler, Class: com.sun.mail.handlers.text_plain
...more conten parser ...
javax.activation                         : Merging commands for type text/*
javax.activation                         : MailcapCommandMap: successfully loaded mailcap file: /META-INF/mailcap.default
javax.activation                         : MailcapCommandMap: createDataContentHandler for multipart/alternative
javax.activation                         :   search DB #1
javax.activation                         :   search DB #2
javax.activation                         :   search fallback DB #1
javax.activation                         :     got content-handler
javax.activation                         :       class com.sun.mail.handlers.multipart_mixed
com.sun.mail.imap.connectionpool         : connection pool current size: 1   pool size: 1
com.sun.mail.imap                        : pool is full, not adding an Authenticated connection
o.s.i.mail.ImapIdleChannelAdapter        : received 1 mail messages
o.s.i.mail.ImapIdleChannelAdapter        : Task completed successfully. Re-scheduling it again right away.
o.s.i.mail.ImapIdleChannelAdapter        : waiting for mail
com.sun.mail.imap.connectionpool         : getStoreProtocol() - connection available -- size: 1
com.sun.mail.imap.connectionpool         : getStoreProtocol() -- storeConnectionInUse
com.sun.mail.imap                        : IMAPProtocol noop
com.sun.mail.imap.connectionpool         : releaseStoreProtocol()
com.sun.mail.imap.connectionpool         : getStoreProtocol() borrowing a connection
com.sun.mail.imap.connectionpool         : getStoreProtocol() - connection available -- size: 1
com.sun.mail.imap.connectionpool         : getStoreProtocol() -- storeConnectionInUse
o.s.integration.channel.DirectChannel    : preSend on channel 'incomingMailFlow.channel#0', message: GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}]
com.sun.mail.imap.connectionpool         : releaseFolderStoreProtocol()
o.s.integration.mail.ImapMailReceiver    : opening folder [imap://user:*****@mailserver:143/INBOX]
com.sun.mail.imap                        : connection available -- size: 1
com.sun.mail.imap.messagecache           : create cache of size 0
o.s.integration.mail.ImapMailReceiver    : This email server does not support RECENT flag, but it does support USER flags which will be used to prevent duplicates during email fetch. This receiver instance uses flag: spring-integration-mail-adapter
o.s.integration.filter.MessageFilter     : incomingMailFlow.org.springframework.integration.filter.MessageFilter#0 received message: GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}]
d.e.m.i.n.i.m.UniqueMimeMessageIdFilter  : Storing the message id &lt;&lt;1dacefec9d29bcaeda907d98@customer-cust.com&gt;&gt;
o.hibernate.internal.util.EntityPrinter  : Listing entities:
o.hibernate.internal.util.EntityPrinter  : de.company.application.mail.domain.MailIdEntity{messageId=&lt;1dacefec9d29bcaeda907d98@customer-cust.com&gt;, id=1266391}
o.s.integration.channel.DirectChannel    : preSend on channel 'incomingMailFlow.channel#1', message: GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}]
o.s.i.t.MessageTransformingHandler       : incomingMailFlow.org.springframework.integration.transformer.MessageTransformingHandler#0 received message: GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}]
i.m.MimeMessageToMailMessageTransformer : transforming mail: org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c
javax.activation                         : MailcapCommandMap: createDataContentHandler for text/plain
javax.activation                         :   search DB #1
javax.activation                         :     got content-handler
javax.activation                         :       class com.sun.mail.handlers.text_plain
com.sun.mail.imap                        : IMAPProtocol noop
o.s.i.channel.PublishSubscribeChannel    : preSend on channel 'errorChannel', message: ErrorMessage [payload=org.springframework.integration.transformer.MessageTransformationException: Failed to transform Message; nested exception is org.springframework.messaging.MessageHandlingException: nested exception is de.company.application.integration.notification.incoming.exception.MailMessageTransformerException: Failed to parse mail message data from mime message, failedMessage=GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}], failedMessage=GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}], headers={id=e015fc76-8c9c-f8b8-9d3f-b4775569ee11, timestamp=1551259380881}] for original GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}]
o.s.i.router.MethodInvokingRouter        : errorRouterFlow.org.springframework.integration.router.MethodInvokingRouter#0 received message: ErrorMessage [payload=org.springframework.integration.transformer.MessageTransformationException: Failed to transform Message; nested exception is org.springframework.messaging.MessageHandlingException: nested exception is de.company.application.integration.notification.incoming.exception.MailMessageTransformerException: Failed to parse mail message data from mime message, failedMessage=GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}], failedMessage=GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}], headers={id=e015fc76-8c9c-f8b8-9d3f-b4775569ee11, timestamp=1551259380881}] for original GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}]
d.e.m.integration.error.ErrorRouter      : Routing org.springframework.integration.transformer.MessageTransformationException: Failed to transform Message; nested exception is org.springframework.messaging.MessageHandlingException: nested exception is de.company.application.integration.notification.incoming.exception.MailMessageTransformerException: Failed to parse mail message data from mime message, failedMessage=GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}], failedMessage=GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}] to channel unknownErrorChannel
o.s.i.channel.PublishSubscribeChannel    : preSend on channel 'unknownErrorChannel', message: ErrorMessage [payload=org.springframework.integration.transformer.MessageTransformationException: Failed to transform Message; nested exception is org.springframework.messaging.MessageHandlingException: nested exception is de.company.application.integration.notification.incoming.exception.MailMessageTransformerException: Failed to parse mail message data from mime message, failedMessage=GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}], failedMessage=GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}], headers={id=e015fc76-8c9c-f8b8-9d3f-b4775569ee11, timestamp=1551259380881}] for original GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}]
o.s.integration.handler.LoggingHandler   : unknownErrorLogger received message: ErrorMessage [payload=org.springframework.integration.transformer.MessageTransformationException: Failed to transform Message; nested exception is org.springframework.messaging.MessageHandlingException: nested exception is de.company.application.integration.notification.incoming.exception.MailMessageTransformerException: Failed to parse mail message data from mime message, failedMessage=GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}], failedMessage=GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}], headers={id=e015fc76-8c9c-f8b8-9d3f-b4775569ee11, timestamp=1551259380881}] for original GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}]
 WARN o.s.integration.handler.LoggingHandler   : org.springframework.integration.transformer.MessageTransformationException: Failed to transform Message; nested exception is org.springframework.messaging.MessageHandlingException: nested exception is de.company.application.integration.notification.incoming.exception.MailMessageTransformerException: Failed to parse mail message data from mime message, failedMessage=GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}], failedMessage=GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}]
    at org.springframework.integration.transformer.MessageTransformingHandler.handleRequestMessage(MessageTransformingHandler.java:95)
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:158)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:47)
    at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:108)
    at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:203)
    at org.springframework.integration.mail.ImapIdleChannelAdapter.lambda$createMessageSendingTask$0(ImapIdleChannelAdapter.java:216)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.messaging.MessageHandlingException: nested exception is de.company.application.integration.notification.incoming.exception.MailMessageTransformerException: Failed to parse mail message data from mime message, failedMessage=GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, timestamp=1551259380290}]
    at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:107)
    at org.springframework.integration.transformer.AbstractMessageProcessingTransformer.transform(AbstractMessageProcessingTransformer.java:90)
    at org.springframework.integration.transformer.MessageTransformingHandler.handleRequestMessage(MessageTransformingHandler.java:89)
    ... 32 more
Caused by: de.company.application.integration.notification.incoming.exception.MailMessageTransformerException: Failed to parse mail message data from mime message
    at de.company.application.integration.notification.incoming.mail.MimeMessageToMailMessageTransformer.transform(MimeMessageToMailMessageTransformer.java:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at org.springframework.integration.util.MessagingMethodInvokerHelper.invokeHandlerMethod(MessagingMethodInvokerHelper.java:574)
    at org.springframework.integration.util.MessagingMethodInvokerHelper.process(MessagingMethodInvokerHelper.java:312)
    at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:104)
    ... 34 more
Caused by: de.company.application.integration.notification.incoming.exception.CreateMimeParserException: Parser for mime message could not be created
    at de.company.application.integration.notification.incoming.mail.IncomingMailParser.getMimeMessageParser(IncomingMailParser.java:47)
    at de.company.application.integration.notification.incoming.mail.MimeMessageToMailMessageTransformer.transform(MimeMessageToMailMessageTransformer.java:38)
    ... 45 more
Caused by: java.io.IOException: A7 BAD Error in IMAP command FETCH: Invalid messageset (0.000 + 0.000 secs).
    at com.sun.mail.imap.IMAPInputStream.fill(IMAPInputStream.java:159)
    at com.sun.mail.imap.IMAPInputStream.read(IMAPInputStream.java:192)
    at java.io.FilterInputStream.read(FilterInputStream.java:83)
    at java.io.PushbackInputStream.read(PushbackInputStream.java:139)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at com.sun.mail.handlers.text_plain.getContent(text_plain.java:98)
    at javax.activation.DataSourceDataContentHandler.getContent(DataHandler.java:795)
    at javax.activation.DataHandler.getContent(DataHandler.java:542)
    at javax.mail.internet.MimeBodyPart.getContent(MimeBodyPart.java:657)
    at org.apache.commons.mail.util.MimeMessageParser.parse(MimeMessageParser.java:96)
    at de.company.application.integration.notification.incoming.mail.IncomingMailParser.getMimeMessageParser(IncomingMailParser.java:45)
    ... 46 more

o.s.i.channel.PublishSubscribeChannel    : postSend (sent=true) on channel 'unknownErrorChannel', message: ErrorMessage [payload=org.springframework.integration.transformer.MessageTransformationException: Failed to transform Message; nested exception is org.springframework.messaging.MessageHandlingException: nested exception is de.company.application.integration.notification.incoming.exception.MailMessageTransformerException: Failed to parse mail message data from mime message, failedMessage=GenericMessage [payload=org.springframework.integration.mail.AbstractMailReceiver$IntegrationMimeMessage@5905215c, headers={id=49d23354-389d-e998-83f6e0a5bb3d, 
com.sun.mail.imap.connectionpool         : getStoreProtocol() - no connections in the pool, creating a new one
com.sun.mail.imap                        : AUTH: PLAIN
com.sun.mail.imap.connectionpool         : getStoreProtocol() -- storeConnectionInUse
com.sun.mail.imap                        : IMAPProtocol noop
com.sun.mail.imap.connectionpool         : releaseStoreProtocol()
o.s.integration.mail.ImapMailReceiver    : attempting to receive mail from folder [INBOX]
o.s.integration.mail.ImapMailReceiver    : This email server does not support RECENT flag, but it does support USER flags which will be used to prevent duplicates during email fetch. This receiver instance uses flag: spring-integration-mail-adapter
o.s.integration.mail.ImapMailReceiver    : found 0 new messages
o.s.integration.mail.ImapMailReceiver    : Received 0 messages
com.sun.mail.imap.connectionpool         : connection pool current size: 1   pool size: 1
com.sun.mail.imap                        : pool is full, not adding an Authenticated connection
com.sun.mail.imap.connectionpool         : releaseFolderStoreProtocol()
o.s.integration.mail.ImapMailReceiver    : opening folder [imap://user:*****@mailserver:143/INBOX]
com.sun.mail.imap                        : connection available -- size: 1
com.sun.mail.imap.messagecache           : create cache of size 0
o.s.integration.mail.ImapMailReceiver    : This email server does not support RECENT flag, but it does support USER flags which will be used to prevent duplicates during email fetch. This receiver instance uses flag: spring-integration-mail-adapter
com.sun.mail.imap.messagecache           : add 4 messages
com.sun.mail.imap.messagecache           : create message number 1
com.sun.mail.imap.messagecache           : create message number 2
com.sun.mail.imap.messagecache           : create message number 3
com.sun.mail.imap.messagecache           : create message number 4
</code></pre>

<p>UPDATE 2: i checked the mail server logfiles and found a pattern that occurs when application fails to read the mails. The application fails when there are two imap logins</p>

<pre><code>Feb 27 10:22:59 Ubuntu postfix/smtpd[3947]: connect from unknown[host-ip]
Feb 27 10:22:59 Ubuntu postfix/smtpd[3947]: A7D87C2074: client=unknown[host-ip]
Feb 27 10:22:59 Ubuntu postfix/cleanup[3949]: A7D87C2074: message-id=&lt;1dace980154b4fec9d29bcaed@customer.com&gt;
Feb 27 10:22:59 Ubuntu postfix/qmgr[1380]: A7D87C2074: from=&lt;sender@customer.com&gt;, size=5941, nrcpt=1 (queue active)
Feb 27 10:22:59 Ubuntu postfix/smtpd[3947]: disconnect from unknown[host-ip] helo=1 mail=1 rcpt=1 data=1 quit=1 commands=5
Feb 27 10:22:59 Ubuntu postfix/local[3950]: A7D87C2074: to=&lt;inbox@domain.com&gt;, orig_to=&lt;recipient@customer.com&gt;, relay=local, delay=0.01, delays=0.01/0/0/0, dsn=2.0.0, status=sent (delivered to mailbox)
Feb 27 10:22:59 Ubuntu postfix/qmgr[1380]: A7D87C2074: removed
Feb 27 10:23:00 Ubuntu dovecot: imap-login: Login: user=&lt;inbox&gt;, method=PLAIN, rip=spring-application-ip, lip=spring-application-ip, mpid=3954, secured, session=&lt;mgBQuNyCOtIKOi7N&gt;
Feb 27 10:23:00 Ubuntu dovecot: imap(inbox): Logged out in=516 out=8630
Feb 27 10:23:00 Ubuntu dovecot: imap-login: Login: user=&lt;inbox&gt;, method=PLAIN, rip=spring-application-ip, lip=spring-application-ip, mpid=3959, secured, session=&lt;8z5auNyCPNIKOi7N&gt;
Feb 27 10:23:00 Ubuntu dovecot: imap(inbox): Logged out in=352 out=1305
</code></pre>

<p>If the mails are processed successfully, the logfile entry looks like</p>

<pre><code>Feb 27 10:24:18 Ubuntu postfix/smtpd[3964]: connect from unknown[host-ip]
Feb 27 10:24:18 Ubuntu postfix/smtpd[3964]: 49C78C2074: client=unknown[host-ip]
Feb 27 10:24:18 Ubuntu postfix/cleanup[3949]: 49C78C2074: message-id=&lt;00014af9-91a9-441a-a0a@customer.com&gt;
Feb 27 10:24:18 Ubuntu postfix/qmgr[1380]: 49C78C2074: from=&lt;sender@customer.com&gt;, size=3023, nrcpt=1 (queue active)
Feb 27 10:24:18 Ubuntu postfix/local[3950]: 49C78C2074: to=&lt;inbox@domain.com&gt;, orig_to=&lt;recipient@customer.com&gt;, relay=local, delay=0.01, delays=0/0/0/0, dsn=2.0.0, status=sent (delivered to mailbox)
Feb 27 10:24:18 Ubuntu postfix/qmgr[1380]: 49C78C2074: removed
Feb 27 10:24:18 Ubuntu postfix/smtpd[3964]: disconnect from unknown[host-ip] helo=1 mail=1 rcpt=1 data=1 quit=1 commands=5
Feb 27 10:24:18 Ubuntu dovecot: imap-login: Login: user=&lt;inbox&gt;, method=PLAIN, rip=spring-application-ip, lip=spring-application-ip, mpid=3971, secured, session=&lt;Z1v9vNyCPtIKOi7N&gt;
Feb 27 10:24:18 Ubuntu dovecot: imap(inbox): Logged out in=1137 out=18905
Feb 27 10:24:51 Ubuntu postfix/qmgr[1380]: 9578BC1FDE: from=&lt;&gt;, size=2044, nrcpt=1 (queue active)
</code></pre>

<p>Update3: after i changed the deleteMessage flag to false, the error does not occur anymore. So if the mails are deleted with ImapIdleChannelAdapterSpec.shouldDeleteMessages(true) the error occurs occasionally. If it set to false, the error does never occur.</p>
",https://stackoverflow.com/questions/54864312/spring-integration-mail-imap-inbound-adapter-throws-exception-after-integration,"['java', 'spring', 'spring-integration', 'jakarta-mail']",1900,False,1,0
JEST - why mock api calls?,"<p>I'm getting familiar with JavaScript testing, and may be missing a point or two related to mocking api calls. Every tutorial I have found mocks api calls when doing unit or integration testing - example: <a href=""https://jestjs.io/docs/en/tutorial-async"" rel=""noreferrer"">https://jestjs.io/docs/en/tutorial-async</a></p>

<p>I dont understand the value of mocking a server response by providing hard coded data, and then testing the value of that hard coded data. It seems like all such a test does is tell you whether or not your tool used a mock instead of an actual api call. That result doesn't tell you anything about the behavior of your application though does it not? Am I missing something?</p>

<p>Additionally, what if I wanted to actually test the result of a real api call? Does that push me over into functional testing territory? Could a real test of an api call be done with a tool like Jest, or is that better suited for something like selenium or testcafe?</p>
",https://stackoverflow.com/questions/54561260/jest-why-mock-api-calls,"['javascript', 'selenium', 'testing', 'jestjs', 'web-api-testing']",1352,True,9,2
Speeding up the Travis build,"<p>I've read <a href=""https://docs.travis-ci.com/user/speeding-up-the-build/"" rel=""nofollow noreferrer"">official doc</a>, and <a href=""https://stackoverflow.com/questions/34117441/travis-ci-run-scripts-in-parallel"">this</a> and <a href=""https://stackoverflow.com/questions/50110360/how-to-make-travisci-run-flow-test-lint-in-parallel/50117342#50117342"">this</a> SO posts. Cited links explains how to run tests in parallel, but not how to build and test only part of them. What I am looking for is: how to set Travis CI for ""partial"" build. If my app has 5 parts, and developer commits code only in part 3, then I need just that part to be built and tested, while later during night there will be full build. </p>

<p>So, to rephrase, my question is how to setup ""partial"" build and ""full"" build as separate and execute them depending on committed code or cron job (for nightly build)? </p>

<p>Also I'd like to run separately front and back-end builds depending on commit. Unit and Integration testing should be also separated on partial and nightly build. App is Ruby on back and Angular on front.</p>
",https://stackoverflow.com/questions/56887602/speeding-up-the-travis-build,"['ruby-on-rails', 'travis-ci']",219,True,0,1
JDK 1.8 java.lang.VerifyError: Expecting a stackmap frame at branch target 47,"<p>I'm working on javafx project and converted it to maven.
I'm implementing progaurd in it and generate encrypted (with Obfuscation) jar. But when i try to run jar using </p>

<blockquote>
  <p>java -jar test.jar</p>
</blockquote>

<p>give me following error-></p>

<pre><code>Exception in thread ""JavaFX Application Thread"" Exception in thread ""main"" java.lang.VerifyError: Expecting a stackmap frame at branch target 47
Exception Details:
  Location:
smartSearch/SmartSearch.setFontStyle(Ljava/lang/String;)V @3: ifnull
  Reason:
Expected stackmap frame at this location.
  Bytecode:
0x0000000: b200 2bc6 002c b200 2b12 03b6 004a 4c2b
0x0000010: c600 1f2b bb00 1259 b700 3912 02b6 003a
0x0000020: 2ab6 003a 1201 b600 3ab6 003b b600 47b1
0x0000030:                                        

at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplicationWithArgs$413(LauncherImpl.java:352)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$399(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$397(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$398(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
</code></pre>

<p>I'm using JDK 1.8 and i have searched lots of solution, some of them are as follows :-</p>

<p><a href=""https://support.cloudbees.com/hc/en-us/articles/225066288-Expecting-a-stackmap-frame-at-branch-target"" rel=""nofollow noreferrer"">https://support.cloudbees.com/hc/en-us/articles/225066288-Expecting-a-stackmap-frame-at-branch-target</a></p>

<p><a href=""https://stackoverflow.com/questions/31567532/getting-expecting-a-stackmap-frame-at-branch-target-when-running-maven-integra"">Getting &quot;Expecting a stackmap frame at branch target&quot; when running Maven integration testing</a></p>

<p>Many more.. </p>

<p>I found that <strong>-XX:-UseSplitVerifier</strong>  not supported by <strong>JDK1.8</strong> and alternative is <strong>-noverify</strong> . But when searched to set <strong>-noverify</strong> i'm confused where to set this and how. </p>

<p>I found on <a href=""https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html#BABDJJFI"" rel=""nofollow noreferrer"">oracle doc</a> that option <strong>-XX:-UseSplitVerifier</strong> was deprecated in JDK 8, and verification is now split by default without a way to disable it.</p>

<p>please help me.</p>
",https://stackoverflow.com/questions/57389277/jdk-1-8-java-lang-verifyerror-expecting-a-stackmap-frame-at-branch-target-47,"['java', 'maven', 'jar', 'jvm', 'proguard']",2005,False,0,0
"In java Spring Boot ,How to pass in-memory LDAPConnection object to ldapService in integration testing?","<p>I am writing integration tests for my API. I have to test flow that's why I implemented in-memory ldap. I have used InMemoryDirectoryServer which return LDAPConnection object for in memory operations. But in my LDAPService I have written function getLdapConnection which returns LDAPConnection, this function is being used for LDAP operations. </p>

<p>so how do I pass in-memory LDAPConnection object to my LDAPServices so each operation will take in-memory LDAPConnection object for integration testing?</p>

<p>I have tried creating setter method for autowired LDAPConnection object.</p>

<pre class=""lang-java prettyprint-override""><code>//Test class
public class LdapInMem
{
    InMemoryDirectoryServer server;
    public LDAPConnection startInMemLdapServer() throws UnknownHostException
    {
           //some in memory listener config
           return ldapConnection;
    }
}
</code></pre>

<pre class=""lang-java prettyprint-override""><code>@Service
@Repository
public class LDAPService
{   
    @Autowired
    private LDAPServerConfig ldapServerConfig;

    private LDAPConnection ldapConnection;
    public LDAPConnection getLDAPConnection()
    {
          //some server config from  ldapServerConfig
          return ldapConnection;
    }
    public function()
    {
       con = getLDAPConnection();
       con.do_ldap_stuff
    }
    public function1()
    {
       con = getLDAPConnection();
       con.do_ldap_stuff1
    }
}
</code></pre>

<pre class=""lang-java prettyprint-override""><code>//LDAP service
    public void setLdapConnection(LDAPConnection ldapConnection)
    {
        this.ldapConnection = ldapConnection;
    }
</code></pre>

<p>how can my testcases set ldapConnection object of LDAPService from in-memory setup while testing and normally from LDAPService while running app?
So I can test my function and function1 in the flow.
I expect my API to use in-memory LDAPConnection object for every LDAP operation to test integration flow.</p>
",https://stackoverflow.com/questions/55591334/in-java-spring-boot-how-to-pass-in-memory-ldapconnection-object-to-ldapservice,"['java', 'spring-boot', 'integration-testing', 'in-memory', 'unboundid-ldap-sdk']",498,True,0,1
E2E rails test through async job and post,"<p>I have a rails route that kicks off an async job thats supposed to post data somewhere when it finishes.</p>

<p>I would love to be able to test this method end to end, ensuring that the job completes and that it sends off a post to the url it's supposed to.</p>

<p>But I'm a little confused on what the best way to do this is. Some posts say that it is a fool's errand to try and test this end to end, and that I should test pieces individually. Others think integration testing is the only way to be sure.</p>

<p>Should I create some kind of listener to catch the post after its been sent out? Should I stub the http get? Or is the whole thing really truly a fools errand?</p>

<p>Thanks for the help</p>
",https://stackoverflow.com/questions/54657303/e2e-rails-test-through-async-job-and-post,"['ruby-on-rails', 'integration-testing']",30,False,0,1
Porting into Laravel: Migration from raw SQL Dumps,"<p>In my project, I am moving from Codeigniter into Laravel, also I am starting to use phpunit tests as well. In this project there are many legacy databases without any sort of migrations. From them I want to autogenerate a test databases for integration testing.</p>

<p>But there's a thorn in my idea: 
How to autogenerate an existing test database and nuke it if requested? There are no database migrations in the existing project so I need to create them in the newly-generated project.</p>

<p>So far I generated a dump of my database using <code>pg-dump</code> (I use a postgresql flavor as my database). The dump is an sql file. I also created an initial migration using the command:</p>

<pre><code>php ./artisan make:migration --path ./database/migrations/myDb InitialDb
</code></pre>

<p>That generated the following code:</p>

<pre><code>use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class InitialDb extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //Read and execute the sql dump.
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //Delete anything except the test data.
    }
}
</code></pre>

<p>So I want to know how I can execute the sql code generated from the in the generated dump? </p>
",https://stackoverflow.com/questions/58429024/porting-into-laravel-migration-from-raw-sql-dumps,"['php', 'laravel', 'postgresql', 'database-migration', 'laravel-5.6']",276,True,0,1
How to set up Mongo DB in Go for a rest service that allows for unit testing?,"<p>I am setting up a rest service in go using MongoDB and mux routers. I am running into issues on how to best set this up to allow for unit/integration testing in a separate database.</p>

<p>I have tried setting up the database in the Init() function but this is giving me issues when trying to set up unit tests using a test DB.</p>

<p>Here are some examples of where I am at right now. I am trying to use a method to connect to the database before posting so in my test I can connect to a different testing database.</p>

<pre class=""lang-golang prettyprint-override""><code>type user struct {
    name string `json:""name""`
    age  int    `json:""age""`
}

type database struct {
    db *mongo.Database
}

func ConnectToDB() (*database, error) {
    client, err := mongo.NewClient(options.Client().ApplyURI(""mongodb://localhost:27017""))
    if err != nil {
        return nil, err
    }

    if err := client.Connect(context.Background()); err != nil {
        return nil, err
    }

    database := &amp;database{
        db: client.Database(""PMBaseGo""),
    }

    return database, nil
}

func PostUser(w http.ResponseWriter, r *http.Request) {
    w.Header().Set(""Content-Type"", ""application/json"")
    //Retrieving request body
    var user user
    _ = json.NewDecoder(r.Body).Decode(&amp;user)
    //Posting Company.
    err := PostUserToDB(user)
    //Error Handling
    if err != nil {
        fmt.Println(err)
        w.WriteHeader(500)
    }
}

func (d *database) connPostUserToDB(user user) error {
    _, err := d.db.Collection(""companies"").InsertOne(context.Background(), user)
    if err != nil {
        return err
    }
    return nil
}

func main() {
    _, _ = ConnectToDB()
    r := mux.NewRouter()

    r.HandleFunc(""/user"", PostUser).Methods(""POST"")

    fmt.Println(""Application Running..."")
    log.Fatal(http.ListenAndServe(""localhost:8081"", r))
}
</code></pre>

<p>The issue I am at right now is trying to call the <code>PostUserToDB</code> method in the <code>PostUser</code> function.</p>

<p>I'm starting to think the issue lies prior to this in how I am going about connecting to the DB.</p>
",https://stackoverflow.com/questions/56189532/how-to-set-up-mongo-db-in-go-for-a-rest-service-that-allows-for-unit-testing,"['rest', 'unit-testing', 'go', 'mux']",237,True,-1,1
Code stuck when querying CosmosDB in java integration test,"<p>I'm writing integration test for an API.
In DAO class, when I try to fetch data from Cosmos DB using AsyncDocumentClient instance queryDocuments method, program has stuck indefinitely.</p>

<p>This is how my function call looks like:</p>

<pre><code>Iterator&lt; FeedResponse&lt;Document&gt;&gt; getDataFromCosmos = asyncDocumentClientInstance.queryDocuments(collectionLink, querySpec, feedOptions).toBlocking().getIterator();
</code></pre>

<p><strong>This is happening only when I run the test cases (in test mode).
But the code and API is working fine when I run in normal mode.</strong></p>

<p>This is how my test class looks like:
(I'm doing integration testing, not unit testing)</p>

<pre><code>import org.junit.runner.RunWith;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)

public class ApiTest extends TestngInitializer

{

@Autowired

ServiceImpl serviceImpl;

    @Test
    public void apiTest()
    {
    RequestClass requestObject = new requestObject();
    // hardcoding requestObject data variables using setters

    ResponseClass response = serviceImpl.apiMethod(requestObject,HttpHeaders);

    //Assertions on response

    }

}
</code></pre>

<p>My TestngInitializer class looks like (Setting path to get all spring beans)</p>

<pre><code>@ContextConfiguration(locations = {""classpath:/META-INF/biz-context.xml"",""classpath:/META-INF/service-context.xml""})

public class TestngInitializer
{

}
</code></pre>

<p>When I try to debug line by line, when control has reached <code>BlockingObservable.java</code>, control is waiting indefinitely for some thread to finish which is not the case when I run the code in normal mode.</p>

<pre><code>BlockingUtils.awaitForComplete(latch, subscription);
</code></pre>

<p>If anyone can help me on this, that would be great.</p>

<p>Here is the small reproducible code I tried as well:</p>

<pre><code>@Test
public void testDBLocally()
{
    AsyncDocumentClient asyncDocumentClient = readDocumentClient(); //calling below function
    FeedOptions feedOptions = new FeedOptions();
    feedOptions.setEnableCrossPartitionQuery(true);
    String collectionLink = ""/dbs/link_to_collection"";
    SqlQuerySpec querySpec = new SqlQuerySpec(""select * from some_document c "");

    //here I tried two approaches
    //first approach using iterator
    Iterator&lt;FeedResponse&lt;Document&gt;&gt; iterator = asyncDocumentClient.queryDocuments(collectionLink,querySpec,feedOptions).toBlocking().getIterator();
    while(iterator.hasNext())
    {
        //control stuck indefinitely at iterator.hasNext()
        //control never reached inside while loop
    }

    //second approach using last()
     FeedResponse&lt;Document&gt; response = capsReadDocumentClient.queryDocuments(collectionLink, querySpec, feedOptions).toBlocking().last(); //control stuck here
     documentList = response.getResults(); //control never reached here

}

public AsyncDocumentClient readDocumentClient() {
    String HOST = ""https://azure-cosmosdb.documents.azure.com:443/"";
    String MASTER_KEY = ""SOME_MASTER_KEY""; 
    return new AsyncDocumentClient.Builder()
            .withServiceEndpoint(HOST)
            .withMasterKeyOrResourceToken(MASTER_KEY)
            .withConnectionPolicy(ConnectionPolicy.GetDefault())
            .withConsistencyLevel(ConsistencyLevel.Session)
            .build();
}
</code></pre>
",https://stackoverflow.com/questions/58959062/code-stuck-when-querying-cosmosdb-in-java-integration-test,"['java', 'spring', 'rx-java', 'integration-testing', 'azure-cosmosdb']",615,False,3,0
Spring-boot test not working with code coverage but works without code coverage,"<p>I have a spring-boot service with spring-security, version -2.1.2.RELEASE. Java-11.0.2
I have test cases written for my API integration testing.
When I run my test cases without code coverage it works, but when I run it with code coverage it fails.
The exception is basically from a configuration file called WebSecurityConfig.java which extends WebSecurityConfigurerAdapter. I have my ldap security check done here and also I am Auto Wiring a settings object called LdapSettings.java which is again a configuration.
Here is a glimpse of the exception which I get when I run with test with code coverage.</p>

<p>java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class
Caused by: java.lang.ClassFormatError: Nest member class_info_index 49 has bad constant type in class file com/acumenllc/notifications/config/security/WebSecurityConfig</p>

<p>Also please suggest me if I am doing anything wrong in the design here.</p>
",https://stackoverflow.com/questions/54475239/spring-boot-test-not-working-with-code-coverage-but-works-without-code-coverage,"['junit4', 'spring-boot-test']",550,False,1,0
Exception in Generating EMF model code in XText Eclipse DSL Tools Version: 2019-03 RC1 (4.11 RC1) - Windows 10,"<p>I consistently get exception while running maven package goal -- I selected the following options in the project wizard </p>

<p>Accepted default project name and language name on first page, 
 - Java Execution environment 1.8 (jdk1.8.0_151),</p>

<p>and on the second page:
 - Eclipse Plugin
 - Web Integration
 - Testing Support JUnit 5
 - Preferred Build System -- Maven
 - Build Language Server -- Fat Jar
 - Source Layout -- Plain</p>

<p>Once the projects are created, from the parent project I select Run As->Maven Build and supply ""clean package"" in goals. ""clean"" succeeds but the build fails with following exception trace.  I did remember to set the active target platform. Something to note, Gradle build works but my use case requires creating language server as well as eclispe plugin. I have tried Gradle with addtinal tycho maven build but without success. It maven build fails the same way.Please let me know if I am doing something incorrectly.</p>

<hr>

<pre><code>2054 [org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher.main()] INFO  text.xtext.generator.XtextGenerator  - Generating org.xtext.example.mydsl1.MyDsl
4186 [org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher.main()] INFO  nerator.ecore.EMFGeneratorFragment2  - Generating EMF model code
Mar 12, 2019 12:50:30 PM org.eclipse.emf.mwe.utils.GenModelHelper registerGenModel
INFO: Registered GenModel 'http://www.xtext.org/example/mydsl1/MyDsl' from 'platform:/resource/org.xtext.example.mydsl1/model/generated/MyDsl.genmodel'
org.eclipse.emf.common.util.WrappedException: org.eclipse.emf.codegen.jet.JETException: InvocationTargetException
    at org.eclipse.emf.codegen.ecore.generator.AbstractGeneratorAdapter.generateJava(AbstractGeneratorAdapter.java:2108)
    at org.eclipse.emf.codegen.ecore.genmodel.generator.GenPackageGeneratorAdapter.generatePackageInterface(GenPackageGeneratorAdapter.java:601)
    at org.eclipse.emf.codegen.ecore.genmodel.generator.GenPackageGeneratorAdapter.generateModel(GenPackageGeneratorAdapter.java:209)
    at org.eclipse.emf.codegen.ecore.genmodel.generator.GenBaseGeneratorAdapter.doGenerate(GenBaseGeneratorAdapter.java:215)
    at org.eclipse.emf.codegen.ecore.generator.AbstractGeneratorAdapter.generate(AbstractGeneratorAdapter.java:319)
    at org.eclipse.emf.codegen.ecore.generator.Generator.generate(Generator.java:728)
    at org.eclipse.emf.codegen.ecore.generator.Generator.generate(Generator.java:639)
    at org.eclipse.xtext.xtext.generator.ecore.EMFGeneratorFragment2.doGenerate(EMFGeneratorFragment2.java:1015)
    at org.eclipse.xtext.xtext.generator.ecore.EMFGeneratorFragment2.generate(EMFGeneratorFragment2.java:469)
    at org.eclipse.xtext.xtext.generator.CompositeGeneratorFragment2.generate(CompositeGeneratorFragment2.java:50)
    at org.eclipse.xtext.xtext.generator.XtextGenerator.invokeInternal(XtextGenerator.java:230)
    at org.eclipse.emf.mwe.core.lib.AbstractWorkflowComponent.invoke(AbstractWorkflowComponent.java:132)
    at org.eclipse.emf.mwe.core.lib.Mwe2Bridge.invoke(Mwe2Bridge.java:34)
    at org.eclipse.emf.mwe.core.lib.AbstractWorkflowComponent.invoke(AbstractWorkflowComponent.java:212)
    at org.eclipse.emf.mwe2.runtime.workflow.AbstractCompositeWorkflowComponent.invoke(AbstractCompositeWorkflowComponent.java:37)
    at org.eclipse.emf.mwe2.runtime.workflow.Workflow.run(Workflow.java:20)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Runner.run(Mwe2Runner.java:102)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Runner.run(Mwe2Runner.java:62)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Runner.run(Mwe2Runner.java:52)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher.run(Mwe2Launcher.java:78)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher.main(Mwe2Launcher.java:36)
    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.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:293)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.eclipse.emf.codegen.jet.JETException: InvocationTargetException
    at org.eclipse.emf.codegen.jet.JETEmitter.generate(JETEmitter.java:467)
    at org.eclipse.emf.codegen.ecore.generator.AbstractGeneratorAdapter.generateJava(AbstractGeneratorAdapter.java:1979)
    ... 26 more
Caused by: java.lang.reflect.InvocationTargetException
    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.eclipse.emf.codegen.jet.JETEmitter.generate(JETEmitter.java:459)
    ... 27 more
Caused by: java.lang.NoSuchMethodError: org.eclipse.emf.codegen.util.CodeGenUtil.xmlEscapeEncode(Ljava/lang/String;)Ljava/lang/String;
    at org.eclipse.emf.codegen.ecore.genmodel.impl.GenBaseImpl.appendModelSetting(GenBaseImpl.java:1925)
    at org.eclipse.emf.codegen.ecore.genmodel.impl.GenPackageImpl.getModelInfo(GenPackageImpl.java:4240)
    at org.eclipse.emf.codegen.ecore.templates.model.PackageClass.generate(PackageClass.java:424)
    ... 32 more
org.eclipse.emf.common.util.WrappedException: org.eclipse.emf.codegen.jet.JETException: InvocationTargetException
    at org.eclipse.emf.codegen.ecore.generator.AbstractGeneratorAdapter.generateJava(AbstractGe4648 [org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher.main()] WARN  nerator.ecore.EMFGeneratorFragment2  - Diagnostic ERROR source=org.eclipse.emf.codegen.ecore code=0 Generating code data=[] [Diagnostic OK source=org.eclipse.emf.common code=0 OK data=[], Diagnostic OK source=org.eclipse.emf.common code=0 OK data=[], Diagnostic OK source=org.eclipse.emf.common code=0 OK data=[], Diagnostic OK source=org.eclipse.emf.common code=0 OK data=[], Diagnostic OK source=org.eclipse.emf.common code=0 OK data=[], Diagnostic ERROR source=org.eclipse.emf.codegen.ecore code=0 Generating Java interface org.xtext.example.mydsl1.myDsl.MyDslPackage failed with an unhandled exception data=[] [Diagnostic ERROR source=org.eclipse.emf.common code=0 InvocationTargetException data=[java.lang.reflect.InvocationTargetException] [Diagnostic ERROR source=org.eclipse.emf.common code=0 NoSuchMethodError: org.eclipse.emf.codegen.util.CodeGenUtil.xmlEscapeEncode(Ljava/lang/String;)Ljava/lang/String; data=[java.lang.NoSuchMethodError: org.eclipse.emf.codegen.util.CodeGenUtil.xmlEscapeEncode(Ljava/lang/String;)Ljava/lang/String;]]], Diagnostic ERROR source=org.eclipse.emf.codegen.ecore code=0 Generating Java interface org.xtext.example.mydsl1.myDsl.Model failed with an unhandled exception data=[] [Diagnostic ERROR source=org.eclipse.emf.common code=0 InvocationTargetException data=[java.lang.reflect.InvocationTargetException] [Diagnostic ERROR source=org.eclipse.emf.common code=0 NoSuchMethodError: org.eclipse.emf.codegen.util.CodeGenUtil.xmlEscapeEncode(Ljava/lang/String;)Ljava/lang/String; data=[java.lang.NoSuchMethodError: org.eclipse.emf.codegen.util.CodeGenUtil.xmlEscapeEncode(Ljava/lang/String;)Ljava/lang/String;]]], Diagnostic ERROR source=org.eclipse.emf.codegen.ecore code=0 Generating Java interface org.xtext.example.mydsl1.myDsl.Greeting failed with an unhandled exception data=[] [Diagnostic ERROR source=org.eclipse.emf.common code=0 InvocationTargetException data=[java.lang.reflect.InvocationTargetException] [Diagnostic ERROR source=org.eclipse.emf.common code=0 NoSuchMethodError: org.eclipse.emf.ecore.util.EcoreValidator$EGenericTypeBuilder.buildEGenericType(Ljava/lang/String;)Lorg/eclipse/emf/ecore/EGenericType; data=[java.lang.NoSuchMethodError: org.eclipse.emf.ecore.util.EcoreValidator$EGenericTypeBuilder.buildEGenericType(Ljava/lang/String;)Lorg/eclipse/emf/ecore/EGenericType;]]], Diagnostic OK source=org.eclipse.emf.common code=0 OK data=[], Diagnostic OK source=org.eclipse.emf.common code=0 OK data=[], Diagnostic OK source=org.eclipse.emf.common code=0 OK data=[], Diagnostic OK source=org.eclipse.emf.common code=0 OK data=[]]
neratorAdapter.java:2108)
    at org.eclipse.emf.codegen.ecore.genmodel.generator.GenClassGeneratorAdapter.generateInterface(GenClassGeneratorAdapter.java:117)
    at org.eclipse.emf.codegen.ecore.genmodel.generator.GenClassGeneratorAdapter.generateModel(GenClassGeneratorAdapter.java:100)
    at org.eclipse.emf.codegen.ecore.genmodel.generator.GenBaseGeneratorAdapter.doGenerate(GenBaseGeneratorAdapter.java:215)
    at org.eclipse.emf.codegen.ecore.generator.AbstractGeneratorAdapter.generate(AbstractGeneratorAdapter.java:319)
    at org.eclipse.emf.codegen.ecore.generator.Generator.generate(Generator.java:728)
    at org.eclipse.emf.codegen.ecore.generator.Generator.generate(Generator.java:639)
    at org.eclipse.xtext.xtext.generator.ecore.EMFGeneratorFragment2.doGenerate(EMFGeneratorFragment2.java:1015)
    at org.eclipse.xtext.xtext.generator.ecore.EMFGeneratorFragment2.generate(EMFGeneratorFragment2.java:469)
    at org.eclipse.xtext.xtext.generator.CompositeGeneratorFragment2.generate(CompositeGeneratorFragment2.java:50)
    at org.eclipse.xtext.xtext.generator.XtextGenerator.invokeInternal(XtextGenerator.java:230)
    at org.eclipse.emf.mwe.core.lib.AbstractWorkflowComponent.invoke(AbstractWorkflowComponent.java:132)
    at org.eclipse.emf.mwe.core.lib.Mwe2Bridge.invoke(Mwe2Bridge.java:34)
    at org.eclipse.emf.mwe.core.lib.AbstractWorkflowComponent.invoke(AbstractWorkflowComponent.java:212)
    at org.eclipse.emf.mwe2.runtime.workflow.AbstractCompositeWorkflowComponent.invoke(AbstractCompositeWorkflowComponent.java:37)
    at org.eclipse.emf.mwe2.runtime.workflow.Workflow.run(Workflow.java:20)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Runner.run(Mwe2Runner.java:102)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Runner.run(Mwe2Runner.java:62)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Runner.run(Mwe2Runner.java:52)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher.run(Mwe2Launcher.java:78)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher.main(Mwe2Launcher.java:36)
    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.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:293)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.eclipse.emf.codegen.jet.JETException: InvocationTargetException
    at org.eclipse.emf.codegen.jet.JETEmitter.generate(JETEmitter.java:467)
    at org.eclipse.emf.codegen.ecore.generator.AbstractGeneratorAdapter.generateJava(AbstractGeneratorAdapter.java:1979)
    ... 26 more
Caused by: java.lang.reflect.InvocationTargetException
    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.eclipse.emf.codegen.jet.JETEmitter.generate(JETEmitter.java:459)
    ... 27 more
Caused by: java.lang.NoSuchMethodError: org.eclipse.emf.codegen.util.CodeGenUtil.xmlEscapeEncode(Ljava/lang/String;)Ljava/lang/String;
    at org.eclipse.emf.codegen.ecore.genmodel.impl.GenBaseImpl.appendModelSetting(GenBaseImpl.java:1917)
    at org.eclipse.emf.codegen.ecore.genmodel.impl.GenTypedElementImpl.appendModelSetting(GenTypedElementImpl.java:971)
    at org.eclipse.emf.codegen.ecore.genmodel.impl.GenFeatureImpl.getModelInfo(GenFeatureImpl.java:2315)
    at org.eclipse.emf.codegen.ecore.genmodel.impl.GenFeatureImpl.getModelInfo(GenFeatureImpl.java:2230)
    at org.eclipse.emf.codegen.ecore.templates.model.Class$2.run(Class.java:1877)
    at org.eclipse.emf.codegen.ecore.templates.model.Class.generate(Class.java:3908)
    ... 32 more
org.eclipse.emf.common.util.WrappedException: org.eclipse.emf.codegen.jet.JETException: InvocationTargetException
    at org.eclipse.emf.codegen.ecore.generator.AbstractGeneratorAdapter.generateJava(AbstractGeneratorAdapter.java:2108)
    at org.eclipse.emf.codegen.ecore.genmodel.generator.GenClassGeneratorAdapter.generateInterface(GenClassGeneratorAdapter.java:117)
    at org.eclipse.emf.codegen.ecore.genmodel.generator.GenClassGeneratorAdapter.generateModel(GenClassGeneratorAdapter.java:100)
    at org.eclipse.emf.codegen.ecore.genmodel.generator.GenBaseGeneratorAdapter.doGenerate(GenBaseGeneratorAdapter.java:215)
    at org.eclipse.emf.codegen.ecore.generator.AbstractGeneratorAdapter.generate(AbstractGeneratorAdapter.java:319)
    at org.eclipse.emf.codegen.ecore.generator.Generator.generate(Generator.java:728)
    at org.eclipse.emf.codegen.ecore.generator.Generator.generate(Generator.java:639)
    at org.eclipse.xtext.xtext.generator.ecore.EMFGeneratorFragment2.doGenerate(EMFGeneratorFragment2.java:1015)
    at org.eclipse.xtext.xtext.generator.ecore.EMFGeneratorFragment2.generate(EMFGeneratorFragment2.java:469)
    at org.eclipse.xtext.xtext.generator.CompositeGeneratorFragment2.generate(CompositeGeneratorFragment2.java:50)
    at org.eclipse.xtext.xtext.generator.XtextGenerator.invokeInternal(XtextGenerator.java:230)
    at org.eclipse.emf.mwe.core.lib.AbstractWorkflowComponent.invoke(AbstractWorkflowComponent.java:132)
    at org.eclipse.emf.mwe.core.lib.Mwe2Bridge.invoke(Mwe2Bridge.java:34)
    at org.eclipse.emf.mwe.core.lib.AbstractWorkflowComponent.invoke(AbstractWorkflowComponent.java:212)
    at org.eclipse.emf.mwe2.runtime.workflow.AbstractCompositeWorkflowComponent.invoke(AbstractCompositeWorkflowComponent.java:37)
    at org.eclipse.emf.mwe2.runtime.workflow.Workflow.run(Workflow.java:20)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Runner.run(Mwe2Runner.java:102)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Runner.run(Mwe2Runner.java:62)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Runner.run(Mwe2Runner.java:52)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher.run(Mwe2Launcher.java:78)
    at org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher.main(Mwe2Launcher.java:36)
    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.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:293)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.eclipse.emf.codegen.jet.JETException: InvocationTargetException
    at org.eclipse.emf.codegen.jet.JETEmitter.generate(JETEmitter.java:467)
    at org.eclipse.emf.codegen.ecore.generator.AbstractGeneratorAdapter.generateJava(AbstractGeneratorAdapter.java:1979)
    ... 26 more
Caused by: java.lang.reflect.InvocationTargetException
    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.eclipse.emf.codegen.jet.JETEmitter.generate(JETEmitter.java:459)
    ... 27 more
Caused by: java.lang.NoSuchMethodError: org.eclipse.emf.ecore.util.EcoreValidator$EGenericTypeBuilder.buildEGenericType(Ljava/lang/String;)Lorg/eclipse/emf/ecore/EGenericType;
    at org.eclipse.emf.codegen.ecore.genmodel.impl.GenBaseImpl.getType(GenBaseImpl.java:1344)
    at org.eclipse.emf.codegen.ecore.genmodel.impl.GenBaseImpl.getImportedType(GenBaseImpl.java:1397)
    at org.eclipse.emf.codegen.ecore.genmodel.impl.GenTypedElementImpl.getRawImportedBoundType(GenTypedElementImpl.java:361)
    at org.eclipse.emf.codegen.ecore.templates.model.Class$2.run(Class.java:1859)
    at org.eclipse.emf.codegen.ecore.templates.model.Class.generate(Class.java:3908)
    ... 32 more
6596 [org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher.main()] INFO  text.xtext.generator.XtextGenerator  - Generating common infrastructure
6637 [org.eclipse.emf.mwe2.launch.runtime.Mwe2Launcher.main()] INFO  .emf.mwe2.runtime.workflow.Workflow  - Done.
[INFO] 
[INFO] --- xtend-maven-plugin:2.17.0:compile (default) @ org.xtext.example.mydsl1 ---
[WARNING] Error injecting: org.eclipse.xtend.maven.XtendCompile
java.lang.NoClassDefFoundError: org/eclipse/emf/common/util/WrappedException
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
    at java.lang.Class.getDeclaredConstructors(Class.java:2020)
    at com.google.inject.spi.InjectionPoint.forConstructorOf(InjectionPoint.java:245)
    at com.google.inject.internal.ConstructorBindingImpl.create(ConstructorBindingImpl.java:99)
    at com.google.inject.internal.InjectorImpl.createUninitializedBinding(InjectorImpl.java:658)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBinding(InjectorImpl.java:882)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBindingRecursive(InjectorImpl.java:805)
    at com.google.inject.internal.InjectorImpl.getJustInTimeBinding(InjectorImpl.java:282)
    at com.google.inject.internal.InjectorImpl.getBindingOrThrow(InjectorImpl.java:214)
    at com.google.inject.internal.InjectorImpl.getProviderOrThrow(InjectorImpl.java:1006)
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1038)
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1001)
    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051)
    at org.eclipse.sisu.space.AbstractDeferredClass.get(AbstractDeferredClass.java:48)
    at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:81)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:53)
    at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:65)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
    at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
    at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:63)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:45)
    at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1016)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
    at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1012)
    at org.eclipse.sisu.inject.Guice4$1.get(Guice4.java:162)
    at org.eclipse.sisu.inject.LazyBeanEntry.getValue(LazyBeanEntry.java:81)
    at org.eclipse.sisu.plexus.LazyPlexusBean.getValue(LazyPlexusBean.java:51)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:263)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:255)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getConfiguredMojo(DefaultMavenPluginManager.java:519)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:124)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:290)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:194)
    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.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: java.lang.ClassNotFoundException: org.eclipse.emf.common.util.WrappedException
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
        ... 54 more
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO] 
[INFO] org.xtext.example.mydsl1.parent 1.0.0-SNAPSHOT ..... SUCCESS [  0.113 s]
[INFO] org.xtext.example.mydsl1 ........................... FAILURE [  8.014 s]
[INFO] org.xtext.example.mydsl1.ide ....................... SKIPPED
[INFO] org.xtext.example.mydsl1.ui ........................ SKIPPED
[INFO] org.xtext.example.mydsl1.target .................... SKIPPED
[INFO] org.xtext.example.mydsl1.tests ..................... SKIPPED
[INFO] org.xtext.example.mydsl1.ui.tests 1.0.0-SNAPSHOT ... SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 59.088 s
[INFO] Finished at: 2019-03-12T13:04:14-07:00
</code></pre>
",https://stackoverflow.com/questions/55130001/exception-in-generating-emf-model-code-in-xtext-eclipse-dsl-tools-version-2019,['xtext'],356,False,0,0
Using Docker and Testcontainers for database integration testing,"<p>After a bit of research I was led to think that Docker containers could be a good fit for database integration testing using <a href=""https://www.testcontainers.org/modules/databases"" rel=""nofollow noreferrer"">test containers</a>, as this would only require a Docker container running a database image reproducing the database schema against which the tests would be executed. This instance can either be run locally on each developer’s machine or, even better, one single instance can be shared by multiple developers: an automated test can be configured to start a database instance from the same image in Docker for every test method if needed using the @Rule annotation.</p>

<p>While trying to install Docker for Windows 7 to play with it, I kept getting the following error which seems to be related to VirtualBox:</p>

<pre><code>docker Error creating machine: Error in driver during machine creation: Unable to start the VM: VBoxManage.exe startvm default --type headless failed:

Result code: E_FAIL (0x80004005)
Component: MachineWrap
Interface: IMachine
</code></pre>

<p>I will share how I worked around this problem to help other people who may have run into the same problem.</p>
",https://stackoverflow.com/questions/55705417/using-docker-and-testcontainers-for-database-integration-testing,"['java', 'oracle', 'docker', 'windows-7', 'testcontainers']",4297,True,0,1
Deserialize Soap in File to DTO,"<p>I contact a web service that returns something like 2600 records in SOAP format. To do some integration testing, I saved the soap message by copying the result from SoapUi to a file. I then removed most of the records (identified as Report_Entry) to give myself a much smaller test. </p>

<p>So, I'm writing a unit test that loads the file as XML:</p>

<pre><code>XmlSerializer deSerialize = new XmlSerializer(typeof(List&lt;Report_EntryType&gt;));
</code></pre>

<p>(The WSDL defines the entries as Report_EntryType.)</p>

<p>Then:</p>

<pre><code>{
    workdayList = deSerialize.Deserialize(reader) as List&lt;Report_EntryType&gt;;
}
</code></pre>

<p>But, my test fails on a</p>

<pre><code>System.InvalidOperationException : &lt;Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'&gt; 
</code></pre>

<p>To summarize:</p>

<blockquote>
  <ol>
  <li>Retrieve a SOAP message from a webservice.</li>
  <li>Save the message to a file.</li>
  <li>Remove most of the records from the test file so I only have one or two.</li>
  <li>Feed that file to a test case that uses XmlSerializer to give me input data.</li>
  <li>Use a string reader to read the input data.</li>
  <li>Blow up when trying to deserialize.</li>
  </ol>
</blockquote>

<p>How do I solve the problem?</p>

<p>Sample file:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;env:Envelope xmlns:env=""http://schemas.xmlsoap.org/soap/envelope/""&gt;
   &lt;env:Body&gt;
      &lt;wd:report_data xmlns:wd=""urn:com.workday.report/wog_workday_to_ad_integration_report:2""&gt;
         &lt;wd:Report_Entry&gt;
            &lt;wd:Employee_ID&gt;99995&lt;/wd:Employee_ID&gt;
            &lt;wd:Manager_ID&gt;001961&lt;/wd:Manager_ID&gt;
            &lt;wd:Full_Legal_Name&gt;Luke Skywalker&lt;/wd:Full_Legal_Name&gt;
            &lt;wd:Legal_Name_-_First_Name&gt;Luke&lt;/wd:Legal_Name_-_First_Name&gt;
            &lt;wd:Legal_Name_-_Last_Name&gt;Skywalker&lt;/wd:Legal_Name_-_Last_Name&gt;
            &lt;wd:Legal_Name_is_Preferred_Name&gt;1&lt;/wd:Legal_Name_is_Preferred_Name&gt;
            &lt;wd:Preferred_Name_in_General_Display_Format&gt;Luke Skywalker&lt;/wd:Preferred_Name_in_General_Display_Format&gt;
            &lt;wd:Preferred_Name_-_First_Name&gt;Luke&lt;/wd:Preferred_Name_-_First_Name&gt;
            &lt;wd:Preferred_Name_-_Last_Name&gt;Skywalker&lt;/wd:Preferred_Name_-_Last_Name&gt;
            &lt;wd:Hire_Date&gt;2019-07-01-07:00&lt;/wd:Hire_Date&gt;
            &lt;wd:Original_Hire_Date&gt;2019-07-01-07:00&lt;/wd:Original_Hire_Date&gt;
            &lt;wd:Job_Title_-_Current&gt;Contractor&lt;/wd:Job_Title_-_Current&gt;
            &lt;wd:Position_Object&gt;
               &lt;wd:Current_Position_Filled_-_Effective_Date&gt;2019-07-01-07:00&lt;/wd:Current_Position_Filled_-_Effective_Date&gt;
            &lt;/wd:Position_Object&gt;
            &lt;wd:Email_-_Work wd:Descriptor=""luke@whiting.com""&gt;
               &lt;wd:ID wd:type=""WID""&gt;106d0dc1e3f2017c123580628801d001&lt;/wd:ID&gt;
            &lt;/wd:Email_-_Work&gt;
            &lt;wd:location wd:Descriptor=""Mytown""&gt;
               &lt;wd:ID wd:type=""WID""&gt;d34191b0c905106f759d0975538e88c8&lt;/wd:ID&gt;
               &lt;wd:ID wd:type=""Location_ID""&gt;LOC008-Myto&lt;/wd:ID&gt;
            &lt;/wd:location&gt;
            &lt;wd:location_Object&gt;
               &lt;wd:Primary_Address_-_Line_1&gt;701 4th Avenue NW&lt;/wd:Primary_Address_-_Line_1&gt;
               &lt;wd:Primary_Address_-_Line_2&gt;PO Box 123&lt;/wd:Primary_Address_-_Line_2&gt;
               &lt;wd:Primary_Address_-_Line_3&gt;Mytown, ND 12345&lt;/wd:Primary_Address_-_Line_3&gt;
               &lt;wd:city&gt;Mytown&lt;/wd:city&gt;
               &lt;wd:state&gt;North Dakota&lt;/wd:state&gt;
               &lt;wd:Primary_Address_-_Postal_Code&gt;12345&lt;/wd:Primary_Address_-_Postal_Code&gt;
            &lt;/wd:location_Object&gt;
            &lt;wd:Cost_Center_-_Name&gt;Field Operations&lt;/wd:Cost_Center_-_Name&gt;
            &lt;wd:WOG_EE_Driver_Eligibility&gt;0&lt;/wd:WOG_EE_Driver_Eligibility&gt;
            &lt;wd:Legal_Name_in_General_Display_Format&gt;Luke Skywater&lt;/wd:Legal_Name_in_General_Display_Format&gt;
            &lt;wd:Cost_Center_-_ID&gt;1010&lt;/wd:Cost_Center_-_ID&gt;
            &lt;wd:Worker_Status&gt;Active&lt;/wd:Worker_Status&gt;
            &lt;wd:Location_Address_-_Region__Any_Country_ wd:Descriptor=""North Dakota""&gt;
               &lt;wd:ID wd:type=""WID""&gt;0567a9c4e90340e192aa655d387323c6&lt;/wd:ID&gt;
               &lt;wd:ID wd:type=""Country_Region_ID""&gt;USA-ND&lt;/wd:ID&gt;
               &lt;wd:ID wd:type=""ISO_3166-2_Code""&gt;ND&lt;/wd:ID&gt;
            &lt;/wd:Location_Address_-_Region__Any_Country_&gt;
            &lt;wd:Job_Code&gt;CONTRACT&lt;/wd:Job_Code&gt;
            &lt;wd:Exempt&gt;0&lt;/wd:Exempt&gt;
            &lt;wd:User_Name&gt;lskywalker&lt;/wd:User_Name&gt;
            &lt;wd:Worker_is_Contingent_Worker&gt;1&lt;/wd:Worker_is_Contingent_Worker&gt;
            &lt;wd:Contract_End_Date&gt;2019-08-07-07:00&lt;/wd:Contract_End_Date&gt;
            &lt;wd:Cost_Center_Hierarchy wd:Descriptor=""Operations""&gt;
               &lt;wd:ID wd:type=""WID""&gt;d9a3758225e01071585ef203864f2bfa&lt;/wd:ID&gt;
               &lt;wd:ID wd:type=""Organization_Reference_ID""&gt;Operations&lt;/wd:ID&gt;
               &lt;wd:ID wd:type=""Custom_Organization_Reference_ID""&gt;Operations&lt;/wd:ID&gt;
            &lt;/wd:Cost_Center_Hierarchy&gt;
            &lt;wd:Region wd:Descriptor=""Northern Rockies""&gt;
               &lt;wd:ID wd:type=""WID""&gt;d9a3758225e010715924f5d0bd472cde&lt;/wd:ID&gt;
               &lt;wd:ID wd:type=""Organization_Reference_ID""&gt;Northern Rockies&lt;/wd:ID&gt;
               &lt;wd:ID wd:type=""Region_Reference_ID""&gt;Northern Rockies&lt;/wd:ID&gt;
            &lt;/wd:Region&gt;
         &lt;/wd:Report_Entry&gt;
      &lt;/wd:report_data&gt;
   &lt;/env:Body&gt;
&lt;/env:Envelope&gt;
</code></pre>
",https://stackoverflow.com/questions/57066725/deserialize-soap-in-file-to-dto,"['c#', 'xml', 'soap']",297,False,0,0
How to Integrate Test @RestControllerAdvice which Has Dependencies?,"<p>I have a simple <code>@RestController</code> in Spring Boot 2.1 which has a <code>@RestControllerAdvice</code> assigned to it to handle exceptions, e.g.</p>

<pre><code>@RestController
@RequestMapping(""/path"")
public class MyController {

  @Value(""${some.property}"")
  private boolean flag;

  // Bunch of @Autowired dependencies

  @GetMapping(value=""/to/load/{id}"", ...)
  public MyObj getSomething(@PathVariable String id) throws MyException {
    if (flag) {
       // a dependency that throws MyException
    }
  }
}

@RestControllerAdvice(assignableTypes = MyController.class)
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
  @Autowired
  private SomeComponent someComponent;

  @ExceptionHandler(value = { MyException.class })
  public ResponseEntity&lt;Object&gt; dealWithMyException(MyException exception) {
    SomeResponseObj obj = someComponent.createSomeResponseObj(exception);
    return new ResponseEntity&lt;&gt;(obj, HttpStatus./*some status*/);
  }
}

public class SomeComponent {
  @Autowired
  private InnerDependency dep;
  /* other codes */
}
</code></pre>

<p>I have set my integration testing as following:</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(controllers = MyController.class)
@ContextConfiguration(classes = {MyController.class, MyExceptionHandler.class, SomeComponent.class, SomeComponentDependency.class})
public class MyControllerTest {

  @Autowired 
  private MyController mycontroller;

  @Autowired
  private MockMvc mockMvc;

  @MockBean
  /* MyController dependencies I need to invoke */

  public void happyPathTest() throws Exception {
    when(myControllerService.someMethod()).thenReturn(""Something"");

    mockMvc.perform(get(/* endpoint path */, ""id1"")
        .contentType(MediaType.APPLICATION_JSON_VALUE))
        .andExpect(status().isOk());

  }

  @Test(expected = MyException.class)
  public void negativeTest() throws Exception {
    when(myControllerService.someMethod()).thenThrow(new MyException());

    mockMvc.perform(get(/* endpoint path */, ""id1"")
        .contentType(MediaType.APPLICATION_JSON_VALUE))
        .andExpect(status().isNotFound());

  }
}
</code></pre>

<p>When I run a happy path test(s), everything works, but when I run the <code>negativeTest</code>, I get dependency error on <code>MyExceptionHandler.SomeComponent.dep</code> not being injected. As you can see, my integration test is employing <code>WebMvcTest</code> to tell the Spring about the context.</p>

<p>Also note that I am autowiring <code>MyController</code> since I need to use <code>ReflectionTestUtils</code> to set <code>flag</code> value for certain test scenarios.</p>

<p>I even added all the needed dependency classes to <code>@ContextConfiguration</code> at no avail.</p>

<p>How can I get around this dependency issue to get the controller advice to be called in such setup?</p>

<p>Also, how can I get the response body that the controller advice sends out to examine it's content?</p>

<p>UPDATE:</p>

<p>Using <code>@SpringBootTest</code> and <code>@AutoConfigureMockMvc</code>, I get the following stacktrace:</p>

<pre><code>java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
    at org.springframework.util.Assert.state(Assert.java:73)
    at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:233)
    at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:149)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:395)
    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.boot.test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:98)
    at org.springframework.test.context.TestContextManager.&lt;init&gt;(TestContextManager.java:139)
    at org.springframework.test.context.TestContextManager.&lt;init&gt;(TestContextManager.java:124)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:151)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.&lt;init&gt;(SpringJUnit4ClassRunner.java:142)
    at org.springframework.test.context.junit4.SpringRunner.&lt;init&gt;(SpringRunner.java:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code></pre>

<p>If I add <code>MyController.class</code> to <code>@SpringBootTest</code>, I get the following (where is 406 status is coming from, and is Eclipse misbehaving here):</p>

<pre><code>java.lang.AssertionError: Status expected:&lt;200&gt; but was:&lt;406&gt;
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:98)
    at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
    at org.springframework.test.web.servlet.result.StatusResultMatchers$$Lambda$268/2082545616.match(Unknown Source)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
    at pkg.to.the.controller.MyControllerTest.happyPathTest(MyControllerTest.java:209)
    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:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code></pre>
",https://stackoverflow.com/questions/59023836/how-to-integrate-test-restcontrolleradvice-which-has-dependencies,"['java', 'spring-boot', 'spring-mvc', 'integration-testing', 'controller-advice']",1425,False,3,0
What are integration tests containing and how to set them up,"<p>I’m currently learning about unit tests and integration testing and as I understood it, unit tests are used to test the logic of a specific class and integration tests are used to check the cooperation of multiple classes and libraries.</p>

<p>But is it only used to test multiple classes and if they work together as expected, or is it also valid to access databases in an integration test? If so, what if the connection can‘t be established because of a server sided error, wouldn’t the tests fail, although the code itself would work as expected? How do I know what‘s valid to use in this kind of tests?</p>

<p>Second thing I don‘t understand is how they are set up. Unit tests seem to me have a quite common form, like:</p>

<pre><code>public class  classTest {

    @BeforeEach
    public void setUp(){
    }

    @Test
    public void testCase(){
    }
}
</code></pre>

<p>But how are integration tests written? Is it commonly done the same way, just including more classes and external factors or is there another way that is used for that?</p>
",https://stackoverflow.com/questions/56115219/what-are-integration-tests-containing-and-how-to-set-them-up,"['java', 'unit-testing', 'testing', 'integration-testing']",1062,True,2,3
How to attach a PostgreSQL volume to a Docker image generated with SBT native packager?,"<p>I would like to be able to deploy my app in a <code>pre-prod</code> environment for integration testing using a Docker volume that will expose an instance of PostgreSQL. I'm using Scala v2.12.8 and Play v2.7. </p>

<p>Looking at the <a href=""https://www.scala-sbt.org/sbt-native-packager/formats/docker.html#environment-settings"" rel=""nofollow noreferrer"">environment settings</a> of the SBT native packager it seems possible to define <code>dockerExposedVolumes</code> in order to attach a DB.</p>

<p>Using a normal Docker compose file I would do something like that:</p>

<pre><code>   version: ""3""
   services:
     db:
       image: postgres
       environment:
         - POSTGRES_USER=postgres
         - POSTGRES_PASSWORD=postgress
         - POSTGRES_DB=postgres
       ports:
         - ""5433:5432""
       volumes:
         - pgdata:/var/lib/postgresql/data
       networks:
         - suruse
   volumes: 
     pgdata:
</code></pre>

<p>This configuration has been taken from this <a href=""https://stackoverflow.com/a/45606440/1977778"">SO answer</a>. </p>

<p>I tried searching for config examples but I didn't find anything useful so far. Now I'm wondering <strong>how I should define a new docker volume and then expose it to the Docker image created by SBT exactly?</strong> </p>

<hr>

<h2>THE WORKING SOLUTION</h2>

<p>The final version. I've fully tested it and it works exposing the DB on the TCP port 5433.</p>

<pre><code># https://docs.docker.com/samples/library/postgres/
version: ""3""
services:
  app-pgsql:
    image: postgres:9.6
    restart: always
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=yourPasswordHere
      - POSTGRES_DB=yourDatabaseNameHere
      - POSTGRES_INITDB_ARGS=""--encoding=UTF8""
    ports:
      - ""5433:5432""
    volumes:
      - pgdata:/var/lib/postgresql/data
volumes: 
  pgdata:
    driver: local
</code></pre>

<p>Launch the docker compose using <code>sbt dockerComposeUp -useStaticPorts</code> and then check if the containers have been actually exposed using <code>docker ps -a</code>. Also, check the log files using the command provided by <code>dockerComposeUp</code> or <code>dockerComposeInstances</code>. </p>
",https://stackoverflow.com/questions/56848544/how-to-attach-a-postgresql-volume-to-a-docker-image-generated-with-sbt-native-pa,"['scala', 'docker', 'playframework', 'sbt', 'sbt-native-packager']",1682,True,2,1
ASP.net core integration testing with inherited Startup class. Unable to locate View,"<p>I am attempting to write some integration tests against aspnet core 2.2.  I want to use a TestStartup class that inherits from the normal Startup class to configure resources and services for testing purposes.</p>

<p>A simple example (can be found here: <a href=""https://github.com/davidgouge/aspnet-integration-testing"" rel=""nofollow noreferrer"">https://github.com/davidgouge/aspnet-integration-testing</a>):</p>

<p>I have a solution that contains two projects:</p>

<p>IntegrationTestingWeb (a barebones aspnet mvc app)
IntegrationTestingTests (a testing project)</p>

<p>I have a test that uses the Web Startup class and asserts that OK is returned from <code>/Home/Privacy</code></p>

<pre><code>[Test]
public async Task GetPrivacy_Through_Normal_Startup()
{
    var builder = new WebHostBuilder().UseStartup&lt;Startup&gt;();
    var client = new TestServer(builder).CreateClient();
    var result = await client.GetAsync(""/Home/Privacy"");
    result.StatusCode.Should().Be(HttpStatusCode.OK);
}
</code></pre>

<p>This test passes.</p>

<p>If I create a TestStartupInTestProject class that inherites from Startup but place it in the Tests project, then I have to do some extra work when creating the WebHostBuilder but then the test fails.</p>

<pre><code>[Test]
    public async Task GetPrivacy_Through_Test_Startup_In_Test_Project()
    {
        var builder = new WebHostBuilder().ConfigureServices(services =&gt;
        {
            var startupAssembly = typeof(TestStartupInTestProject).GetTypeInfo().Assembly;

            var manager = new ApplicationPartManager();
            manager.ApplicationParts.Add(new AssemblyPart(startupAssembly));
            manager.ApplicationParts.Add(new AssemblyPart(typeof(HomeController).Assembly));
            manager.FeatureProviders.Add(new ControllerFeatureProvider());
            manager.FeatureProviders.Add(new ViewComponentFeatureProvider());
            services.AddSingleton(manager);
        }).UseStartup&lt;TestStartupInTestProject&gt;();
        var client = new TestServer(builder).CreateClient();

        var result = await client.GetAsync(""/Home/Privacy"");

        result.StatusCode.Should().Be(HttpStatusCode.OK);
    }
</code></pre>

<p>The error in the failure is:</p>

<pre><code>Tests.Tests.GetPrivacy_Through_Test_Startup_In_Test_Project

System.InvalidOperationException : The view 'Privacy' was not found. The 
following locations were searched:
/Views/Home/Privacy.cshtml
/Views/Shared/Privacy.cshtml
/Pages/Shared/Privacy.cshtml
</code></pre>

<p>So it looks like because my Startup class is located in the Test project, the views cannot be located.  What setting am I missing to be able to find the Views?</p>
",https://stackoverflow.com/questions/55021393/asp-net-core-integration-testing-with-inherited-startup-class-unable-to-locate,"['unit-testing', 'asp.net-core', 'integration-testing']",414,True,1,1
Maven failsafe recognizes integration test class but not tests in class,"<p>I have a multi-module Maven project and I'm trying to setup integration testing tooling with the failsafe plugin.</p>

<p>I added the following to the project's parent pom.xml:</p>

<pre><code>&lt;profiles&gt;
    &lt;profile&gt;
        &lt;id&gt;failsafe&lt;/id&gt;
        &lt;build&gt;
            &lt;plugins&gt;
                &lt;plugin&gt;
                    &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt;
                    &lt;version&gt;2.22.0&lt;/version&gt;
                    &lt;executions&gt;
                        &lt;execution&gt;
                            &lt;goals&gt;
                                &lt;goal&gt;integration-test&lt;/goal&gt;
                                &lt;goal&gt;verify&lt;/goal&gt;
                            &lt;/goals&gt;
                        &lt;/execution&gt;
                    &lt;/executions&gt;
                &lt;/plugin&gt;
            &lt;/plugins&gt;
        &lt;/build&gt;
    &lt;/profile&gt;
&lt;/profiles&gt;
</code></pre>

<p>I also added that exact same snippet to the child module's pom.xml where the initial tests were added along with this snippet:</p>

<pre><code>&lt;build&gt;
    &lt;plugins&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
            &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt;
        &lt;/plugin&gt;
    &lt;/plugins&gt;
&lt;/build&gt;
</code></pre>

<p>Here is the directory structure of the module where the initial integration test has been added:</p>

<pre><code>parent
-aws-service-utils
--src
---main
----java
-----com
------lorem
-------ipsum
--------S3
---------S3.java (dummy class)
---test (in same directory as main)
----java
-----com
------lorem
-------ipsum
--------dolor
---------tests
----------S3IT.java (test class for dummy class)
</code></pre>

<p>Here's what <code>S3.java</code> looks like, excluding the imported packages:</p>

<pre><code>public class S3 {
   public int confirmAdd() {
      int sum = 2 + 2;
      return sum;
   }
}
</code></pre>

<p>Here's what <code>S3IT.java</code> looks like, again excluding imported packages:</p>

<pre><code>public class S3IT {
  @Test
  public void confirmAdd() {
     int sum = 2+2;
     assertTrue(sum == 4);
  }
}
</code></pre>

<p>I run <code>mvn verify -Pfailsafe</code> followed by <code>mvn failsafe:integration-test</code> and get no test output for all of the other classes, as expected. Then the following comes up for the <code>aws-service-utils</code> module:</p>

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

<p>So it appears to be recognizing the integration test class S3IT.java but not the test inside. I went through the proposed solutions in a <a href=""https://stackoverflow.com/questions/16387679/maven-fail-safe-not-executing-tests"">similar Stack Overflow post</a> and none of them worked. My primary resource for setting up integration tests with Maven can be found <a href=""https://www.baeldung.com/maven-integration-test"" rel=""nofollow noreferrer"">here</a>.</p>
",https://stackoverflow.com/questions/54206777/maven-failsafe-recognizes-integration-test-class-but-not-tests-in-class,"['java', 'maven', 'integration-testing', 'maven-failsafe-plugin']",481,False,0,0
Use HttpTest inside asp.net core/grpc integration test,"<p>I have a ASP.NET core/gRPC service that I want to integration test.
Inside the grpc services I make Flurl calls to 3rd party web apis.
I want to mock those calls out using Flurl's HttpTest class.
I can get it to work in a really convoluted way but it must be easier.</p>

<p>Currently:</p>

<pre class=""lang-cs prettyprint-override""><code>            var client = _factory
                    .WithWebHostBuilder(builder =&gt;
                    {
                        builder.ConfigureTestServices(services =&gt;
                        {
                        });
                    })
                .CreateClient(new WebApplicationFactoryClientOptions 
                {BaseAddress = new Uri(""http://localhost:5555"")});

            using var channel = GrpcChannel.ForAddress(""http://localhost:5555"",
                new GrpcChannelOptions { HttpClient = client });

            var grpcClient = new MyGrpcService.MyClient(channel);

            var httpTest = new HttpTest();
            var content = new StringContent(""some removed json"", Encoding.UTF8, ""application/json"");
            httpTest.RespondWith(content, 200);

...
            var resp = await grpcClient.GetSomeDataAsync(someRequest);
</code></pre>

<p>n.b. I'm creating my IFlurlClient manually inside the service as we need to provide add dynamic certificate dependent on the host.</p>

<p>My main problem is that Flurl is making real HTTP calls rather than using the HttpTest. </p>

<p>After some digging, this is due to the static nature of <code>HttpTest.Current</code>. The static <code>HttpTest.Current</code> that Flurl uses is set up in the test but does not exist inside the server. I've managed to hack it working by relaying the outer HttpTest.ResponseQueue to one inside the service via a DI override of <code>FlurlClientFactoryBase</code> but this seems far from ideal.</p>

<p>Is there a canonical way of integration testing a service and having Flurl's HttpTest mock any outgoing HTTP calls?</p>
",https://stackoverflow.com/questions/58398235/use-httptest-inside-asp-net-core-grpc-integration-test,"['.net-core', 'grpc', 'flurl']",1444,True,0,1
gcc instrumentation - is it possible to automatically output the arguments of a function?,"<p>I know about <a href=""https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html"" rel=""nofollow noreferrer""><code>-finstrument-functions</code></a>:</p>

<p><em>Generate instrumentation calls for entry and exit to functions. Just after function entry and just before function exit, the following profiling functions are called with the address of the current function and its call site. (On some platforms, __builtin_return_address does not work beyond the current function, so the call site information may not be available to the profiling functions otherwise.)</em></p>

<p>But this only outputs the adress of the function and caller and not any of the inputs or outputs of the function.</p>

<pre><code>void __cyg_profile_func_enter (void *this_fn,
                               void *call_site);
void __cyg_profile_func_exit  (void *this_fn,
                               void *call_site);
</code></pre>

<p>I want to <code>cout &lt;&lt;</code> the arguments so I can do whitebox/integration testing: <strong>testing the input and output of a set of functions along an execution path in response to an event.</strong> </p>

<p>I know I could accomplish my desired instrumentation by running a Python script on my desired functions.</p>

<p><strong>QUESTION</strong></p>

<p>But is there a way to accomplish this instrumentation using only <code>gcc</code> options?</p>

<p><strong>THOUGHTS</strong></p>

<p>To accomplish this using only <code>gcc</code> and C++, I think I would need a way to loop over the function's arguments so I can call each object's <code>&lt;&lt;</code> operator.</p>
",https://stackoverflow.com/questions/58169256/gcc-instrumentation-is-it-possible-to-automatically-output-the-arguments-of-a,"['c++', 'gcc']",400,False,2,1
Mocking inbound Jax-RS Response with Entity,"<p>I am trying to unit test a class that uses Jersey 2 Client + Moxy to call a REST service. I want to mock the response, which contains a large JSON object. The code is structured in such a way that I can override/mock the following method:</p>

<pre><code>protected Response doPost(String path, Entity&lt;?&gt; entity) {
    Invocation.Builder invocationBuilder = getRestInvocationBuilder(path);
    Response response = invocationBuilder.post(entity);
    return response;
}
</code></pre>

<p>I would like to somehow inject some example JSON data (ideally from a file) into the Response at this point, prior to <code>readEntity()</code> being called, so that I can test that the JSON data is correctly unmarshalled into the target object.</p>

<p>Is there any way to do this? Note that this is for unit testing and therefore I'm not interested in running a local server or other integration testing techniques.</p>

<p>I'm aware similar questions have been asked, but many seem out of date or have incomplete solutions. The closest solution suggested is to mock the <code>readEntity()</code> method of the Response, this will not work for me because it would involve creating an object of the desired type to return, rather than creating one from the example JSON data.</p>
",https://stackoverflow.com/questions/58115808/mocking-inbound-jax-rs-response-with-entity,"['java', 'json', 'jersey-2.0', 'moxy']",432,False,1,0
Selenium Hub - create a reusable profile,"<p>I need to execute integration testing using Python code and Selenium HUB driver.
I'm planning to use remote driver (I'm using Selenium HUB docker image on <a href=""https://github.com/SeleniumHQ/docker-selenium"" rel=""nofollow noreferrer"">https://github.com/SeleniumHQ/docker-selenium</a>).</p>

<p>I am unable to figure out how to create a persistent profile in the Selenium HUB image and recall from remote webdriver.
I guess I need to first create the profile on Selenium HUB, than recall in the python code:
    chrome_options = webdriver.ChromeOptions()</p>

<pre><code>chrome_options.add_argument('user-data-dir=##remotepath')

browser = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub',desired_capabilities = chrome_options.to_capabilities())

browser.get('http://www.google.it')
session_id = browser.session_id
</code></pre>

<p>How can I create the ""<strong>user data dir</strong>"" profile on docker selenium hub image?</p>

<p>Thx</p>

<h3>UPDATE</h3>

<p>I run ""chrome:\version"" and I was able to identify the profile
<a href=""https://i.stack.imgur.com/4GOmY.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/4GOmY.png"" alt=""enter image description here""></a></p>

<p>I was able to specify it in the '<strong>user-data-dir</strong>' param but, after committing on docker, when re-launching the image, the path change.
Is it there any way to make it persistent?</p>

<h3>UPDATE 2</h3>

<p>I've created a folder ""/etc/opt/chrome/profile/maya""</p>

<p>I've created a test_policy.json file:</p>

<pre><code>{
  ""UserDataDir"": ""/etc/opt/chrome/profile/maya""
}
</code></pre>

<p>placed in this directory:</p>

<pre><code>/etc/opt/chrome/policies/managed
</code></pre>

<p>When I try to execute the ""chrome://policy/"" I see this:</p>

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

<p>Indicating something is wrong:
<a href=""https://i.stack.imgur.com/Hu3jh.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Hu3jh.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/57376153/selenium-hub-create-a-reusable-profile,"['docker', 'selenium-webdriver', 'selenium-docker']",553,True,1,1
Performance testing with external dependencies,"<p>When performance testing in the microservices world (talking mainly load testing), what is your approach regarding external dependencies (APIs) your application relies on, but not owned/controlled by your team. In my case the external dependencies are owned by teams within the same company.So would you point to the corresponding ""real"" integration non-prod endpoints OR you would create stubs and mimic their response times in order to match production as much as possible?</p>

<ul>
<li>First approach example: A back-end api owned by your team and calling an external api to verify a customer. Your team doesn't have control over the customer api, but you still point to their integration testing endpoint when running the load test.</li>
<li>Second approach example: A back-end api owned by your team calls a stub that sends a static response and mimics the response time of the external customer api.</li>
</ul>

<p>I realise there are pros and cons of the two approaches, and one would favour over the other depending on the goals of the testing. But what is your preferred one? Shouldn't be necessarily a choice between the two mentioned above. Can be a completely different one.</p>
",https://stackoverflow.com/questions/59341411/performance-testing-with-external-dependencies,"['performance-testing', 'stub', 'external-dependencies']",1202,True,8,1
cannot access database from multiple unit tests,"<p>I had the connection string and a bunch of my unit tests using it in order to test the logic of some class which was applying some CRUD operations to it. So I was passing it as a private constant field in test class and sharing it to my tests. Everything worked perfectly fine!</p>

<p>But then I realized I have to do it as integration testing. So I've decided to use static helper class to create database via session for me tests to work with it and then drop.</p>

<p>The class is the following:</p>

<pre><code>public static class LocalDB
{
    public const string DB_DIRECTORY = ""Data"";

    public static string GetLocalDB(string dbName, bool deleteIfExists = false)
    {
        try
        {
            var outputFolder = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), DB_DIRECTORY);
            var mdfFilename = dbName + "".mdf"";
            var dbFileName = Path.Combine(outputFolder, mdfFilename);
            var logFileName = Path.Combine(outputFolder, $""{dbName}_log.ldf"");

            if (!Directory.Exists(outputFolder))
            {
                Directory.CreateDirectory(outputFolder);
            }

            if (File.Exists(dbFileName) &amp;&amp; deleteIfExists)
            {
                if (File.Exists(logFileName)) File.Delete(logFileName);
                File.Delete(dbFileName);
                CreateDatabase(dbName, dbFileName);
            }

            else if (!File.Exists(dbFileName))
            {
                CreateDatabase(dbName, dbFileName);
            }

            var connectionString = string.Format(@""Data Source=(LocalDB)\v11.0;AttachDBFileName={1};Initial Catalog={0};Integrated Security=True;"", dbName, dbFileName);

            CreateTable(connectionString, ""Cpa"", dbName);

            return connectionString;
        }
        catch(Exception ex)
        {
            throw;
        }
    }

    public static bool CreateDatabase(string dbName, string dbFileName)
    {
        try
        {
            var connectionString = @""Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True"";

            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();

                var cmd = connection.CreateCommand();

                DetachDatabase(dbName);

                cmd.CommandText = string.Format(""CREATE DATABASE {0} ON (NAME = N'{0}', FILENAME = '{1}')"", dbName, dbFileName);
                cmd.ExecuteNonQuery();

                cmd.Dispose();
            }

            return File.Exists(dbFileName);
        }
        catch
        {
            throw;
        }
    }

    public static bool DetachDatabase(string dbName)
    {
        try
        {
            var connectionString = $@""Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True"";

            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();

                var cmd = connection.CreateCommand();
                cmd.CommandText = $""exec sp_detach_db '{dbName}'"";
                cmd.ExecuteNonQuery();

                cmd.Dispose();
                return true;
            }
        }
        catch(Exception ex)
        {
            return false;
        }

    }

    public static bool CreateTable(string connectionString, string tableName, string dbName)
    {
        connectionString = connectionString.Replace(""master"", dbName);
        try
        {
            using (var connection = new SqlConnection(connectionString))
            {
                var createTableQuery = $@""CREATE TABLE {tableName}(
                                            CrmId nvarchar(50) NOT NULL,
                                            Service nvarchar(25) NOT NULL,
                                            RecurringReference nvarchar(50),
                                            ExpiryDate datetime,
                                            CardNumber nvarchar(50),
                                            Enabled bit,
                                            Brand nvarchar(50),
                                            CpaType nvarchar(50),
                                            Channel nvarchar(50)
                                                                );"";

                var command = new SqlCommand(createTableQuery, connection);

                connection.Open();

                var reader = command.ExecuteReader();
                reader.Dispose();

                return true;
            }
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}
</code></pre>

<p>I was calling it's <strong>GetLocalDB</strong> method in my test class' ctor amd initializing field.
After that I've got the following error ""the process cannot access the file blah <strong>log.ldf</strong> because it is used by another process""</p>

<p><strong>!!!</strong> All the tests were using the same connection string, I have no idea what's gone wrong. It can't be the unit tests failure for all I've changed is connection string (was for already existent db -> changed to temporary local (LocalDb class))</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/54312581/cannot-access-database-from-multiple-unit-tests,"['c#', 'sql', '.net', 'sql-server', 'database']",248,False,0,1
isolating database operations for integration tests,"<p>I am using NHibernate and ASP.NET/MVC. I use one session per request to handle database operations. For integration testing I am looking for a way to have each test run in an isolated mode that will not change the database and interfere with other tests running in parallel. Something like a transaction that can be rolled back at the end of the test. The main challenge is that each test can make multiple requests. If one request changes data the next request must be able to see these changes etc.</p>

<p>I tried binding the session to the auth cookie to create child sessions for the following requests of a test. But that does not work well, as neither sessions nor transactions are threadsafe in NHibernate. (it results in trying to open multiple DataReaders on the same connection)
I also checked if TransactionScope could be a way, but could not figure out how to use it from multple threads/requests.</p>

<p>What could be a good way to make this happen?</p>
",https://stackoverflow.com/questions/57791034/isolating-database-operations-for-integration-tests,"['asp.net', 'asp.net-mvc', 'nhibernate', 'integration-testing']",264,True,0,1
How Can I Verify varargs To RPC Calls Before Runtime?,"<p>I can make an RPC call in Java <a href=""https://github.com/corda/samples/blob/master/obligation-cordapp/java-source/src/main/java/net/corda/examples/obligation/ObligationApi.java#L192-L194"" rel=""nofollow noreferrer"">like this</a>:</p>

<pre><code>        final FlowHandle flowHandle = rpcOps.startFlowDynamic(
                TransferObligation.Initiator.class,
                linearId, newLender, true);
</code></pre>

<p>The first parameter is the class to invoke and the next three are arguments to the class passed via varargs.</p>

<p>As we can see by the <a href=""https://github.com/corda/samples/blob/master/obligation-cordapp/java-source/src/main/java/net/corda/examples/obligation/flows/TransferObligation.java#L64-L67"" rel=""nofollow noreferrer"">class definition</a> the args match and the call works fine:</p>

<pre><code>    public Initiator(UniqueIdentifier linearId, Party newLender, Boolean anonymous) {
        this.linearId = linearId;
        this.newLender = newLender;
        this.anonymous = anonymous;
    }
</code></pre>

<p>However, if I add or remove args from the constructor the code will still compile and I will only notice at runtime (or <strong>integration</strong> testing - assuming I have enough test coverage).</p>

<p>The same applies if I pass the wrong args in the first place in the RPC call.
e.g. the following compiles fine but gives a runtime error:</p>

<pre><code>        final FlowHandle flowHandle = rpcOps.startFlowDynamic(
                TransferObligation.Initiator.class,
                linearId, newLender, true, 100000L, ""Random String"");
</code></pre>

<p>Is it possible to check for these errors with something other than test cases?</p>

<p>e.g. Static analysis using a custom IDEA code inspection or a custom SonarQube rule</p>

<p><strong>EDIT:</strong> It appears that the Kotlin API has a type safe way of starting the flows (using inline reified extension functions) that the Java API does not, so I have removed the kotlin tag and updated the references to Java examples.</p>
",https://stackoverflow.com/questions/57731969/how-can-i-verify-varargs-to-rpc-calls-before-runtime,"['java', 'corda', 'static-analysis']",66,True,0,1
Grails integration test fails with &quot;Unsatisfied dependency expressed through constructor parameter&quot;,"<p>Grails v3.3.9 and jsonView 1.2.10</p>

<p>I have a domain class query that fails when running an integration test  with class my Domain class Device, extends ManagedEntity (abstract) which extends RootEntity (also abstract).  Device has two static withCriteria queries to do eager fetches.</p>

<p>domain class Device.groovy:</p>

<pre><code>Device extends ManagedEntity {
OrgRoleInstance org
Site site
Location location
NetworkDomain domain //can only be in one domain or zero
ProviderNetwork vfNetwork  //can be part of one CSP network domain
//simpler option than deviceRoles - not an entity in this case but  a join table
Collection&lt;Resource.ResourceRoleType&gt; roles = [] // creates device_roles table no versioning */
Collection&lt;FlexAttribute&gt; attributes = []
Collection&lt;Equipment&gt; buildConfiguration = []
Collection&lt;Interface&gt; interfaces = []
Collection&lt;Alias&gt; aliasNames = []


boolean freeStanding = false
boolean testDevice = false
Product product  //ref to portfolio offering if exists
String deviceStatus = ""Operational""  //or Ceased or ...
String licenceType  //e.g. for cisco 903 would be one of  ""metro servcices"", or ""metro Ip services"", ""metro aggregation services""
String licence = ""none""
String memory
String storage
String numberOfCpu
Software runtimeOS

boolean isTestEntity () {
    testDevice
}

boolean isFreeStanding () {
    freeStanding
}

static hasMany = [deviceRoles: Resource, roles: Resource.ResourceRoleType, attributes:FlexAttribute, buildConfiguration: Equipment, interfaces:Interface, aliasNames:Alias]

static belongsTo = [org:OrgRoleInstance]  //dont at providerNetwork as belongs to as we dont want cascade delete



static constraints = {
    org nullable:true
    site nullable:true
    location nullable:true
    roles nullable:true
    domain nullable:true  , validator : {NetworkDomain domain, Device dev -&gt;
        //assumes org has been set
        if (domain == null)
            return true
        if (dev.org == null)
            log.debug ""org was null, trying to validate domain is in orgs.domains list - so org must be set first""
        NetworkDomain[] validDomains = dev?.org?.domains ?: []
        boolean test = validDomains.contains(domain)
        test
    }
    vfNetwork nullable:true , validator : {ProviderNetwork vfNetwork, Device dev -&gt;
        if (vfNetwork == null)  return true
        OrgRoleInstance vf = OrgRoleInstance.findByNameAndRole (""Vodafone"", OrgRoleInstance.OrgRoleType.ServiceProvider)
        ProviderNetwork[] networks = vf?.providerNetworks ?: []
        boolean test = networks.contains (vfNetwork)
        if (test == false)
            log.debug ""Vodafone provider does not yet have any ProviderNetworks to validate to, please create and save any provider networks before assigning to device, then save ""
        test
    }//ensure its in vf's list of provider networks }*/
    product nullable:true
    deviceStatus nullable:true
    licenceType nullable:true
    licence nullable:true
    memory nullable:true
    storage nullable:true
    numberOfCpu nullable:true
    runtimeOS nullable:true
    attributes nullable:true
    buildConfiguration nullable:true
    interfaces nullable:true
    aliasNames nullable:true
}

String toString () {
    ""Device (manHostname:$manHostName, opState:$opStatus)[id:$id]""
}

//Queries
static Device getFullDeviceById (Serializable id) {
    Device.withCriteria (uniqueResult:true) {
        join 'domain'
        join 'providerNetwork'
        join 'site'
        join 'location'
        join 'runtimeOS'
        fetchMode 'product', FetchMode.SELECT
        fetchMode 'interfaces', FetchMode.SELECT
        fetchMode 'attributes', FetchMode.SELECT
        fetchMode 'aliasNames', FetchMode.SELECT
        fetchMode 'buildConfiguration', FetchMode.SELECT

        idEq (id as Long)
    }
}

//Queries
static List&lt;Device&gt; getFullDeviceBySite (Serializable sid) {
    Device.withCriteria (uniqueResult:true) {
        join 'domain'
        join 'providerNetwork'
        join 'site'
        join 'location'
        join 'runtimeOS'
        fetchMode 'product', FetchMode.SELECT
        fetchMode 'interfaces', FetchMode.SELECT
        fetchMode 'attributes', FetchMode.SELECT
        fetchMode 'aliasNames', FetchMode.SELECT
        fetchMode 'buildConfiguration', FetchMode.SELECT

        site {idEq (sid as Long)}
    }
}
}
</code></pre>

<p>My test integration test fails with this (as seen from test report)</p>

<pre><code>&lt;testcase time=""0.0"" name=""build relationship between two CI "" classname=""com.softwood.domain.DeviceIntegSpecSpec""&gt;

&lt;failure type=""org.springframework.beans.factory.UnsatisfiedDependencyException"" message=""org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.softwood.controller.JsonApiRestfulController': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.Class&lt;?&gt;' available: expected at least 1 bean which qualifies as autowire candidate. 
</code></pre>

<p>My pared-back test looks like this, which just calls the static query (data is loaded in Bootstrap):</p>

<p>DeviceIntegrationTestSpec </p>

<p>void ""build relationship between two CI ""() {</p>

<pre><code>    given:

    Device pe = Device.getFullDeviceById(2)

    assert pe

    when : ""build a ce and relate the CE and PE  ""


    then:

        true


}
</code></pre>

<p>This appears to be objecting about my Controller class (which I'm not testing) which actually runs fine when i do a run-app (starts without errors).</p>

<p>How can I fix this? I am not sure if this is related:</p>

<p><a href=""https://github.com/grails/grails-core/issues/11005"" rel=""nofollow noreferrer"">similar problem in someone's plugin </a></p>

<p>If I fire up the Groovy console and run the query like this:</p>

<pre><code>import com.softwood.domain.Device

Device pe = Device.getFullDeviceById(2)

println pe
</code></pre>

<p>this runs fine without errors - so it's something to do with launching the integration testing framework and not loading all my controllers. I want to write some integration tests and can't because this is a blocker.</p>
",https://stackoverflow.com/questions/54430493/grails-integration-test-fails-with-unsatisfied-dependency-expressed-through-con,"['grails', 'integration-testing']",312,False,0,1
Dockerized integration test an ASP.NET Core app connection to RabbitMQ,"<p>I have very new to the dockerized integration testing world, so my apologies in advance if the question sounds very trivial.</p>

<p>I have an ASP.NET Core app that communicates with a dockerized RabbitMQ instance. When I start the application for debugging, <code>docker-compose</code> creates an container of that app and RabbitMQ, and then app is able to establish a connection to the RabbitMQ service. However, when running integration tests, the app fails to establish connection to the RabbitMQ service. </p>

<p>I do have a separate <code>docker-compose</code> for the integration tests that starts the RabbitMQ service, which I run it before running integration tests. </p>

<p>The test and application setup is fairly simple and follows a common setup, and is defined as: </p>

<pre class=""lang-cs prettyprint-override""><code>public class WebAPITest : IClassFixture&lt;WebApplicationFactory&lt;Program&gt;&gt;
{
    private readonly WebApplicationFactory&lt;Program&gt; _factory;

    public WebAPITest(WebApplicationFactory&lt;Program&gt; factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task IfConsumerReceives()
    {
        var client = _factory.CreateClient();
        var response = await client.GetAsync(""/api/requestitems"");

        // assert
        response.EnsureSuccessStatusCode();
    }
}
</code></pre>

<p>The application has a RabbitMQ service, defined as it follows in the <code>Startup</code> class: </p>

<pre class=""lang-cs prettyprint-override""><code>public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc(options =&gt; options.EnableEndpointRouting = false)
        .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

    RegisterEventBus(services);
    services.AddOptions();
}

private void RegisterEventBus(IServiceCollection services)
{
    services.AddSingleton&lt;IRabbitMQPersistentConnection&gt;(sp =&gt;
    {
        var factory = new ConnectionFactory()
        {
            HostName = Configuration[""RabbitMQConnection:HostName""],
            Port = Configuration.GetValue&lt;int&gt;(""RabbitMQConnection:Port""),
            DispatchConsumersAsync = true
        };

        factory.UserName = Configuration[""RabbitMQConnection:UserName""];
        factory.Password = Configuration[""RabbitMQConnection:Password""];
        var retryCount = int.Parse(Configuration[""RabbitMQConnection:RetryCount""]);
        return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount);
    });

    var queueName = Configuration[""QueueName""];
    services.AddSingleton&lt;IEventBus, EventBusRabbitMQ&gt;(sp =&gt;
    {
        var rabbitMQPersistentConnection = sp.GetRequiredService&lt;IRabbitMQPersistentConnection&gt;();
        var iLifetimeScope = sp.GetRequiredService&lt;ILifetimeScope&gt;();
        var logger = sp.GetRequiredService&lt;ILogger&lt;EventBusRabbitMQ&gt;&gt;();
        var eventBusSubcriptionsManager = sp.GetRequiredService&lt;IEventBusSubscriptionsManager&gt;();

        var retryCount = int.Parse(Configuration[""RabbitMQConnection:RetryCount""]);

        return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, queueName, retryCount);
    });

    services.AddSingleton&lt;IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager&gt;();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseHttpsRedirection();
    app.UseMvc();
    ConfigureEventBus(app);
}

private void ConfigureEventBus(IApplicationBuilder app)
{
    // The following fails to establish connection to RabbitMQ when running integration tests.
    var eventBus = app.ApplicationServices.GetRequiredService&lt;IEventBus&gt;();
    eventBus.Subscribe&lt;CollectionCompletedIntegrationEvent, CollectionCompletedIntegrationEventHandler&gt;();
}
</code></pre>

<p>The error message I receive is: </p>

<blockquote>
  <p>RabbitMQ.Client.Exceptions.BrokerUnreachableException: 'None of the specified endpoints were reachable'</p>
</blockquote>

<p>Any suggestions is warmly appreciated. </p>

<hr>

<h2>Update 1</h2>

<p>As requested docker compose files are as it follows; however, I am not sure these files are called when running integration tests, they are called when debugging only. </p>

<ul>
<li><code>docker-compose</code></li>
</ul>

<pre><code>version: '3.4'

services:

  sql.data:
    image: microsoft/mssql-server-linux:2017-latest

  rabbitmq:
    image: rabbitmq:3-management-alpine

  myapp:
    image: ${DOCKER_REGISTRY-}myapp
    build:
      context: .
      dockerfile: myapp/Dockerfile
    depends_on:
      - sql.data
      - rabbitmq
</code></pre>

<ul>
<li><code>docker-compose.override.yml</code>:</li>
</ul>

<pre><code>version: '3.4'

services:
  sql.data:
    environment:
      - SA_PASSWORD=Pass_word
      - ACCEPT_EULA=Y
    ports:
      - ""1433:1433""

  rabbitmq:
    ports:
      - ""15672:15672""
      - ""5672:5672""

  myapp:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=https://+:443;http://+:80
      - ASPNETCORE_HTTPS_PORT=44376
    ports:
      - ""61936:80""
      - ""44376:443""
    volumes:
      - ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
      - ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro
</code></pre>
",https://stackoverflow.com/questions/58760400/dockerized-integration-test-an-asp-net-core-app-connection-to-rabbitmq,"['c#', 'docker', 'asp.net-core', 'rabbitmq']",577,False,0,0
How to perform integration testing on EF Core migrations,"<p>I've searched extensively on this subject and have found zero results for exactly what it is that I want to do.</p>
<p>From a high level, this is what I want to do:<br/></p>
<ul>
<li>Arrange: Within a test method, call appropriate services to seed the database.</li>
<li>Act: Run a migration to update the database schema.</li>
<li>Assert: Data integrity, i.e., seed data can be accessed as per the updated entity structure.</li>
</ul>
<p>What's the point of this?<br/>
Well it's pretty much described in the assertion above; data integrity. Migrations in this project are run on app startup using <code>Database.Migrate()</code>. I'd like to make sure that there's no loss/corruption of existing data.</p>
<p>All examples of integration testing I've come across pretty much run <code>Database.Migrate()</code> as part of the test setup, followed by seeding, and then making assertions. This however is only useful in testing the data access layer given the <em>latest</em> schema (with all migrations already applied). It's not useful in testing the effects of a specific migration on data that already exists.</p>
<p><strong>Question:</strong><br/></p>
<p>How have others tackled the issue of testing data integrity across migrations? I'm looking for a setup which would work well with a CI pipeline.</p>
",https://stackoverflow.com/questions/55086435/how-to-perform-integration-testing-on-ef-core-migrations,"['asp.net-web-api', 'integration-testing', 'entity-framework-migrations', 'ef-core-2.0']",1607,True,6,2
Mock service for xUnit,"<p>I have an application that currently works as designed, but I am trying to setup integration testing with xUnit before I expand upon it. At the moment the test will only use the original service when performing the test and I don't see why.</p>

<p>This the is the test:</p>

<pre class=""lang-cs prettyprint-override""><code>using IStoreRepository = Repositories.V3.Interfaces.IStoreRepository;

public class StoreTests : IClassFixture&lt;WebApplicationFactory&lt;Startup&gt;&gt; {
    private readonly ITestOutputHelper _output;
    private readonly WebApplicationFactory&lt;Startup&gt; _factory;
    private readonly string _url;

    public StoreTests(ITestOutputHelper output, WebApplicationFactory&lt;Startup&gt; factory) {
        _output = output;
        _factory = factory;

        _url = ""/api/store"";
    }

    [Theory]
    [InlineData(""GET"", ""FAKE123"")]
    public async Task StoreByCode(string method, string code = null) {
        // var client = _factory.CreateClient();

        var client = _factory.WithWebHostBuilder(builder =&gt; {
            builder.ConfigureTestServices(services =&gt; {
                services.AddScoped&lt;IStoreRepository, StoreRepositoryTest&gt;();
            });
        }).CreateClient();

        var request = new HttpRequestMessage(new HttpMethod(method), $""{_url}/{code}"");

        string readAsStringAsync;

        _output.WriteLine($""Request Uri: {request.RequestUri}"");

        using (var response = await client.SendAsync(request)) {
            response.EnsureSuccessStatusCode();
            readAsStringAsync = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode) {
                _output.WriteLine($""Not successful ({response.StatusCode}): {readAsStringAsync}"");
            }
        }

        var stores = JsonConvert.DeserializeObject&lt;List&lt;Store&gt;&gt;(readAsStringAsync);

        Assert.True(stores.Any());
    }
}
</code></pre>

<p>However when I conduct the test the break point in the real <code>Repository</code>, <code>StoreRepository</code> that is registered in Startup.cs is the one that is hit, not the break point in <code>StoreRepositoryTest</code>. I setup my factory to override the dependency, but it's ignoring it. What can I do to correct this.</p>

<p>For reference, I have been using this source: <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2</a></p>

<h1>Update</h1>

<p>Not sure if this question should be deleted or not but it ended up being a really silly mistake. I updated the code above to include a using alias. It turned out I was registering and overriding the V1 interface instead of V3. When I implemented the Mock class I didn't realize I was implementing the old service. So the good news is the above code is a working example of how to mock using Microsoft's documentation.</p>
",https://stackoverflow.com/questions/57617113/mock-service-for-xunit,"['c#', 'asp.net-core', 'integration-testing', 'xunit']",1654,True,3,2
EF Core DbContext Concurrency Issue with XUnit Tests,"<p>I seem to have a strange concurrency issue I can't seem to put my finger on. 
When I construct my implementation of a DbContext I inject the Entities I want to be built by the modelbuilder (don't worry about why). This is only done once by my app at runtime and runs fine, but when I'm integration testing DB integration, I inject only the test entities I need for my InMemoryDatabase.</p>

<p>Now I seem to have a weird issue where two unit tests in different class files needing different entities seem to get crossed over. </p>

<p>I keep running the unit tests and the first test will pass, but the second test will fail saying that TestObjectB doesn't exist in the model. When I inspect the model it says TestObjectA exists instead, even though it wasn't injected on this test. So as if the implementation of the DataContext was static and overwritten...These are different files and fresh constructors for the context, I don't understand how they are crossing paths? If I run the unit test that fails on it's own, it passes.</p>

<p>Note the following code has been simplified for your view.</p>

<p>DB Context:</p>

<pre><code>public class DataContext : DbContext
{
    private readonly List&lt;IEntity&gt; _entities;

    public DataContextA(List&lt;IEntity&gt; entities, DbContextOptions options) : base(options)
    {
        _entities = entities;
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var entity in _entities)
        {
            modelBuilder.Entity(entity.GetType());
        }
    }
}
</code></pre>

<p>Test Implementation 1:</p>

<pre><code>[Fact]
            public void CheckUniqueFieldA()
            {
                var options = new DbContextOptionsBuilder&lt;DataContext&gt;();

                options.UseInMemoryDatabase(Guid.NewGuid().ToString());

                using (var context = new DataContext(new List&lt;IEntity&gt; { new TestObjectA() }, options.Options))
                {
                    //Do Something
                }
            }
</code></pre>

<p>Test Implementation2:</p>

<pre><code>[Fact]
            public void CheckUniqueFieldB()
            {
                var options = new DbContextOptionsBuilder&lt;DataContext&gt;();

                options.UseInMemoryDatabase(Guid.NewGuid().ToString());

                using (var context = new DataContext(new List&lt;IEntity&gt; { new TestObjectB() }, options.Options))
                {
                    //Do Something
                }
            }
</code></pre>
",https://stackoverflow.com/questions/56311901/ef-core-dbcontext-concurrency-issue-with-xunit-tests,"['c#', 'entity-framework-core', 'xunit']",1208,True,2,1
Factors that contribute to an R binary package,"<p>Binary packages are generally not available for Linux (see discussion at <a href=""https://stackoverflow.com/q/11871394/169947"">Create R binary packages for Linux that can be installed on different machines?</a>, for example).</p>

<p>However, this can often lead to very long build times when doing Continuous Integration testing.  After many years of just waiting for those long builds, I would like to build binary packages from source, then cache those binaries for reinstallation later in future builds.</p>

<p>The question is what factors should go into the cache key - what should be considered ""the same platform"" so that a binary package can (relatively) safely be pulled from the cache and installed.  I can think of:</p>

<ul>
<li>Everything in <code>R.version</code> (or maybe just the entries <code>platform</code>, <code>major</code>, and <code>minor</code>)</li>
<li>Everything in the output of <code>R CMD config --all</code></li>
<li>Value of <code>R.home()</code></li>
</ul>

<p>Anything else I'm missing?</p>

<p>My thought is to dump all this info into a file, compute an <code>md5</code> or <code>shasum</code> on it, and use that as the cache key.</p>

<p>I'm aware of some similar efforts, but nothing that fits the bill in a general way:</p>

<ul>
<li><a href=""https://github.com/r-lib/crancache"" rel=""nofollow noreferrer"">https://github.com/r-lib/crancache</a> (e.g. <a href=""https://github.com/r-lib/crancache/issues/20"" rel=""nofollow noreferrer"">https://github.com/r-lib/crancache/issues/20</a>)</li>
<li><a href=""https://cran.r-project.org/bin/linux/ubuntu/"" rel=""nofollow noreferrer"">https://cran.r-project.org/bin/linux/ubuntu/</a></li>
</ul>
",https://stackoverflow.com/questions/55835927/factors-that-contribute-to-an-r-binary-package,"['r', 'package', 'binaryfiles']",85,False,2,0
Hard-coded vs Soft-coded expected values for Integration Testing,"<p>I understand that in Unit Test, hard-coded is preferred as we don't want to write much code as possible.</p>

<p>For Integration Testing however, is the same principle still applied? For a context, here's a common scenario:</p>

<ul>
<li>TodoController</li>
<li>TodoService</li>
<li>Serializer/Transformer/Whatever you call it</li>
</ul>

<p>Here's an imaginary code on how both approach might look like:</p>

<ul>
<li>Hard Coded</li>
</ul>

<pre><code>// Arrange
$note = new Note('note123', 'John', 'example message');

$this-&gt;noteRepository-&gt;save($note);

// Act
$response = $this-&gt;json('GET', '/api/notes');

// Assert
$response-&gt;seeJsonEquals([
   'id' =&gt; 'note123',
   'author' =&gt; 'John',
   'message' =&gt; 'example message'
]);

</code></pre>

<ul>
<li>Soft Coded (Computed)</li>
</ul>

<pre><code>// Arrange
$note = new Note('note123', 'John', 'example message');

$this-&gt;noteRepository-&gt;save($note);

// Act
$response = $this-&gt;json('GET', '/api/notes');

// Assert
$noteSerializer = new NoteSerializer();

$response-&gt;seeJsonEquals($noteSerializer-&gt;serialize($note));
</code></pre>

<p>The only catch for the soft-coded approach is that if the Serializer is the problem, the test will still pass because both the controller and expected value uses it.</p>

<p>However, we can solve that by creating another test for the Serializer.</p>

<p>We might have lots of mini-tests but I think it'll us save lots of time compared to hard-coding. If we changed our response structure, the hard-coded tests will need some changes as well but the soft-coded one needs to change in its own test only.</p>

<p>I might be missing something but I already tried to Google it and all I see are always about Unit Tests so thought of asking if same principle is still applied in Integration Tests as well</p>
",https://stackoverflow.com/questions/54748034/hard-coded-vs-soft-coded-expected-values-for-integration-testing,"['testing', 'tdd', 'integration-testing']",1165,True,1,2
How to Unit Test a Method in Sitecore MVC having tightly coupled Dependency on two distinct Sitecore Contexts?,"<p>I have to unfortunately write Unit Tests for a legacy Sitecore MVC code base where two distinct Sitecore Contexts are called. I understand this comes under Integration Testing but i don't have the option of educating my project Leads on that front. So i have chosen to use <strong>FakeDb</strong> for emulating Sitecore Instance and <strong>NSubstitute</strong> for substituting injected Dependencies (can't use any Profilier API Frameworks like MS Fakes, TypeMock etc because of Budget constraints). I am providing the code below:</p>

<p><strong>Method to be UnitTested</strong></p>

<pre><code> public bool DubiousMethod()
 {
    // This HttpContext call is pain area 1. This gets resolved when i call it using ItemContextSwitcher in Unit Tests.
    string currentUrl = HttpContext.Current.Request.RawUrl; 

   // This Sitecore Context call to Site Name is pain area 2. This gets resolved when Unit Tests are run under SiteContextSwitcher.
    string siteName = Sitecore.Context.Site.Name;

    return true/False;
 }
</code></pre>

<p><strong>Unit Test Method</strong></p>

<pre><code>[Fact]

public void DubiousMethodUT()
{
 // create a fake site context            
        var fakeSite = new Sitecore.FakeDb.Sites.FakeSiteContext(
          new Sitecore.Collections.StringDictionary
           {
              { ""name"", ""website"" }, { ""database"", ""web"" }, { ""rootPath"", ""/sitecore/content/home"" },
              { ""contentStartItem"", ""home""}, {""hostName"",""https://www.myorignalsiteurl.com""}                 

           });

 using (new Sitecore.Sites.SiteContextSwitcher(fakeSite))
        {                           
            //DubiousClassObject.DubiousMethod(home) // When Debugging after uncommenting this line i get correct value in **Sitecore.Context.Site.Name**
            using (Sitecore.FakeDb.Db db = new Sitecore.FakeDb.Db
                 {

                   new Sitecore.FakeDb.DbItem(""home"") { { ""Title"", ""Welcome!"" } ,

                   new Sitecore.FakeDb.DbItem(""blogs"") }
                  })

            {

                Sitecore.Data.Items.Item home = db.GetItem(""/sitecore/content/home"");
                //bool abc = confBlogUT.IsBlogItem(home);
                using (new ContextItemSwitcher(home))
                {
                    string siteName = Sitecore.Context.Site.Name;
                    var urlOptions = new Sitecore.Links.UrlOptions();
                    urlOptions.AlwaysIncludeServerUrl = true;
                    var pageUrl = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item, urlOptions);
                    HttpContext.Current = new HttpContext(new HttpRequest("""", pageUrl.Substring(3), """"), new HttpResponse(new StringWriter()));



                    Assert.False(DubiousClassObject.DubiousMethod(home); //When Debugging after commenting above DubiousMethodCall i get correct value for **HttpContext.Current.Request.RawUrl**
                }
            }
        }
    }
</code></pre>

<p>As you can observe that when i try to call the method from FakSiteContext then i am getting the correct value for <strong>Sitecore.Context.Site.Name</strong> however my code breaks when <strong>HttpContext.Current.Request.RawUrl</strong> is invoked in the method. Opposite happens when i invoke the method from <strong>ContextItemSwitcher(FakeItem)</strong> context. So far i have not been able to find a way to merge both the Contexts (which i believe is impossible in Sitecore). Can anyone suggest if i run my Unit Tests in an overarching context where i am able to contrl fakeSite Variables as well as FakeItem context variables as well and by extensions any other Sitecore Context calls?</p>

<p>Any help would be appreciated.</p>
",https://stackoverflow.com/questions/58693235/how-to-unit-test-a-method-in-sitecore-mvc-having-tightly-coupled-dependency-on-t,"['unit-testing', 'model-view-controller', 'mocking', 'sitecore-mvc', 'sitecore9']",433,True,1,1
CakePHP 3.6 Controller Integration Testing - HTTP requests not sent,"<p>I am trying to implement controller integration testing in CakePHP <strong>3.6</strong> using its testing tools. I assumed that this would be handled by making a 'real' (as in CURL) HTTP request against the running webserver, but it looks like it isn't. Below is the test case code I'm using.</p>

<p>The problems I'm running into:</p>

<ol>
<li>The test case is somehow managing to access the controler action,
even when the webserver is not running at all (Apache down and no
dev webserver running).</li>
<li>When running this test, the controller does not have access to
<code>$_SERVER</code> (see below) and any of the <code>$postData</code> defined in the test case appears empty on the controller side.</li>
<li>When I place <code>exit;</code> in the controller code, the whole test case
stops, which suggests that the controller code is run directly, not
via a HTTP request.</li>
</ol>

<p><strong>Question:</strong> How can I make a 'real' HTTP requests when testing controllers, apart from resorting to using CURL and handling the requests manually?</p>

<p>Clearly, I am either not understanding how the controller testing is done, or I'm doing something wrong.</p>

<p>Test case I'm using:</p>

<p><strong>/tests/TestCase/Controller/JobsControllerTest.php</strong></p>

<pre><code>&lt;?php
namespace App\Test\TestCase\Controller;

use Cake\ORM\TableRegistry;
use Cake\TestSuite\IntegrationTestCase;

/**
 * App\Controller\JobsController Test Case
 */
class JobsControllerTest extends IntegrationTestCase
{

    /**
     * Test add method
     *
     * @return void
     */
    public function testAdd()
    {
        $this-&gt;useHttpServer(true);

        $this-&gt;configRequest([
            'headers' =&gt; [
                'Content-Type' =&gt; 'application/json',
                'X-Api-Key' =&gt; '8f083c8f083c8f083c8f083c'
            ]
        ]);
        $postData = [
            'user_id' =&gt; 3,
            'job_status' =&gt; 'New'
        ];
        $this-&gt;post('/jobs/add', $postData);

        $this-&gt;assertResponseSuccess();
        $jobs = TableRegistry::get('Jobs');
        $query = $jobs-&gt;find()-&gt;where(['user_id' =&gt; $postData['user_id']]);
        $this-&gt;assertEquals(1, $query-&gt;count());
    }

}
</code></pre>

<p><strong>The dump of <code>$_SERVER</code> global</strong> from the controller that I'm testing:</p>

<pre><code>Array
(
    [LS_COLORS] =&gt; rs=0:di=01;34 [...]
    [LANG] =&gt; en_US.UTF-8
    [HOME] =&gt; /home/tomasz
    [TERM] =&gt; screen
    [PATH] =&gt; /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
    [MAIL] =&gt; /var/mail/root
    [LOGNAME] =&gt; root
    [USER] =&gt; root
    [USERNAME] =&gt; root
    [SHELL] =&gt; /bin/bash
    [SUDO_COMMAND] =&gt; vendor/bin/phpunit --verbose
    [SUDO_USER] =&gt; tomasz
    [SUDO_UID] =&gt; 1000
    [SUDO_GID] =&gt; 1000
    [PHP_SELF] =&gt; vendor/bin/phpunit
    [SCRIPT_NAME] =&gt; vendor/bin/phpunit
    [SCRIPT_FILENAME] =&gt; vendor/bin/phpunit
    [PATH_TRANSLATED] =&gt; vendor/bin/phpunit
    [DOCUMENT_ROOT] =&gt;
    [REQUEST_TIME_FLOAT] =&gt; 1546631688.0758
    [REQUEST_TIME] =&gt; 1546631688
    [argv] =&gt; Array
        (
            [0] =&gt; vendor/bin/phpunit
            [1] =&gt; --verbose
        )

    [argc] =&gt; 2
)
</code></pre>
",https://stackoverflow.com/questions/54045338/cakephp-3-6-controller-integration-testing-http-requests-not-sent,"['testing', 'cakephp', 'phpunit']",323,True,0,1
Maven not recognizing integration tests in multi-module project,"<p>I'm trying to set up integration testing for my multi-module Maven project using the failsafe plugin.
In a smaller dummy project, I had the following structure:</p>

<pre><code>pom.xml
src 
-main
--java
---com
----App.java
-test
--java 
---com 
----AppIT.java
</code></pre>

<p>Here was the relevant addition to the pom.xml: </p>

<pre><code>&lt;profiles&gt;
  &lt;profile&gt;
    &lt;id&gt;failsafe&lt;/id&gt;
    &lt;build&gt;
      &lt;plugins&gt;
        &lt;plugin&gt;
          &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt;
          &lt;version&gt;2.22.0&lt;/version&gt;
          &lt;executions&gt;
             &lt;execution&gt;
               &lt;goals&gt;
                 &lt;goal&gt;integration-test&lt;/goal&gt;
                 &lt;goal&gt;verify&lt;/goal&gt;
               &lt;/goals&gt;
             &lt;/execution&gt;
          &lt;/executions&gt;
        &lt;/plugin&gt;
      &lt;/plugins&gt;
    &lt;/build&gt;
  &lt;/profile&gt;
&lt;/profiles&gt;         
</code></pre>

<p>Everything worked fine and the test was detected when I ran <code>mvn verify -Pfailsafe</code>.</p>

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

<p>For the new project, I have the following
structure:</p>

<pre><code>pom.xml
module-1
module-2
module-testing
-src
--test
---java    
----com
-----Test1.java
-----Test2.java
-----...
-----RestIT.java
</code></pre>

<p>All of Test1.java through TestN.java are unit tests. RestIT.java is the name of an empty integration test which I just want to be
detected by the verify command in the same way that AppIT.java was detected in the old dummy project.</p>

<p>Here is what I added to the pom.xml for the entire project (identical to what was in the pom.xml for the dummy Maven project):</p>

<pre><code>&lt;profiles&gt;
  &lt;profile&gt;
    &lt;id&gt;failsafe&lt;/id&gt;
    &lt;build&gt;
      &lt;plugins&gt;
        &lt;plugin&gt;
          &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt;
          &lt;version&gt;2.22.0&lt;/version&gt;
          &lt;executions&gt;
            &lt;execution&gt;
              &lt;goals&gt;
                &lt;goal&gt;integration-test&lt;/goal&gt;
                &lt;goal&gt;verify&lt;/goal&gt;
              &lt;/goals&gt;
            &lt;/execution&gt;
          &lt;/executions&gt;
        &lt;/plugin&gt;
      &lt;/plugins&gt;
    &lt;/build&gt;
  &lt;/profile&gt;
 &lt;/profiles&gt;
</code></pre>

<p>The existing unit tests are detected in the output of <code>mvn verify -Pfailsafe</code>, but the RestIT.java test is not. I've also
previously seen the error for ""the profile of failsafe not found"" before and it's not present when I run that command
with the above snippet added to the parent pom.xml.</p>

<p>If you're interested in seeing the entire maven command output or the whole pom.xml let me know and I'll add Dropbox links.</p>
",https://stackoverflow.com/questions/54096325/maven-not-recognizing-integration-tests-in-multi-module-project,"['java', 'maven', 'pom.xml', 'maven-plugin', 'maven-failsafe-plugin']",373,False,0,1
Azure functions integration testing locally,"<p>I am trying to run integration tests on an azure functions project locally. My method is to start the azure server programatically using a process. This does not work for some reason.</p>

<p>This is how i setup the process:</p>

<pre><code>private Process process;
private RestClient client;

[OneTimeSetUp]
public void OneTimeSetUp()
{
    const string dotnetExePath = @""C:\Program Files\dotnet\dotnet.exe"";
    const string functionHostPath = @""C:\Users\MyName\AppData\Local\AzureFunctionsTools\Releases\2.24.0\cli\func.dll"";
    const string functionAppFolder = @""C:\Users\MyName\Source\Repos\ShyftApi\ShyftApi\bin\Debug\netstandard2.0"";

    process = new Process
    {
        StartInfo =
        {
            FileName = dotnetExePath,
            Arguments = $""\""{functionHostPath}\"" start -p {7001}"",
            WorkingDirectory =  functionAppFolder
        }
    };

    bool success = process.Start();
    Assert.AreEqual(true, success);
    client = new RestClient($""http://localhost:{7001}/api"");
    Thread.Sleep(8000);
}
</code></pre>

<p><code>OneTimeSetup</code> succeeds without an error so i assume that the process started correctly (but i see no azure shell, wierd?)</p>

<p>I run a simple http call (using restsharp):</p>

<pre><code>[Test]
public void SimpleTest()
{
    RestRequest request = new RestRequest(""/test"", Method.POST);
    IRestResponse response = client.Execute(request);
    Assert.AreEqual(200, response.StatusCode);
}
</code></pre>

<p>This is the azure function that i am trying to test:</p>

<pre><code>[FunctionName(""test"")]
public static IActionResult Test([HttpTrigger(AuthorizationLevel.Anonymous, ""get"", Route = null)]HttpRequest req, TraceWriter log)
{
    return new OkObjectResult(""ok"");
}
</code></pre>

<p>The test fails because <code>response.StatusCode</code> is 0 so i assume that the server is not up. </p>

<p>I followed the format used in <a href=""https://blog.kloud.com.au/2018/11/08/integration-testing-precompiled-v2-azure-functions/"" rel=""nofollow noreferrer"">https://blog.kloud.com.au/2018/11/08/integration-testing-precompiled-v2-azure-functions/</a> for the arguments to the process. I have manually checked that the paths are correct (But the process starts sucessfully so i dont think the paths are the issue?). </p>

<p>The endpoint i am trying to hit is <code>http://localhost:7071/api/test</code> and when running the azure server regurarly (F5) and accessing it through my browser i get a 200 ok.</p>

<p>What do you think could be the issue? The starting arguments to the process or am i just using the wrong url?</p>
",https://stackoverflow.com/questions/56759066/azure-functions-integration-testing-locally,"['azure', 'rest', 'process', 'integration-testing', 'restsharp']",434,False,-1,1
Mockito Unit Test with HTTPUrlConnection,"<p>I wrote code in our Spring Boot 2 application to make a third-party API call with HTTPUrlConnection.</p>

<pre><code>public String loginApi(LoginDTO loginDto)
{
    String responseData = null;
    HttpURLConnection conn = null;
    try {
        link = authBaseUrl + loginUrl;
        url = new URL(link);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(""POST"");
        conn.setRequestProperty(CONTENT_TYPE, MEDIA_TYPE);
        String body = getAuth0LoginDto(loginDto);
        // =====================
        // For POST only - START
        conn.setDoOutput(true);
        OutputStream os = conn.getOutputStream();
        os.write(body.getBytes(StandardCharsets.UTF_8));
        os.flush();
        os.close();
        // For POST only - END
        // ====================

        try (BufferedReader br = (conn.getResponseCode() &gt;= 400
                ? new BufferedReader(new InputStreamReader(conn.getErrorStream()))
                : new BufferedReader(new InputStreamReader(conn.getInputStream())))) {

            StringBuilder everything = new StringBuilder();
            String output = null;
            while ((output = br.readLine()) != null) {
                everything.append(output);
            }
            responseData = everything.toString();
        }
    } catch (JsonProcessingException e) {
        throw new Auth0Exception(""Could not create Auth0 Login Body"", e);
    } catch (IOException e) {
        throw new Auth0Exception(""Error with Login API"", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return responseData;
}
</code></pre>

<p>Now, I am very much used to doing real integration testing, where I make a real call to the web-service and check the results.</p>

<p>I am now being asked to use strictly Mockito, not PowerMockito, not EasyMock, to create mocking tests, and I have never done that before.   My knowledge of Mockito is weak also since I haven't used it in a very long time.</p>

<p>So, I know it has been asked before, and I have really searched on the internet, and I really haven't found a full piece of code as an example.  I see code snippets which leaves me with pieces missing, and I am not knowledgeable enough to add those parts myself.</p>

<p>I know this code actual implementation works fine, and the integration test works fine also.  But, what I have seen before is that some users are being told they need  to change their client code in order to make the mockito tests work.</p>

<p>If I don't get the mocking tests working for HTTPUrlConnection, then I'll be forced to switch over to RestTemplate and Mocking since my co-worker insists we use RestTemplate anyway.</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/55070105/mockito-unit-test-with-httpurlconnection,"['spring-boot', 'java-8', 'mockito']",11038,True,2,1
How can I fix my test suites failure to run because of the tcomb-form-native library for React Native?,"<p>I am trying to perform unit testing and integration testing for a React Native application. When running <code>yarn test --coverage</code> several of my test suites fail to run because of the tcomb-form-native library.</p>

<p>I receive this specific error: </p>

<p><code>({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){import t from ""./lib"";
</code>                                                                                             </p>

<pre><code>SyntaxError: Unexpected identifier

  13 | // import { gray } from 'ansi-colors';
  14 |
&gt; 15 | import t from 'tcomb-form-native';
     | ^
  16 |
  17 | const Form = t.form.Form;
  18 |

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
  at Object.&lt;anonymous&gt; (screens/ReservationScreen.js:15:1)
</code></pre>

<p>I updated the <code>package.json</code> file following the Tests section from the library's GitHub, <a href=""https://github.com/gcanti/tcomb-form-native"" rel=""nofollow noreferrer"">https://github.com/gcanti/tcomb-form-native</a>, but continue to get the same error. </p>

<p>I'm confused by this line from the tcomb-form-native ReadMe Tests description:</p>

<pre><code>  ""ios.js""    &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; this needs to be defined!
</code></pre>

<p>I created the React Native app using Expo so I don't have an ios.js file. The only difference under the <code>""jest"":</code> from the example code in the GitHub is that I also have <code>""preset"": ""jest-expo"",</code> defined.</p>

<p><strong>What changes do I need to make to my <code>package.json</code> file or my test suites in order for my test suites to run?</strong> (They don't have to pass, just simply run.)</p>

<hr>

<p><em>Edit:</em> </p>

<p>I tried adding the following code to <code>package.json</code> based on the top answer from <a href=""https://github.com/gcanti/tcomb-form-native/issues/443"" rel=""nofollow noreferrer"">https://github.com/gcanti/tcomb-form-native/issues/443</a>: </p>

<pre><code>""transformIgnorePatterns"": [
  ""node_modules/(?!react-native|tcomb-form-native)""
]`
</code></pre>

<p>I added the code without the original suggested edits from the library's GitHub ReadMe and added it IN ADDITION to the suggested edits. I am still receiving <code>SyntaxError: Unexpected identifier</code> when I run tests.</p>

<hr>

<p><em>Edit #2:</em> </p>

<p>I changed changed <code>import t from 'tcomb-form-native';</code> to <code>var t = require('tcomb-form-native');</code> and I'm still receiving <code>SyntaxError: Unexpected identifier.</code></p>
",https://stackoverflow.com/questions/55523157/how-can-i-fix-my-test-suites-failure-to-run-because-of-the-tcomb-form-native-lib,"['reactjs', 'react-native', 'jestjs', 'expo', 'tcomb-form-native']",266,False,0,0
Gradle build-cache in composite builds,"<p>I'm dealing with weird behavior using gradle <em><strong>build-cache</strong></em> with <em><strong>composite builds</strong></em>.
I have a repo where i have 3 independent projects:</p>
<ul>
<li>app</li>
<li>mocks</li>
<li>integration-tests</li>
</ul>
<p>Integration-tests are including 2 builds - mocks and app and starting both services as java apps (depending on jar task of both projects).</p>
<h3>Running locally</h3>
<p>When running locally, everything seems fine (also using build cache), but on integration machine, something weird is happening.</p>
<h3>Integration testing</h3>
<p>We use gitlab, and pipiline is quite simple:</p>
<pre><code>---|-- junit-mocks --|--- integration-tests
   |-- junit-app ----|
</code></pre>
<p>junit mocks and junit app in parallel (with build cache) and next stage is int-testing where java compilation of app and mocks is loaded from build-cache. (as you can see in picture attached).</p>
<p>The error is only a consequence, that Main class was not found (weird#1). When i looked inside the jar file, it was truly half empty, missing a lot of classes, but static resources were there. When i looked into gradle's build/classes dir, it was completely empty. It's like cache was hit, but classes were not copied?</p>
<p>Weird#2: is that mocks has built successfully (and started), but not the app.</p>
<p>When I turned off build cache, build passed.</p>
<p>Any ideas what could cause the issue?</p>
<p><a href=""https://i.stack.imgur.com/aNpVs.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/aNpVs.jpg"" alt=""Example of build"" /></a></p>
",https://stackoverflow.com/questions/54438080/gradle-build-cache-in-composite-builds,"['gradle', 'build', 'gitlab']",244,False,0,1
Java Testcontainers - Cannot connect to exposed port,"<p>I implemented a POP3 server and client using javax.mail just to try doing integration testing with Docker. So I created two Docker images based on the openjdk:8-jre image and copied my jars to them and started it. Based on my configuration (see below) it is working. They are talking to each other.</p>
<p>But as want to have multiple integration tests it is going to be tedious to build an image for each one and starting them. Also I don't know how to automate the results.
But then I stumbled across TestContainers and it seems that this would be big help when implementing those tests.</p>
<p>So I started to port those tests to TestContainers using my POP3 Server image as a GenericContainer and starting my POP3 Client classes in the JUnit test method. I exposed the port 24999 which my POP3 Server is listening to. But when I try to connect to the server I get the following error:</p>
<pre><code>com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 32782; timeout -1;
  nested exception is:
    java.net.ConnectException: Connection refused
...
</code></pre>
<p>There is probably some setting I am missing in TestContainers. Could you please help me.</p>
<p>Here is the code I am using:</p>
<pre><code>public class DockerPop3AutocryptKeyProvidingAndReceivingTest {
    @Test
    public void test() throws InterruptedException {
        GenericContainer container = new GenericContainer&lt;&gt;(&quot;immerfroehlich/emailfilter:latest&quot;)
                .withExposedPorts(24999);
        
        container.start();
        
        String host = container.getContainerIpAddress();
        String port = container.getFirstMappedPort().toString();

        //The following is simplified, but copied from the working jar used in the Docker Client image/container
        MyPOP3Client client = new MyPOP3Client(host, port);
        client.connect();
        
        container.stop();
    }
}
</code></pre>
<p>This is how I create my Docker image:</p>
<pre><code>FROM openjdk:8-jre

ADD build/distributions/MyPOP3Server.tar . #This is where I have packed all the needed files to. It gets unpacked by Docker.
#EXPOSE 24999 #I tried both with and without this expose
WORKDIR /MyPOP3Server/bin
ENTRYPOINT [&quot;sh&quot;,&quot;MyPOP3Server&quot;] #Executes the shell script which runs java with my jar
</code></pre>
<p>This is a simplified version of the code that is running inside the Server Jar:</p>
<pre><code>MyPOP3Server server = new MyPOP3Server();
server.listenToPort(24999);
</code></pre>
<p>Please tell me what am I missing. What is wrong here?</p>
<p>Thanks and kind regards.</p>
",https://stackoverflow.com/questions/58202705/java-testcontainers-cannot-connect-to-exposed-port,"['java', 'docker', 'junit', 'dockerfile', 'testcontainers']",14277,True,4,5
